Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
Product audit: provisioning, render, captions, MCP, studio, onboarding, nightly e2e (#108)
Nika Siradzeb1f00f61109a
diff --git a/.claude/commands/auto.md b/.claude/commands/auto.mdindex d3516ca..73e9ebd 100644--- a/.claude/commands/auto.md+++ b/.claude/commands/auto.md@@ -21,7 +21,7 @@ This command orchestrates the existing MCP tools on top of the compact packed tr1. **Read, don't watch.** Reason about clips from the packed markdown view — not raw segments, not frame dumps.2. **Strategy first, render after.** Propose the cut list and WAIT for user confirmation before calling `batch_create_clips`.-3. **Knowledge base is context, not template.** If `.podcli/knowledge/` exists, read it for brand voice and format preferences. If not, infer from the content itself.+3. **Knowledge base is context, not template.** If `` exists, read it for brand voice and format preferences. If not, infer from the content itself.4. **Never silently render.** Every clip that ships must appear in the proposal the user approved.---@@ -48,7 +48,7 @@ This command orchestrates the existing MCP tools on top of the compact packed tr- Loop: call `transcribe_status(job_id, wait_seconds: 30)`. Between calls, emit ONE terse line to the user like `"Progress: 47% — pyannote diarization"`. Keep it to one line per poll — no repeat prose. Exit the loop when `done: true`.- If `status: "error"`, stop and report the error.3. Read the packed transcript: `get_ui_state(include_transcript: true)`. This returns a compact phrase-grouped view with speakers, silence gaps, and energy peaks.-4. If `.podcli/knowledge/` exists, read `01-brand-identity.md`, `02-voice-and-tone.md`, and `04-shorts-creation-guide.md` for show context. Skip silently if missing — `/auto` works on any content.+4. If `` exists, read `01-brand-identity.md`, `02-voice-and-tone.md`, and `04-shorts-creation-guide.md` for show context. Skip silently if missing — `/auto` works on any content.5. Call `clip_history` to see what's already been shipped for this episode. Avoid duplicates in the proposal.**Fallback**: if `transcribe_start` returns an error about the Web UI not running, tell the user and offer either (a) run `npm run ui` in another terminal then retry, or (b) fall back to the synchronous `transcribe_podcast` (no live progress, works silently).@@ -61,7 +61,7 @@ Emit a numbered strategy table. Do NOT render yet.Proposed strategy for <video-label> (<duration>, <N> speakers):Inferred format: <talking-head | interview | montage | tutorial | travel | other>-Inferred tone: <from voice fingerprint or knowledge/02>+Inferred tone: <from voice fingerprint or 02-voice-and-tone.md>Target count: <N> clips (from arg, or inferred from content density)#1 [00:04:22-00:05:01] 39s S0 "<hook>"diff --git a/.claude/commands/bootstrap-knowledge.md b/.claude/commands/bootstrap-knowledge.mdnew file mode 100644index 0000000..caad6f3--- /dev/null+++ b/.claude/commands/bootstrap-knowledge.md@@ -0,0 +1,57 @@+---+description: Draft the knowledge base from an existing channel, feed, or show description+allowed-tools: Read, Write, WebFetch, WebSearch, Bash+argument-hint: [channel-url-or-show-description]+triggers:+ - bootstrap knowledge+ - set up knowledge base+ - fill knowledge from channel+ - import my channel+ - new show setup+---++# /bootstrap-knowledge: knowledge base bootstrapper++> You turn an existing channel, podcast feed, or plain description of a show into a first draft of the knowledge base, so the owner edits instead of starting from blank templates.++---++## Before starting++1. If `` has no files, run `podcli knowledge init` first so all 14 templates exist.+2. Ask for whichever of these the user has not provided:+ - Channel or podcast URL (YouTube channel, Spotify show, RSS feed)+ - Or a few sentences about the show if nothing is published yet++## Research phase++From the channel URL, gather with WebFetch/WebSearch:++- Show name, tagline, and about text+- The 10-15 most recent episode titles and descriptions+- The 5 best-performing videos you can identify (views relative to channel size)+- Host names and how they describe themselves+- Recurring topics across episode titles+- Any shorts already published: their titles and hooks++If there is no published content, interview the user instead: format, audience, topics, tone, 3 shows they admire.++## Drafting phase++Fill these files with drafts, marking every inference with `<!-- draft: verify -->` where you are guessing:++| File | Draft from |+|------|-----------|+| `01-brand-identity.md` | About text, episode patterns, host info |+| `02-voice-and-tone.md` | Actual phrasing in titles and descriptions; propose banned words from cliches the niche overuses |+| `03-episodes-database.md` | The recent episode list, with links |+| `05-title-formulas.md` | Patterns extracted from their best-performing titles |+| `08-topics-themes.md` | Topic clusters across episodes |+| `11-inspiration-channels.md` | 3-5 comparable channels in the niche |+| `12-quick-reference.md` | Platform links found during research |++Leave `04`, `06`, `07`, `09`, `10`, `13` as templates unless the user gave you enough to draft them: those encode preferences research cannot infer.++## Handoff++End with a short list of the specific `[brackets]` and `<!-- draft: verify -->` marks the owner must confirm, ordered by how much they affect output quality (voice and banned words first).diff --git a/.claude/commands/generate-descriptions.md b/.claude/commands/generate-descriptions.mdindex 80fb486..2c49d32 100644--- a/.claude/commands/generate-descriptions.md+++ b/.claude/commands/generate-descriptions.md@@ -19,9 +19,9 @@ triggers:## Before StartingRead:-- `knowledge/06-descriptions-template.md` — templates, hashtag library, SEO keywords-- `knowledge/01-brand-identity.md` — show name, hosts, links-- `knowledge/02-voice-and-tone.md` — voice and banned words+- `06-descriptions-template.md` — templates, hashtag library, SEO keywords+- `01-brand-identity.md` — show name, hosts, links+- `02-voice-and-tone.md` — voice and banned words---diff --git a/.claude/commands/generate-titles.md b/.claude/commands/generate-titles.mdindex 58ed3f4..39224bc 100644--- a/.claude/commands/generate-titles.md+++ b/.claude/commands/generate-titles.md@@ -18,13 +18,11 @@ triggers:## Before Starting-Read the knowledge base:-- `knowledge/05-title-formulas.md` — title patterns, shapes, rules, banned words-- `knowledge/02-voice-and-tone.md` — voice fingerprint, The Coffee Test-- `knowledge/01-brand-identity.md` — show positioning-- `knowledge/13-learnings.md` — past title patterns that worked / didn't--If using podcli, replace `knowledge/` with `.podcli/knowledge/`.+Read the knowledge base with the `knowledge_base` MCP tool:+- `05-title-formulas.md` — title patterns, shapes, rules, banned words+- `02-voice-and-tone.md` — voice fingerprint, The Coffee Test+- `01-brand-identity.md` — show positioning+- `13-learnings.md` — past title patterns that worked / didn't---@@ -81,7 +79,7 @@ For EVERY title:| **For Whom Test** | Can you name who would stop scrolling? || **Payoff Check** | Does the clip deliver what the title promises? || **Hook Alignment** | Is the core tension visible in first 3 seconds? |-| **Banned Words** | Zero banned words from `knowledge/02-voice-and-tone.md` |+| **Banned Words** | Zero banned words from `02-voice-and-tone.md` || **Length** | Under 70 characters. Main keyword in first 3 words. |### Step 7: Flag Top 2 and Output@@ -95,7 +93,7 @@ For EVERY title:- **5-11 words**. One clear idea per title.### Four Default Shapes-(Check `knowledge/05-title-formulas.md` for show-specific shapes)+(Check `05-title-formulas.md` for show-specific shapes)| Shape | Pattern | Example ||-------|---------|---------|diff --git a/.claude/commands/plan-episode.md b/.claude/commands/plan-episode.mdindex 505f130..b90f3e1 100644--- a/.claude/commands/plan-episode.md+++ b/.claude/commands/plan-episode.md@@ -19,16 +19,14 @@ triggers:## Before Starting-Read the knowledge base:-- `knowledge/01-brand-identity.md` — show positioning, what makes it unique-- `knowledge/02-voice-and-tone.md` — voice fingerprint, what resonates with the audience-- `knowledge/03-episodes-database.md` — past episodes (avoid repetition, find gaps)-- `knowledge/05-title-formulas.md` — title patterns (design questions that produce title-worthy answers)-- `knowledge/08-topics-themes.md` — core topics, audience interests-- `knowledge/11-inspiration-channels.md` — reference channels and what they do well-- `knowledge/13-learnings.md` — what consistently works / doesn't across past episodes--If using podcli, replace `knowledge/` with `.podcli/knowledge/`.+Read the knowledge base with the `knowledge_base` MCP tool:+- `01-brand-identity.md` — show positioning, what makes it unique+- `02-voice-and-tone.md` — voice fingerprint, what resonates with the audience+- `03-episodes-database.md` — past episodes (avoid repetition, find gaps)+- `05-title-formulas.md` — title patterns (design questions that produce title-worthy answers)+- `08-topics-themes.md` — core topics, audience interests+- `11-inspiration-channels.md` — reference channels and what they do well+- `13-learnings.md` — what consistently works / doesn't across past episodes---@@ -127,7 +125,7 @@ For each planned moment, draft 2-3 title options BEFORE recording. This gives th### Step 7: Apply Learnings-Read `knowledge/13-learnings.md` and adjust:+Read `13-learnings.md` and adjust:- Prefer question types that have produced high-performing shorts in past retros- Avoid patterns flagged as "consistently doesn't work"- Consider testing one Open Question if relevant@@ -209,7 +207,7 @@ Read `knowledge/13-learnings.md` and adjust:----## Applied Learnings (from knowledge/13-learnings.md)+## Applied Learnings (from 13-learnings.md)- [Pattern applied in this plan] → [which question/moment uses it]- [Pattern avoided] → [what we're doing instead]diff --git a/.claude/commands/plan-thumbnails.md b/.claude/commands/plan-thumbnails.mdindex 11edf6f..a665161 100644--- a/.claude/commands/plan-thumbnails.md+++ b/.claude/commands/plan-thumbnails.md@@ -19,8 +19,8 @@ triggers:## Before StartingRead:-- `knowledge/07-thumbnail-guide.md` — layouts, colors, typography, examples-- `knowledge/01-brand-identity.md` — brand positioning and visual identity+- `07-thumbnail-guide.md` — layouts, colors, typography, examples+- `01-brand-identity.md` — brand positioning and visual identity---@@ -34,7 +34,7 @@ Read:- **Max:** 4-6 words total across both lines- **Feel:** Conversational, would-actually-say-this-**Layout elements** (customize per `knowledge/07-thumbnail-guide.md`):+**Layout elements** (customize per `07-thumbnail-guide.md`):- Border/frame treatment- Dark or branded background- Guest photo placement@@ -59,7 +59,7 @@ For each moment/clip:What is the single most compelling image or concept?### Step 2: Write Two-Line Text-- **Podcast version:** Based on show style from `knowledge/07-thumbnail-guide.md`+- **Podcast version:** Based on show style from `07-thumbnail-guide.md`- **Shorts version:** ALL CAPS, urgent, Line 2 = payoff### Step 3: Specify Layoutdiff --git a/.claude/commands/process-transcript.md b/.claude/commands/process-transcript.mdindex 587d923..a5bbc96 100644--- a/.claude/commands/process-transcript.md+++ b/.claude/commands/process-transcript.md@@ -18,15 +18,13 @@ triggers:## Before Starting-Read the knowledge base to understand this show's brand, voice, and existing content:-- `knowledge/01-brand-identity.md` — who the show is, positioning-- `knowledge/02-voice-and-tone.md` — voice fingerprint, banned words-- `knowledge/03-episodes-database.md` — existing episodes (avoid duplicates)-- `knowledge/04-shorts-creation-guide.md` — moment selection criteria-- `knowledge/05-title-formulas.md` — title patterns-- `knowledge/13-learnings.md` — patterns from past retros--If using podcli, replace `knowledge/` with `.podcli/knowledge/`.+Read the knowledge base with the `knowledge_base` MCP tool to understand this show's brand, voice, and existing content:+- `01-brand-identity.md` — who the show is, positioning+- `02-voice-and-tone.md` — voice fingerprint, banned words+- `03-episodes-database.md` — existing episodes (avoid duplicates)+- `04-shorts-creation-guide.md` — moment selection criteria+- `05-title-formulas.md` — title patterns+- `13-learnings.md` — patterns from past retros---@@ -104,7 +102,7 @@ For every flagged moment, score on four dimensions (1-5 each):### Phase 5: Check for Duplicates-Read `knowledge/03-episodes-database.md` and verify no selected moments overlap with existing shorts.+Read `03-episodes-database.md` and verify no selected moments overlap with existing shorts.### Phase 6: Extract Keywords@@ -175,7 +173,7 @@ For every moment included:- [ ] Hook lands in first 3 seconds- [ ] Single focused idea, fully delivered- [ ] Would share this clip independently-- [ ] No banned words (check `knowledge/02-voice-and-tone.md`)+- [ ] No banned words (check `02-voice-and-tone.md`)- [ ] Titles match the show's voice- [ ] Thumbnail text is 4-6 words max, two-line formatdiff --git a/.claude/commands/produce-shorts.md b/.claude/commands/produce-shorts.mdindex 7175983..6c96d15 100644--- a/.claude/commands/produce-shorts.md+++ b/.claude/commands/produce-shorts.md@@ -19,15 +19,15 @@ triggers:## Before Starting-Read the full knowledge base to understand the show:-- `knowledge/01-brand-identity.md` — who the show is-- `knowledge/02-voice-and-tone.md` — voice, banned words-- `knowledge/03-episodes-database.md` — existing content (dedup)-- `knowledge/04-shorts-creation-guide.md` — moment criteria-- `knowledge/05-title-formulas.md` — title spec-- `knowledge/06-descriptions-template.md` — description templates-- `knowledge/07-thumbnail-guide.md` — visual specs-- `knowledge/13-learnings.md` — past retro patterns (what worked, what didn't)+Read the full knowledge base with the `knowledge_base` MCP tool:+- `01-brand-identity.md` — who the show is+- `02-voice-and-tone.md` — voice, banned words+- `03-episodes-database.md` — existing content (dedup)+- `04-shorts-creation-guide.md` — moment criteria+- `05-title-formulas.md` — title spec+- `06-descriptions-template.md` — description templates+- `07-thumbnail-guide.md` — visual specs+- `13-learnings.md` — past retro patterns (what worked, what didn't)---@@ -214,7 +214,7 @@ Each phase consumes upstream output and passes structured state downstream. Phas## Post-Pipeline-1. **Update episode database:** Add to `knowledge/03-episodes-database.md`+1. **Update episode database:** Add to `03-episodes-database.md`2. **Save package:** Write to `episodes/ep[XX]-[guest]-content-package.md`3. **Posting order:** Vary topics, lead with strongest hooks, mix energy levelsdiff --git a/.claude/commands/retro-episode.md b/.claude/commands/retro-episode.mdindex 273b94f..1d1cb4e 100644--- a/.claude/commands/retro-episode.md+++ b/.claude/commands/retro-episode.md@@ -13,7 +13,7 @@ triggers:# /retro-episode — Analyst-> You are the performance analyst. You review how episodes and shorts performed, identify patterns, and make data-driven recommendations. You also **persist learnings** to `knowledge/13-learnings.md` so future episodes benefit.+> You are the performance analyst. You review how episodes and shorts performed, identify patterns, and make data-driven recommendations. You also **persist learnings** to `13-learnings.md` so future episodes benefit.---@@ -24,7 +24,7 @@ triggers:| Episode number | User specifies || Performance data | User provides from YouTube Studio || Previous retros | Check `episodes/` for past retros |-| Existing learnings | Read `knowledge/13-learnings.md` before writing new ones |+| Existing learnings | Read `13-learnings.md` before writing new ones |---@@ -61,7 +61,7 @@ Compare against previous episodes:## Learnings Persistence (Critical)-After every retro, append any **new, repeatable** pattern to `knowledge/13-learnings.md`. Follow the entry format:+After every retro, append any **new, repeatable** pattern to `13-learnings.md`. Follow the entry format:```markdown- **[Pattern stated as a rule]** ([evidence: episode numbers, metrics]) → [action to take next time]@@ -135,7 +135,7 @@ Rules for appending:## Learnings File Updates-Appended to `knowledge/13-learnings.md`:+Appended to `13-learnings.md`:- [Entry 1]- [Entry 2]diff --git a/.claude/commands/review-content.md b/.claude/commands/review-content.mdindex 43a8709..eb13c42 100644--- a/.claude/commands/review-content.md+++ b/.claude/commands/review-content.md@@ -20,10 +20,10 @@ triggers:## Before StartingRead:-- `knowledge/02-voice-and-tone.md` — voice fingerprint, banned words-- `knowledge/05-title-formulas.md` — title rules and shapes-- `knowledge/01-brand-identity.md` — brand positioning-- `knowledge/13-learnings.md` — patterns from past retros (what worked, what didn't)+- `02-voice-and-tone.md` — voice fingerprint, banned words+- `05-title-formulas.md` — title rules and shapes+- `01-brand-identity.md` — brand positioning+- `13-learnings.md` — patterns from past retros (what worked, what didn't)---@@ -47,12 +47,12 @@ Dispatch subagents in parallel, each owning one dimension. Each returns a findin| Specialist | Owns | Always run? ||-----------|------|-------------|| **Voice Check** | Coffee Test, tone fingerprint match | Yes |-| **Banned Words** | Exact scan against `knowledge/02-voice-and-tone.md` | Yes |+| **Banned Words** | Exact scan against `02-voice-and-tone.md` | Yes || **Title Review** | Length, keyword-first, shape, anchor presence, no tension-without-payoff | If titles in package || **Standalone Check** | Each short makes sense without the episode | If shorts in package || **Clickbait Detector** | Title promises something the clip can't deliver | If titles + clips both in package || **SEO / Hashtags** | Description hashtags count, show hashtag present, keyword coverage | If descriptions in package |-| **Duplication Check** | Cross-reference `knowledge/03-episodes-database.md` | If moments/shorts in package |+| **Duplication Check** | Cross-reference `03-episodes-database.md` | If moments/shorts in package |Run specialists concurrently via `Task`. Collect findings, then merge with **deduplication**: if two specialists flag the same span/field, merge into one finding and raise confidence by +1 (cap 10). Tag `MULTI-SPECIALIST`.diff --git a/.env.example b/.env.exampleindex 1319101..3e17208 100644--- a/.env.example+++ b/.env.example@@ -5,7 +5,11 @@FFMPEG_PATH=FFPROBE_PATH=-# Python path (leave blank to auto-detect venv)+# Python interpreter override (leave blank to use the managed runtime or venv)+PODCLI_PYTHON=++# Resolved internal value the launcher exports for the TypeScript layer.+# Set PODCLI_PYTHON instead; only set this when running the TS server directly.PYTHON_PATH=# Config home: knowledge, presets, assets, history@@ -24,7 +28,7 @@ PODCLI_QUALITY=high# Transition QA/autofix passes (0=off, 1-2 allowed; renderer hard-caps at 2)PODCLI_TRANSITION_AUTOFIX_PASSES=2-PORT=3847 # Web UI port+PODCLI_PORT=3847 # Web studio port (PORT also works)# Logging verbosity: debug, info, warn, errorPODCLI_LOG_LEVEL=infodiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 43e8772..3306a80 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -3,8 +3,9 @@ name: CIon:push:branches: [main]+ # Any base, not just main: a stacked PR targets the branch below it and would+ # otherwise merge with no CI of its own.pull_request:- branches: [main]jobs:go:@@ -15,8 +16,10 @@ jobs:matrix:os: [ubuntu-latest, macos-latest, windows-latest]steps:- - uses: actions/checkout@v7- - uses: actions/setup-go@v5+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0with:go-version: '1.23'cache: false # stdlib-only module: no go.sum to key a cache on@@ -42,8 +45,10 @@ jobs:matrix:os: [ubuntu-latest, macos-latest, windows-latest]steps:- - uses: actions/checkout@v7- - uses: actions/setup-node@v4+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0with:node-version: "20"cache: "npm"@@ -52,14 +57,31 @@ jobs:- run: npm test- run: npm run build+ remotion-bundle:+ name: Remotion release bundle+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020+ with:+ node-version: "20"+ cache: "npm"+ cache-dependency-path: remotion/package-lock.json+ - run: sh scripts/build-remotion.sh dist/remotion-bundle+ - working-directory: dist/remotion-bundle+ run: node --input-type=module --eval "await Promise.all(['@remotion/bundler', '@remotion/renderer', 'remotion', 'react', 'react-dom'].map((name) => import(name))); import.meta.resolve('@fontsource/dm-sans/400.css')"+docs-drift:name: Docs drift checkruns-on: ubuntu-lateststeps:- - uses: actions/checkout@v7+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0with:+ persist-credentials: falsefetch-depth: 0- - uses: actions/setup-node@v4+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0with:node-version: "20"- run: node scripts/gen-docs-manifest.mjs@@ -73,8 +95,10 @@ jobs:matrix:os: [ubuntu-latest, macos-latest, windows-latest]steps:- - uses: actions/checkout@v7- - uses: actions/setup-python@v6+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0with:python-version: "3.12"cache: "pip"diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.ymlnew file mode 100644index 0000000..3b661bc--- /dev/null+++ b/.github/workflows/nightly.yml@@ -0,0 +1,73 @@+# CI only ran unit tests, so a change could break the render pipeline and still+# go green: nothing in the pipeline ever produced a clip. This renders real ones.+# Nightly rather than per-PR because it installs ffmpeg and a headless browser.+name: nightly++on:+ schedule:+ - cron: '0 4 * * *'+ workflow_dispatch:++permissions:+ contents: read++jobs:+ render:+ name: End-to-end render+ runs-on: ${{ matrix.os }}+ timeout-minutes: 45+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0+ with:+ node-version: '20'+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0+ with:+ python-version: '3.12'++ - name: Install ffmpeg+ shell: bash+ run: |+ case "${{ runner.os }}" in+ Linux) sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg ;;+ macOS) brew install --quiet ffmpeg ;;+ Windows) choco install ffmpeg -y --no-progress ;;+ esac+ ffmpeg -version | head -1++ - name: Install dependencies+ shell: bash+ run: |+ npm ci+ python -m pip install --upgrade pip+ pip install numpy Pillow python-dotenv opencv-python-headless++ # The caption renderer runs in a headless browser Remotion downloads on+ # first use; failing here is a real failure, not a flake to retry away.+ - name: Render a clip per caption style+ shell: bash+ run: |+ for style in branded hormozi karaoke subtle; do+ echo "::group::$style"+ python scripts/e2e_render.py "$style"+ echo "::endgroup::"+ done++ - name: Render the caption compositions directly+ shell: bash+ run: node remotion/test-render.mjs branded++ - name: Upload the failed render for inspection+ if: failure()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: e2e-render-${{ matrix.os }}+ path: e2e-artifacts/+ retention-days: 7+ if-no-files-found: ignorediff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 24ceef3..a895331 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,6 +1,8 @@-# Cuts a release on a v* tag: cross-compiles the Go launcher for all 5 targets,-# builds whisper.cpp per platform, publishes both as release assets (the names-# the npm wrapper, self-update, and provisioner expect), then publishes npm.+# Cuts a release on a v* tag: cross-compiles the Go launcher for the 4 targets+# in the build matrix, builds whisper.cpp / ffmpeg / studio / remotion bundles+# per platform, and publishes everything as release assets (the names+# self-update and the provisioner expect). Distribution is the install script+# plus these assets; there is no npm publish (the name is blocked, see RELEASE.md).## The whisper.cpp matrix below is unverified until the first tagged run — the# binary name / cmake flags may need adjustment for the pinned whisper.cpp ref.@@ -29,10 +31,13 @@ jobs:- { runner: ubuntu-latest, goos: linux, goarch: arm64 }- { runner: ubuntu-latest, goos: windows, goarch: amd64 }steps:- - uses: actions/checkout@v7- - uses: actions/setup-go@v5+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0with:go-version: '1.23'+ cache: false- name: Build launcherworking-directory: clienv:@@ -54,7 +59,7 @@ jobs:OUT="podcli-${{ matrix.goos }}-${{ matrix.goarch }}${EXT}"go build -trimpath -ldflags "-s -w" -o "../${OUT}" .echo "ASSET=${OUT}" >> "$GITHUB_ENV"- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: ${{ env.ASSET }}path: ${{ env.ASSET }}@@ -73,10 +78,11 @@ jobs:WHISPER_REF: v1.7.4 # pin a known-good whisper.cpp tagsteps:- name: Clone whisper.cpp- uses: actions/checkout@v7+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0with:repository: ggml-org/whisper.cppref: ${{ env.WHISPER_REF }}+ persist-credentials: false- name: Build (static; Metal embedded on macOS)shell: bashrun: |@@ -92,7 +98,7 @@ jobs:OUT="whisper-cli-${{ matrix.goos }}-${{ matrix.goarch }}${EXT}"cp "$SRC" "$OUT"echo "ASSET=$OUT" >> "$GITHUB_ENV"- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: ${{ env.ASSET }}path: ${{ env.ASSET }}@@ -164,7 +170,7 @@ jobs:for enc in libx264 h264_videotoolbox; do./ffmpeg-darwin-arm64 -hide_banner -encoders | grep -q "$enc" || { echo "missing encoder: $enc"; exit 1; }done- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: ffmpeg-darwin-arm64path: |@@ -174,17 +180,20 @@ jobs:studio:runs-on: ubuntu-lateststeps:- - uses: actions/checkout@v7- - uses: actions/setup-node@v4+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0with:node-version: '20'+ cache: ''- name: Build studio bundlerun: |npm version --no-git-tag-version --allow-same-version "${GITHUB_REF_NAME#v}"npm cish scripts/build-studio.sh dist/studiotar -czf studio-bundle.tar.gz -C dist/studio .- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: studio-bundle.tar.gzpath: studio-bundle.tar.gz@@ -202,10 +211,13 @@ jobs:- { runner: windows-latest, goos: windows, goarch: amd64 }runs-on: ${{ matrix.runner }}steps:- - uses: actions/checkout@v7- - uses: actions/setup-node@v4+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0with:node-version: '20'+ cache: ''- name: Build remotion bundleshell: bashrun: |@@ -213,7 +225,7 @@ jobs:OUT="remotion-bundle-${{ matrix.goos }}-${{ matrix.goarch }}.tar.gz"tar -czf "$OUT" -C dist/remotion-bundle .echo "ASSET=$OUT" >> "$GITHUB_ENV"- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: ${{ env.ASSET }}path: ${{ env.ASSET }}@@ -226,7 +238,7 @@ jobs:env:LANDING_DISPATCH_TOKEN: ${{ secrets.LANDING_DISPATCH_TOKEN }}steps:- - uses: actions/download-artifact@v8+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1with:path: distmerge-multiple: true@@ -235,10 +247,35 @@ jobs:run: |sha256sum * > "$RUNNER_TEMP/checksums.txt"mv "$RUNNER_TEMP/checksums.txt" checksums.txt- - uses: softprops/action-gh-release@v3+ - name: Assert the release asset set is complete+ working-directory: dist+ run: |+ set -eu+ expected="podcli-darwin-arm64 podcli-linux-amd64 podcli-linux-arm64 podcli-windows-amd64.exe \+ whisper-cli-darwin-arm64 whisper-cli-linux-amd64 whisper-cli-linux-arm64 whisper-cli-windows-amd64.exe \+ remotion-bundle-darwin-arm64.tar.gz remotion-bundle-linux-amd64.tar.gz remotion-bundle-linux-arm64.tar.gz remotion-bundle-windows-amd64.tar.gz \+ ffmpeg-darwin-arm64 ffprobe-darwin-arm64 studio-bundle.tar.gz checksums.txt"+ fail=0+ for f in $expected; do+ [ -f "$f" ] || { echo "::error::missing release asset: $f"; fail=1; }+ done+ for f in $expected; do+ [ "$f" = checksums.txt ] && continue+ grep -q " $f\$" checksums.txt || { echo "::error::checksums.txt has no entry for $f"; fail=1; }+ done+ # An unlisted file would be published unreviewed; treat it as a failure too.+ for f in *; do+ case " $expected " in *" $f "*) ;; *) echo "::error::unexpected file in dist/: $f"; fail=1 ;; esac+ done+ [ "$fail" -eq 0 ] || { echo "::error::release asset set is incomplete or wrong; refusing to publish"; exit 1; }+ echo "all 16 release assets present, every binary checksummed"+ - uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1with:files: dist/*generate_release_notes: true+ - name: Warn that the landing changelog will not rebuild+ if: ${{ env.LANDING_DISPATCH_TOKEN == '' }}+ run: echo "::warning::LANDING_DISPATCH_TOKEN is unset; skipping the landing site dispatch, so podcli.com's changelog will not pick up ${GITHUB_REF_NAME}."- name: Rebuild the landing site so the changelog picks up this releaseif: ${{ env.LANDING_DISPATCH_TOKEN != '' }}run: |diff --git a/.gitignore b/.gitignoreindex 71a1b23..7f3afdd 100644--- a/.gitignore+++ b/.gitignore@@ -20,6 +20,7 @@ data/.podcli/.podcli-homepresets/+e2e-artifacts/# Environment.envdiff --git a/AGENTS.podstack.md b/AGENTS.podstack.mdindex a046563..a1bae00 100644--- a/AGENTS.podstack.md+++ b/AGENTS.podstack.md@@ -1,46 +1,26 @@-# AGENTS.md — PodStack+# AGENTS.podstack.md: cross-tool entry point for PodStack skills-> Cross-tool entry point for PodStack skills.->-> This file is the **primary instruction document** for AI coding tools that read `AGENTS.md` by convention (OpenAI Codex, opencode, Aider, Cursor Agent, and others). Claude Code uses `CLAUDE.md` as its primary but also reads `AGENTS.md` as a secondary index.+> This file is the instruction document for AI coding tools that read `AGENTS.md` by convention (OpenAI Codex, opencode, Aider, Cursor Agent, and others). Claude Code uses `CLAUDE.md` as its primary; the command index, pipeline, MCP tool table, knowledge base table (14 files at `.podcli/knowledge/`), and quality gate live there and are not repeated here.PodStack turns your AI tool into a podcast content team: Episode Architect, Content Analyst, Title Writer, Copywriter, Art Director, Brand Guardian, Producer, Launch Manager, and Performance Analyst.----## How To Use+## How to use-Each skill below is a self-contained instruction file in `commands/` (or `.claude/commands/`, `.codex/prompts/`, `.cursor/rules/`, `.opencode/commands/` — depending on which host installed it).+Each skill below is a self-contained instruction file in `commands/` (or `.claude/commands/`, `.codex/prompts/`, `.cursor/rules/`, `.opencode/commands/`, depending on which host installed it).**To run a skill:** ask your agent to "run the [skill-name] skill" or invoke its slash command (`/[skill-name]`) where supported. The agent opens the corresponding file and follows it step by step.**Natural-language triggers:** each skill's `triggers:` list describes phrases that should auto-route to it. If the user's message matches one, run that skill without asking.-**Completion Protocol:** every skill ends its output with one of:-- `DONE` — all quality gates passed-- `DONE_WITH_CONCERNS` — shipped, but flag non-blocking issues with evidence-- `BLOCKED` — cannot complete; state blocker + what's needed to unblock-- `NEEDS_INPUT` — one specific missing input; ask the question and wait+**Completion protocol:** every skill ends its output with one of:+- `DONE`: all quality gates passed+- `DONE_WITH_CONCERNS`: shipped, but flag non-blocking issues with evidence+- `BLOCKED`: cannot complete; state blocker + what's needed to unblock+- `NEEDS_INPUT`: one specific missing input; ask the question and wait-**Three-Strike Rule:** orchestrators (`/produce-shorts`) stop after 3 consecutive phase failures and return `BLOCKED` rather than looping.-------## Sprint Workflow--PodStack is a process, not a collection of tools. Skills run in the order a content sprint runs:--```-Plan → Process → Write → Review → Publish → Retro-```--```-/plan-episode → [record] → /process-transcript → /generate-titles → /generate-descriptions- ↓- /retro-episode ← [published] ← /publish-checklist ← /review-content ← /plan-thumbnails-```--Or run the full post-record pipeline at once: `/produce-shorts`.+**Three-strike rule:** orchestrators (`/produce-shorts`) stop after 3 consecutive phase failures and return `BLOCKED` rather than looping.---@@ -104,7 +84,7 @@ Or run the full post-record pipeline at once: `/produce-shorts`.- **triggers:** process episode, produce shorts, full pipeline, prep episode, make content package- **outputs:** complete content package in `episodes/ep[XX]-[guest]-content-package.md`- **orchestrates:** process-transcript → generate-titles → generate-descriptions → plan-thumbnails → review-content-- **stop-rule:** Three-Strike Rule (BLOCKED after 3 consecutive phase failures)+- **stop-rule:** three-strike rule (BLOCKED after 3 consecutive phase failures)### /publish-checklist@@ -120,66 +100,34 @@ Or run the full post-record pipeline at once: `/produce-shorts`.- **description:** Analyze published performance; append patterns to learnings file- **allowed-tools:** Read, Write, Edit- **triggers:** retro, episode review, analytics, what worked, post-mortem-- **outputs:** retro report written to `episodes/ep[XX]-[guest]-retro.md` + patterns appended to `knowledge/13-learnings.md`-------## Knowledge Base--Skill files reference these knowledge files (default location: `knowledge/`, or `.podcli/knowledge/` with podcli):--| File | Contents |-|------|----------|-| `00-master-instructions.md` | AI operating system — routing, decision tree |-| `01-brand-identity.md` | Show positioning, hosts, format |-| `02-voice-and-tone.md` | Voice fingerprint, banned words |-| `03-episodes-database.md` | Episode tracking, existing shorts log |-| `04-shorts-creation-guide.md` | Moment selection criteria |-| `05-title-formulas.md` | Title spec — shapes, rules |-| `06-descriptions-template.md` | Description formulas, hashtags |-| `07-thumbnail-guide.md` | Layouts, colors, typography |-| `08-topics-themes.md` | Core topics, audience mapping |-| `09-content-workflow.md` | End-to-end workflow phases |-| `10-internal-processing.md` | Internal quality gates |-| `11-inspiration-channels.md` | Reference channels, viral hooks |-| `12-quick-reference.md` | Copy-paste hooks, CTAs, checklists |-| `13-learnings.md` | Cross-episode learnings (auto-updated by `/retro-episode`) |+- **outputs:** retro report written to `episodes/ep[XX]-[guest]-retro.md` + patterns appended to `.podcli/knowledge/13-learnings.md`----## Quality Gate (Always Active)--Before outputting ANY content, verify:--1. **Would I click this?** — If no, rewrite-2. **Does it earn attention in 5 seconds?** — If no, find a better hook-3. **Does it deliver on the promise?** — If no, it's clickbait-4. **Is it standalone?** — If context needed, unusable for shorts-5. **Zero banned words** — Check `02-voice-and-tone.md`-6. **The Coffee Test** — Sounds like a person, not a press release+## Knowledge base and quality gate-Full philosophy in `ETHOS.md`.+Skill files read the 14 knowledge files at `.podcli/knowledge/`; the full file table and the always-active quality gate are in `CLAUDE.md`. Full content philosophy in `ETHOS.podstack.md`.----## Host Compatibility+## Host compatibilityPodStack ships one source-of-truth (`commands/`) and installs to the right location for each tool:| Host | Install location | Primary doc ||------|-----------------|-------------|| Claude Code | `.claude/commands/*.md` | `CLAUDE.md` |-| OpenAI Codex | `.codex/prompts/*.md` | `AGENTS.md` (this file) |-| Cursor | `.cursor/rules/*.mdc` | `AGENTS.md` |-| opencode | `.opencode/commands/*.md` | `AGENTS.md` |-| Generic | `commands/*.md` | `AGENTS.md` |+| OpenAI Codex | `.codex/prompts/*.md` | `AGENTS.podstack.md` (this file) |+| Cursor | `.cursor/rules/*.mdc` | `AGENTS.podstack.md` |+| opencode | `.opencode/commands/*.md` | `AGENTS.podstack.md` |+| Generic | `commands/*.md` | `AGENTS.podstack.md` |These command files ship with podcli; place the set for your tool (left column) inits command dir. See `README.md` for per-host usage examples.----## One Rule+## One rule> **Earn attention in 5 seconds. Deliver value that matches the promise.**diff --git a/CLAUDE.md b/CLAUDE.mdindex fa3ac3d..5b9ea42 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,19 +1,21 @@-# podcli + PodStack — AI Podcast Content Studio+# podcli + PodStack: AI podcast content studio-> Transcribe, clip, and publish — all from one place.+> Transcribe, clip, and publish from one place.++This file is the primary instruction document. `CLAUDE.podstack.md` (persona and protocols), `AGENTS.podstack.md` (cross-tool usage), and `ETHOS.podstack.md` (content philosophy) build on it; the tables below are the single source of truth.You have two systems working together:-1. **podcli** — video processing engine (transcription, clip detection, rendering)-2. **PodStack** — content workflow (titles, descriptions, thumbnails, publishing)+1. **podcli**: video processing engine (transcription, clip detection, rendering)+2. **PodStack**: content workflow (titles, descriptions, thumbnails, publishing)Both share the same knowledge base at `.podcli/knowledge/`.----## Slash Commands (PodStack)+## Slash commands (PodStack)-| Command | Role | What It Does |+| Command | Role | What it does ||---------|------|-------------|| `/plan-episode` | Episode Architect | Pre-recording: designs questions, story arc, and target moments backwards from ideal output || `/process-transcript` | Content Analyst | Ingests transcript → extracts 8-15 moments → scores → categorizes |@@ -23,25 +25,63 @@ Both share the same knowledge base at `.podcli/knowledge/`.| `/review-content` | Brand Guardian | Reviews output against brand voice, quality gates, banned words || `/produce-shorts` | Producer | Full pipeline: transcript → publish-ready package || `/publish-checklist` | Launch Manager | Pre/post-publish optimization checklist |-| `/retro-episode` | Analyst | Episode performance review + learnings |+| `/retro-episode` | Analyst | Episode performance review + appends learnings to `.podcli/knowledge/13-learnings.md` |----## MCP Tools (podcli engine)+## MCP tools (podcli engine)++All 26 tools registered by the MCP server.++**Transcription and input**++| Tool | What it does |+|------|-------------|+| `transcribe_podcast` | Transcribe audio/video with Whisper word timestamps + speaker detection |+| `transcribe_start` | Start transcription as a background job, returns a job_id immediately |+| `job_status` | Poll any background job (transcription, render, batch export) with long-polling |+| `set_video` | Set the working video without transcribing |+| `import_transcript` | Import an external transcript with word-level timestamps, skips Whisper |+| `parse_transcript` | Parse a speaker-labeled plain text transcript into word-level timestamps |++**Clip workflow**-| Tool | What It Does |+| Tool | What it does ||------|-------------|-| `transcribe_podcast` | Transcribe audio/video with Whisper + speaker detection |-| `suggest_clips` | Submit clip suggestions with duplicate check |-| `create_clip` | Render a single short-form clip (9:16, captions, audio norm) |+| `get_ui_state` | Read session state (video, transcript, suggestions, settings) and next steps |+| `suggest_clips` | Submit clip suggestions, assigns clip numbers, pushes them to the web UI |+| `modify_clip` | Adjust a suggested clip: timing, title, caption style, or delete it |+| `toggle_clip` | Select or deselect a suggested clip for export |+| `create_clip` | Render a single clip with burned-in captions and normalized audio || `batch_create_clips` | Render multiple clips in one batch |-| `knowledge_base` | Read/write `.podcli/knowledge/` context files |-| `manage_assets` | Register/list logos, intros, outros |-| `clip_history` | View generated clips, check for duplicates |+| `manage_reel` | Build a highlights reel: detect once, edit moments, rebuild without re-detecting |+| `analyze_energy` | Analyze audio energy levels to find high-energy moments |++**Content and configuration**++| Tool | What it does |+|------|-------------|+| `knowledge_base` | Read or manage the `.podcli/knowledge/` context files |+| `manage_assets` | Register and manage reusable assets: logos, intros, outros, music |+| `clip_history` | View previously created clips to avoid duplicates |+| `list_outputs` | List rendered clip files with sizes and dates |+| `update_settings` | Update rendering settings: caption style, crop strategy, logo, outro |+| `manage_presets` | Save, load, list, or delete rendering presets |+| `manage_thumbnail_config` | Show, export, import, or reset the thumbnail template |++**Integrations and environment**++| Tool | What it does |+|------|-------------|+| `manage_integrations` | List, enable, or disable podcli integrations |+| `export_to_davinci_resolve` | Export shorts as a DaVinci Resolve FCPXML project |+| `manage_config` | Manage portable config profiles and legacy path migration |+| `manage_env` | List, set, or unset global podcli settings stored in `.env` |+| `ai_cli_status` | Show whether Claude Code / Codex CLIs are available for AI features |----## The Full Pipeline+## The full pipeline```/plan-episode → Record → /produce-shorts → Published content@@ -56,11 +96,11 @@ After publishing: `/retro-episode`----## Knowledge Base+## Knowledge base-All slash commands read from `.podcli/knowledge/`. This is where your show's brand, voice, and style live.+All slash commands read from `.podcli/knowledge/`. This is where your show's brand, voice, and style live. 14 files:-| File | What It Contains |+| File | What it contains ||------|-----------------|| `00-master-instructions.md` | AI operating system, auto-detection rules || `01-brand-identity.md` | Show name, positioning, hosts, format |@@ -75,23 +115,24 @@ All slash commands read from `.podcli/knowledge/`. This is where your show's bra| `10-internal-processing.md` | Auto-execution rules || `11-inspiration-channels.md` | Reference channels, viral hooks || `12-quick-reference.md` | Copy-paste resources |+| `13-learnings.md` | Cross-episode learnings, appended by `/retro-episode` |----## Quality Gate (Always Active)+## Quality gate (always active)Before outputting ANY content:-1. **Would I click this?** — If no, rewrite-2. **Does it earn attention in 5 seconds?** — If no, find better hook-3. **Does it deliver on the promise?** — If no, it's clickbait, fix it-4. **Is it standalone?** — If context needed, unusable for shorts-5. **Zero banned words** — Check `02-voice-and-tone.md`-6. **The Coffee Test** — Sounds like a person, not a press release+1. **Would I click this?** If no, rewrite+2. **Does it earn attention in 5 seconds?** If no, find better hook+3. **Does it deliver on the promise?** If no, it's clickbait, fix it+4. **Is it standalone?** If context needed, unusable for shorts+5. **Zero banned words**: check `02-voice-and-tone.md`+6. **The Coffee Test**: sounds like a person, not a press release----## Auto-Detection+## Auto-detectionWhen input is provided without a specific command:@@ -104,19 +145,20 @@ When input is provided without a specific command:----## Project Layout+## Project layout```-├── CLAUDE.md ← You are here+├── CLAUDE.md ← primary instructions (this file)├── .claude/commands/ ← PodStack slash commands-├── src/ ← TypeScript (MCP server, Web UI, services)+├── cli/ ← Go launcher (install, update, provisioning)+├── src/ ← TypeScript (MCP server, web studio, services)├── backend/ ← Python (Whisper, FFmpeg, captions)├── .podcli/-│ ├── knowledge/ ← Your show's brand brain (13 .md files)-│ ├── output/ ← Rendered clips-│ ├── history/ ← Clip tracking-│ ├── assets/ ← Logos, intros, outros-│ ├── cache/ ← Transcription cache-│ └── presets/ ← Saved configs-└── episodes/ ← Content packages (PodStack output)+│ ├── knowledge/ ← your show's brand brain (14 .md files)+│ ├── history/ ← clip tracking+│ ├── assets/ ← logos, intros, outros+│ └── presets/ ← saved configs+├── data/ ← runtime data: cache, working files (gitignored)+├── podcli-clips/ ← rendered clips (gitignored; PODCLI_OUTPUT overrides)+└── episodes/ ← content packages from PodStack (gitignored output)```diff --git a/CLAUDE.podstack.md b/CLAUDE.podstack.mdindex 28dffa6..9b529d2 100644--- a/CLAUDE.podstack.md+++ b/CLAUDE.podstack.md@@ -1,56 +1,26 @@-# PodStack — AI Podcast Content Studio+# PodStack: personas and protocols-> **One repo, one install, entire podcast content workflow.**+> One repo, one install, entire podcast content workflow.>-> This file is the Claude Code-specific primary doc. For cross-tool usage (Codex, Cursor, opencode, generic), see `AGENTS.md` — it contains the same command index and protocols in a host-agnostic form.+> `CLAUDE.md` is the primary instruction document: it holds the command index, pipeline, MCP tool table, knowledge base table, and quality gate. This file adds the working protocols behind those commands. For cross-tool usage (Codex, Cursor, opencode, generic), see `AGENTS.podstack.md`.You are the content production team for this podcast. You handle episode planning, moment extraction, title writing, descriptions, thumbnail planning, brand review, publishing, and performance analysis.----## Sprint Workflow+## Sprint workflow-PodStack is a process, not a collection of tools. The skills run in the order a content sprint runs:+PodStack is a process. The skills run in the order a content sprint runs:```Plan → Process → Write → Review → Publish → Retro```-Every skill feeds the next. Every skill returns a structured outcome (see Completion Protocol).+Every skill feeds the next. Every skill returns a structured outcome (see completion protocol). The full pipeline diagram and command index live in `CLAUDE.md`.----## Pipeline--```-/plan-episode → [record] → /process-transcript → /generate-titles → /generate-descriptions- ↓- /retro-episode ← [published] ← /publish-checklist ← /review-content ← /plan-thumbnails-```--Or run the full post-record pipeline at once: `/produce-shorts`-------## Skills (Slash Commands)--Each skill has YAML frontmatter with `description`, `allowed-tools`, and `triggers`. Claude Code uses these for routing.--| Command | Role | What It Does |-|---------|------|-------------|-| `/plan-episode` | Episode Architect | Designs the episode BEFORE recording — questions, story arc, moment map |-| `/process-transcript` | Content Analyst | Ingests transcript → extracts 8-15 moments → scores → categorizes |-| `/generate-titles` | Title Writer | Generates 8 title options with full verification checklist |-| `/generate-descriptions` | Copywriter | Creates descriptions + hashtags + SEO keywords |-| `/plan-thumbnails` | Art Director | Plans thumbnail text + layout briefs for podcast and shorts formats |-| `/review-content` | Brand Guardian | Fix-First review — auto-fixes + flags what needs human decision |-| `/produce-shorts` | Producer | Runs the full pipeline: transcript → publish-ready package |-| `/publish-checklist` | Launch Manager | Pre-publish, post-publish, and day 3-4 optimization checklist |-| `/retro-episode` | Analyst | Performance review + appends learnings to `knowledge/13-learnings.md` |-------## Completion Protocol (Every Skill)+## Completion protocol (every skill)Every skill returns one of four outcomes at the end of its output:@@ -63,88 +33,23 @@ Every skill returns one of four outcomes at the end of its output:Never report DONE if a blocking quality gate failed. Never report DONE with silent concerns.-**Three-Strike Rule:** If a phase (moment extraction, title generation, etc.) fails to produce valid output 3 times in a row, stop the pipeline and return BLOCKED with the failing phase and evidence. Do not loop indefinitely.-------## Knowledge Base--Your show's brand, voice, and style live in knowledge base files. Skills reference these automatically.--**Location:** `knowledge/` (or `.podcli/knowledge/` if using podcli)--| File | What It Contains |-|------|-----------------|-| `00-master-instructions.md` | AI operating system — auto-detection rules, decision tree |-| `01-brand-identity.md` | Show positioning, tagline, hosts, format |-| `02-voice-and-tone.md` | Voice fingerprint, tone qualities, banned words |-| `03-episodes-database.md` | Episode tracking, existing shorts log |-| `04-shorts-creation-guide.md` | Moment types, selection criteria, extraction process |-| `05-title-formulas.md` | Title spec — shapes, rules, templates by content type |-| `06-descriptions-template.md` | Description formulas, hashtag library, SEO keywords |-| `07-thumbnail-guide.md` | Layouts, brand colors, typography, visual specs |-| `08-topics-themes.md` | Core topics, cross-cutting themes, audience mapping |-| `09-content-workflow.md` | End-to-end workflow phases and handoff specs |-| `10-internal-processing.md` | Auto-execution rules, internal quality gates |-| `11-inspiration-channels.md` | Reference channels, hybrid formulas, viral hooks |-| `12-quick-reference.md` | Copy-paste hooks, hashtags, CTAs, checklists |-| `13-learnings.md` | Cross-episode learnings — updated by `/retro-episode` |-------## Quality Gate (Always Active)--Before outputting ANY content, verify:--1. **Would I click this?** — If no, rewrite-2. **Does it earn attention in 5 seconds?** — If no, find better hook-3. **Does it deliver on the promise?** — If no, it's clickbait, fix it-4. **Is it standalone?** — If context needed, unusable for shorts-5. **Zero banned words** — Check against the list in `02-voice-and-tone.md`-6. **The Coffee Test** — Sounds like a person, not a press release--Full philosophy in `ETHOS.md`.+**Three-strike rule:** if a phase (moment extraction, title generation, etc.) fails to produce valid output 3 times in a row, stop the pipeline and return BLOCKED with the failing phase and evidence. Do not loop indefinitely.---## Routing-When the user provides input without a slash command, match against each skill's `triggers` frontmatter. If one fires with high confidence, run it. If two fire, ask which. If none fire, ask what they want.--Common routes:-- **Transcript text or file** → `/process-transcript`-- **"plan episode" or a guest name** → `/plan-episode`-- **"titles for..."** → `/generate-titles`-- **"thumbnails..."** → `/plan-thumbnails`-- **"descriptions..."** → `/generate-descriptions`-- **"process episode X"** or full transcript + episode number → `/produce-shorts`-- **"review..." or "check..."** → `/review-content`+When the user provides input without a slash command, match against each skill's `triggers` frontmatter. If one fires with high confidence, run it. If two fire, ask which. If none fire, ask what they want. The common routes are listed under "Auto-detection" in `CLAUDE.md`.----## Reference Files--When a skill needs detailed specs, consult the knowledge base:--| Need | File |-|------|------|-| Master instructions & auto-detection | `knowledge/00-master-instructions.md` |-| Brand voice & positioning | `knowledge/01-brand-identity.md`, `knowledge/02-voice-and-tone.md` |-| Title patterns & spec | `knowledge/05-title-formulas.md` |-| Thumbnail format & layout | `knowledge/07-thumbnail-guide.md` |-| Description templates | `knowledge/06-descriptions-template.md` |-| Existing episodes & shorts | `knowledge/03-episodes-database.md` |-| Moment selection criteria | `knowledge/04-shorts-creation-guide.md` |-| Copy-paste resources | `knowledge/12-quick-reference.md` |-| Inspiration styles | `knowledge/11-inspiration-channels.md` |-| Topic areas | `knowledge/08-topics-themes.md` |-| Cross-episode learnings | `knowledge/13-learnings.md` |+## Reference tables-> **Note:** If using podcli, replace `knowledge/` with `.podcli/knowledge/` in all paths above.+The knowledge base file list (14 files at `.podcli/knowledge/`), the command index, and the quality gate live in `CLAUDE.md`. Full content philosophy in `ETHOS.podstack.md`.----## One Rule+## One rule> **Earn attention in 5 seconds. Deliver value that matches the promise.**diff --git a/README.md b/README.mdindex 87bc8dc..2e27d7f 100644--- a/README.md+++ b/README.md@@ -92,6 +92,16 @@ Clips land in `podcli-clips/` in the directory you ran it from, so each show kee- DaVinci Resolve export as FCPXML when you want to finish by hand- Presets, clip history with duplicate detection, and a transcript cache+## Why podcli++If you are weighing podcli against the cloud clippers, this is the difference:++- Runs locally. Transcription and rendering happen on your machine by default, so episodes stay there. Only the optional cloud engine (AssemblyAI) and publishing to YouTube send anything out.+- Free and open source under AGPL-3.0. Exports are unlimited, full quality, and watermark-free.+- Agent-native. 26 MCP tools let Claude Code or Codex drive the whole flow, transcription through publishing.+- A knowledge base keeps titles, captions, and descriptions in your show's voice, and stops the engine from resuggesting moments you already published.+- DaVinci Resolve handoff. Export any clip as FCPXML when you want to finish the edit yourself.+## Use it from your agentpodcli is an [MCP](https://modelcontextprotocol.io) server, so an agent can transcribe, suggest clips, and render them through conversation.diff --git a/backend/cli.py b/backend/cli.pyindex fb4d0c8..dc9f67d 100644--- a/backend/cli.py+++ b/backend/cli.py@@ -18,6 +18,10 @@ import subprocessimport sysimport textwrapimport time+from pathlib import Path++import questionary+from questionary import Stylefrom version import VERSION# Windows streams default to cp1252, which can't encode chars like '→'; podcli is UTF-8.@@ -47,7 +51,6 @@ if os.path.exists(_env_file):os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"if sys.platform == "darwin":os.environ.setdefault("DYLD_LIBRARY_PATH", "")-os.environ.setdefault("PODCLI_TRANSITION_AUTOFIX_PASSES", "2")sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))@@ -68,7 +71,28 @@ def _reveal_in_os(path: str) -> None:from config.paths import paths+from config.server import DEFAULT_PORT, resolve_web_server_port, web_server_urlfrom presets import 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+++def _parse_json_transcript(raw_text):+ data = json.loads(raw_text)+ if isinstance(data, list):+ return data, [], {}+ return data.get("words", []), data.get("segments", []), data+++def _cached_face_map(video_path: str):+ """Face maps are keyed by video content, not by transcript, so an imported+ transcript can still borrow the map from an earlier run on the same file."""+ try:+ from services.transcript_packer import load_cached_transcript_for_video++ cached = load_cached_transcript_for_video(video_path)+ except Exception:+ return None+ return (cached or {}).get("face_map")def _suggestions_session_path(cache_hash: str) -> str:@@ -317,6 +341,44 @@ def _resolve_output_dir(return os.path.join(base_output_dir, preset_folder)+class _SharedWav:+ """Lazily extracted 16 kHz mono WAV shared by transcription, energy and+ reaction analysis so the source video is decoded once per run."""++ def __init__(self, media_path: str):+ self.media_path = media_path+ self.path = None+ self.error = None+ self._failed = False+ import atexit+ atexit.register(self.cleanup)++ def get(self) -> str | None:+ if self.path and os.path.exists(self.path):+ return self.path+ # A decode that fails slowly (or hangs to the 1800s timeout) would be+ # retried by each caller, so the failure is remembered too.+ if self._failed:+ return None+ try:+ from services.audio_extract import extract_wav_16k_mono+ self.path = extract_wav_16k_mono(self.media_path)+ except Exception as e:+ self.error = e+ self.path = None+ if not self.path:+ self._failed = True+ return self.path++ def cleanup(self) -> None:+ if self.path and os.path.exists(self.path):+ try:+ os.unlink(self.path)+ except OSError:+ pass+ self.path = None++def _has_successful_results(results: list) -> bool:"""Return True if at least one clip rendered successfully."""return any(isinstance(r, dict) and r.get("output_path") for r in results)@@ -458,7 +520,7 @@ def cmd_reel(args):def cmd_process(args):"""Full auto pipeline: transcribe → suggest → export."""from services.clip_generator import generate_clip- from services.transcript_parser import parse_speaker_transcript+ from services.transcript_parser import detect_and_parsefrom services.audio_analyzer import get_energy_profilefrom services.audio_events import get_event_profile, is_available as audio_events_availablefrom services.encoder import get_encoder_info@@ -618,6 +680,13 @@ def cmd_process(args):print(f" Video: {os.path.basename(video_path)}")print()+ if kb_is_empty():+ yellow = "\033[38;2;250;204;21m"+ reset = "\033[0m"+ print(f" {yellow}⚠ Knowledge base empty, clips will be scored without your show context.{reset}")+ print(f" {yellow} Run: podcli knowledge init{reset}")+ print()+# Cache hash for resume — keyed by video size+mtime. Disabled when a custom# transcript is supplied, since the hash ignores transcript contents and# would otherwise resume suggestions made from a different transcript.@@ -635,6 +704,7 @@ def cmd_process(args):words = []segments = []result = {}+ shared_wav = _SharedWav(video_path)# Saliency profiles (party/action) select on audio/visual signals, not dialogue,# so transcribing a long video would be wasted work — skip it entirely.@@ -668,15 +738,10 @@ def cmd_process(args):# Detect formatif raw_text.strip().startswith("{") or raw_text.strip().startswith("["):- data = json.loads(raw_text)- if isinstance(data, list):- words = data- else:- words = data.get("words", [])- segments = data.get("segments", [])+ words, segments, result = _parse_json_transcript(raw_text)print(f" JSON transcript: {len(words)} words")else:- parsed = parse_speaker_transcript(+ parsed = detect_and_parse(raw_text,time_adjust=config.get("time_adjust", 0),)@@ -685,7 +750,17 @@ def cmd_process(args):sys.exit(1)words = parsed["words"]segments = parsed["segments"]- print(f" Parsed: {len(segments)} segments, {len(words)} words")+ result = parsed+ fmt = parsed.get("format", "speaker")+ print(f" Parsed {fmt}: {len(segments)} segments, {len(words)} words")++ if not result.get("face_map"):+ cached_face_map = _cached_face_map(video_path)+ if cached_face_map:+ result["face_map"] = cached_face_map+ print(" Reusing cached face map (speaker framing preserved)")+ else:+ print(" No cached face map, crop falls back to per-clip face tracking")elif not skip_transcript:# Check cache firstcached = load_cached_transcript_for_video(video_path)@@ -725,12 +800,16 @@ def cmd_process(args):_spin_msg[0] = f"{msg} ({pct}%)" if pct < 100 else msgtry:+ # Only pre-extract the shared wav when the energy step will+ # reuse it anyway; otherwise let the engine decide (whisper-py+ # and AssemblyAI decode the source themselves).result = transcribe_file(file_path=video_path,model_size=config.get("whisper_model", "base"),engine=os.environ.get("PODCLI_ENGINE") or None,enable_diarization=not config.get("no_speakers", False),progress_callback=_transcribe_progress,+ wav_path=shared_wav.get() if config.get("energy_boost", True) else None,)except (RuntimeError, FileNotFoundError, subprocess.CalledProcessError) as e:_spin_stop.set()@@ -772,18 +851,24 @@ def cmd_process(args):# ── Step 2: Analyze audio energy ──energy_scores = Nonereaction_scores = None+ energy_data = None+ events_data = None+ reaction_times = Noneif config.get("energy_boost", True):print(" [2/4] Analyzing audio energy...")try:- profile = get_energy_profile(video_path, segments)+ profile = get_energy_profile(video_path, segments, wav_path=shared_wav.get())energy_scores = profile["segment_scores"]+ energy_data = profile["energy_data"]print(f" {len(profile['peak_times'])} peak moments found")except Exception as e:print(f" Skipped (error: {e})")if audio_events_available():try:- reactions = get_event_profile(video_path, segments)+ reactions = get_event_profile(video_path, segments, wav_path=shared_wav.get())reaction_scores = reactions["segment_scores"]+ events_data = reactions["events_data"]+ reaction_times = reactions["reaction_times"]n = len(reactions["reaction_times"])if n:print(f" {n} laughter/reaction moments found")@@ -824,6 +909,9 @@ def cmd_process(args):segments=segments or None,words=words or None,progress_callback=lambda pct, msg: print(f" {msg}") if msg else None,+ energy_data=energy_data,+ events_data=events_data,+ wav_path=shared_wav.get(),)if clips:print(f" ✓ {len(clips)} highlights found")@@ -832,7 +920,9 @@ def cmd_process(args):print(" ⚠ No highlights found, falling back to transcript selection")# Try an AI CLI first (uses PodStack knowledge base for intelligent selection)- from services.claude_suggest import suggest_initial_with_claude, _engine_label, _find_ai_cli+ from services.claude_suggest import (+ suggest_initial_with_claude, blend_signal_scores, _engine_label, _find_ai_cli,+ )ai_path, ai_engine = _find_ai_cli()if clips:@@ -844,8 +934,10 @@ def cmd_process(args):segments=segments,top_n=top_n,progress_callback=lambda pct, msg: print(f" {msg}") if msg else None,+ reaction_times=reaction_times,)if clips:+ blend_signal_scores(clips, energy_data=energy_data, events_data=events_data)actual_engine = next((c.get("_ai_engine") for c in clips if c.get("_ai_engine")), ai_engine)print(f" ✓ {_engine_label(actual_engine)} selected {len(clips)} clips")_save_suggestions_session(cache_hash, top_n, actual_engine, clips, selection_sig)@@ -874,6 +966,9 @@ def cmd_process(args):print(" No clips found. Try a longer transcript or lower --min-duration.", file=sys.stderr)sys.exit(1)+ # Rendering reads the source video directly; the shared wav is done.+ shared_wav.cleanup()+# ── Step 3.5: Interactive review ──clips = _review_clips(clips, segments, energy_scores, config)@@ -2700,15 +2795,42 @@ def cmd_knowledge(args):action = getattr(args, "knowledge_action", None) or "list"- if action == "list":+ if action == "init":+ templates_dir = Path(__file__).resolve().parent / "templates" / "knowledge"+ templates = sorted(templates_dir.glob("*.md"))+ if not templates:+ print(f" {red}✗{reset} No templates found at {templates_dir}", file=sys.stderr)+ return+ os.makedirs(kb_dir, exist_ok=True)+ created, skipped = [], []+ for tpl in templates:+ target = os.path.join(kb_dir, tpl.name)+ if os.path.exists(target):+ skipped.append(tpl.name)+ continue+ shutil.copyfile(tpl, target)+ created.append(tpl.name)print(f"\n {bold}Knowledge Base{reset}")print(f" {'─' * 45}")- if not os.path.isdir(kb_dir):- print(f" {gray}Empty — no knowledge files{reset}\n")- return- files = sorted(f for f in os.listdir(kb_dir) if f.endswith(".md"))+ for fname in created:+ print(f" {green}✓{reset} {fname}")+ for fname in skipped:+ print(f" {gray}• {fname} (exists, kept){reset}")+ print(f" {'─' * 45}")+ print(f" {gray}{len(created)} created, {len(skipped)} kept in {kb_dir}{reset}")+ if created:+ print(f" {gray}Fill in the [brackets], starting with 01-brand-identity and 02-voice-and-tone,{reset}")+ print(f" {gray}or run /bootstrap-knowledge in your agent to draft them from an existing channel.{reset}\n")+ else:+ print()++ elif action == "list":+ print(f"\n {bold}Knowledge Base{reset}")+ print(f" {'─' * 45}")+ empty_hint = f" {gray}Empty — run{reset} podcli knowledge init {gray}to create the starter templates{reset}\n"+ files = kb_files(kb_dir)if not files:- print(f" {gray}Empty — no knowledge files{reset}\n")+ print(empty_hint)returnfor fname in files:fpath = os.path.join(kb_dir, fname)@@ -2994,7 +3116,7 @@ def cmd_clips(args):print(f"\n {green}✓{reset} Reopened {accent}{str(clip.get('id'))[:8]}{reset} {bold}{clip.get('title')}{reset}")if not transcript:print(f" {gray}Transcript not loaded — re-transcribe in the studio to edit captions.{reset}")- print(f" {gray}Open the studio:{reset} {accent}http://localhost:3847/clip/{clip.get('id')}{reset}\n")+ print(f" {gray}Open the studio:{reset} {accent}{web_server_url()}/clip/{clip.get('id')}{reset}\n")return@@ -3183,16 +3305,16 @@ def cmd_cache(args):if action == "clear":count = 0- if os.path.isdir(cache_dir):- for fname in os.listdir(cache_dir):- if fname.endswith(".json"):- os.unlink(os.path.join(cache_dir, fname))- count += 1- transcripts_dir = os.path.join(cache_dir, "transcripts")- if os.path.isdir(transcripts_dir):- for fname in os.listdir(transcripts_dir):+ for directory in (+ cache_dir,+ os.path.join(cache_dir, "transcripts"),+ os.path.join(cache_dir, "signals"),+ ):+ if not os.path.isdir(directory):+ continue+ for fname in os.listdir(directory):if fname.endswith(".json"):- os.unlink(os.path.join(transcripts_dir, fname))+ os.unlink(os.path.join(directory, fname))count += 1if count:print(f"\n {green}✓{reset} Cleared {count} cached transcription(s)")@@ -3340,9 +3462,7 @@ def print_banner():except Exception:encoder_label = "CPU"- # Count knowledge base files- kb_path = paths["knowledge"]- kb_count = len([f for f in os.listdir(kb_path) if f.endswith(".md")]) if os.path.isdir(kb_path) else 0+ kb_count = len(kb_files())gray = "\033[38;5;245m"accent = "\033[38;2;212;135;74m"@@ -3388,7 +3508,8 @@ def print_banner():ai_tag = f"{green}✓ {ai_label}{reset}" if ai_path else f"{yellow}✗{reset}"speaker_tag = f"{green}✓{reset}" if speakers_ok else f"{yellow}✗{reset}"cache_tag = f"{green}{cache_count}{reset}" if cache_count else f"{gray}0{reset}"- print(f" {gray}Encoder {green}{encoder_label}{reset} {gray}· {ai_tag} {gray}· Speakers {speaker_tag} {gray}· Cache {cache_tag}{reset}")+ kb_tag = f"{green}{kb_count}{reset}" if kb_count else f"{yellow}0{reset}"+ print(f" {gray}Encoder {green}{encoder_label}{reset} {gray}· {ai_tag} {gray}· Speakers {speaker_tag} {gray}· Cache {cache_tag} {gray}· Knowledge {kb_tag}{reset}")# Assets — one line if anytry:@@ -3437,6 +3558,9 @@ def print_banner():else:print(f" {yellow}⚠ Speaker detection needs a token — run: podcli env set HF_TOKEN <token>{reset}")+ if not kb_count:+ print(f" {yellow}⚠ Knowledge base empty, clips get scored without your show context. Run: podcli knowledge init{reset}")+print()@@ -3461,14 +3585,15 @@ def print_help():print(f" {accent}assets{reset} {gray}<action>{reset} Manage logos, intros, outros")print(f" {accent}presets{reset} {gray}<action>{reset} Save/load rendering presets")print(f" {accent}thumbnails{reset} {gray}<title>{reset} Generate thumbnail variations")- print(f" {accent}knowledge{reset} {gray}<action>{reset} Manage knowledge base (.podcli/knowledge/)")+ print(f" {accent}knowledge init{reset} Create the starter templates for your show")+ print(f" {accent}knowledge{reset} {gray}<action>{reset} list | read | edit | delete knowledge files")print(f" {accent}config{reset} {gray}<action>{reset} Export/import/migrate config profiles")print(f" {accent}corrections{reset} {gray}<action>{reset} Fix Whisper misheard words (Boxel→Voxel)")print(f" {accent}cache{reset} {gray}[clear]{reset} Show/clear transcription cache")print(f" {accent}info{reset} Show system info (encoder, codecs)")print()print(f" {bold}Process options:{reset}")- print(f" {green}-t{reset}, {green}--transcript{reset} {gray}<file>{reset} Use existing transcript (.txt/.json)")+ print(f" {green}-t{reset}, {green}--transcript{reset} {gray}<file>{reset} Use existing transcript (.srt/.vtt/.txt/.json)")print(f" {green}-n{reset}, {green}--top{reset} {gray}<N>{reset} Export top N clips {dim}(default: 5){reset}")print(f" {green}-o{reset}, {green}--output{reset} {gray}<dir>{reset} Output directory {dim}(default: ./clips){reset}")print(f" {green}-p{reset}, {green}--preset{reset} {gray}<name>{reset} Load a saved preset")@@ -3493,18 +3618,201 @@ def print_help():print()print(f" {bold}PodStack{reset} {dim}(Claude Code slash commands):{reset}")print(f" {accent}/auto{reset} One-verb pipeline: confirm strategy → render clips")- print(f" {accent}/prep-episode{reset} Full pipeline: transcript → publish-ready")+ print(f" {accent}/bootstrap-knowledge{reset} Draft your knowledge base from an existing channel")+ print(f" {accent}/plan-episode{reset} Design questions and target moments before recording")+ print(f" {accent}/produce-shorts{reset} Full pipeline: transcript → publish-ready")print(f" {accent}/process-transcript{reset} Extract clip-worthy moments from transcript")print(f" {accent}/generate-titles{reset} Generate 8 title options with verification")print(f" {accent}/generate-descriptions{reset} Descriptions + hashtags + SEO")print(f" {accent}/plan-thumbnails{reset} Thumbnail text + layout briefs")print(f" {accent}/review-content{reset} Brand voice & quality gate check")print(f" {accent}/publish-checklist{reset} Pre/post-publish checklist")+ print(f" {accent}/retro-episode{reset} Performance review + learnings after publishing")print()print(f" {gray}Run {reset}podcli <command> --help{gray} for command-specific options{reset}")print()+def _onboarding_marker() -> str:+ return os.path.join(paths["home"], ".onboarded")+++def _needs_onboarding() -> bool:+ if os.environ.get("PODCLI_NO_ONBOARDING"):+ return False+ if os.path.exists(_onboarding_marker()):+ return False+ return sys.stdin.isatty() and sys.stdout.isatty()+++def _mark_onboarded() -> None:+ marker = _onboarding_marker()+ os.makedirs(os.path.dirname(marker), exist_ok=True)+ with open(marker, "w", encoding="utf-8") as f:+ f.write(VERSION + "\n")+++def _render_brand_identity(answers: dict) -> str:+ hosts = [h.strip() for h in answers.get("hosts", "").split(",") if h.strip()]+ host_lines = "\n".join(f"- {h}" for h in hosts) or "- (add the hosts)"+ return f"""# Brand identity++## Show++- Name: {answers.get('show_name', '').strip()}+- Format: {answers.get('format', '').strip()}+- Language: {answers.get('language', '').strip()}++## Hosts++{host_lines}++## Audience++- Who watches: {answers.get('audience', '').strip()}++## Still to write++- One-line positioning: who the show is for and what they get out of it.+- The promise: what every episode leaves the viewer with.+- What this show is not: two or three things it deliberately avoids.+"""+++def _render_voice_and_tone(answers: dict) -> str:+ hosts = [h.strip() for h in answers.get("hosts", "").split(",") if h.strip()]+ host_phrase = " and ".join(hosts) if hosts else "a host"+ return f"""# Voice and tone++## Voice fingerprint++{answers.get('show_name', '').strip()} sounds: {answers.get('voice', '').strip()}++Every title, description, and thumbnail line has to sound like {host_phrase} talking, in {answers.get('language', '').strip()}.++## The coffee test++Copy should sound like something a host would say to a friend over coffee. If it reads like marketing, rewrite it.++## Banned words and phrases++Never use these in titles, descriptions, or thumbnails:++- insane, mind-blowing, game-changer+- you won't believe+- this changed everything++Add the cliches your niche is drowning in as you spot them.++## Punctuation and style++- Sentence case titles, no all-caps words.+- Numerals over spelled-out numbers.+- Emoji: none in titles.+"""+++def _wizard_ask(question, on_eof=None):+ """questionary turns Ctrl-C into None itself, but lets Ctrl-D escape as EOFError."""+ try:+ return question.ask()+ except EOFError:+ return on_eof+++def _first_run_setup() -> bool:+ """Guided setup on the first interactive run. Skippable, asked once.+ False means the user cancelled: nothing is saved and the caller must not+ treat the run as a success."""+ accent = "\033[38;2;212;135;74m"+ gray = "\033[38;5;245m"+ green = "\033[38;2;74;222;128m"+ bold = "\033[1m"+ reset = "\033[0m"++ qstyle = Style([+ ("qmark", "fg:#d97631 bold"),+ ("question", "bold"),+ ("answer", "fg:#4ade80"),+ ("pointer", "fg:#d97631 bold"),+ ("highlighted", "fg:#d97631 bold"),+ ("selected", "fg:#4ade80"),+ ("instruction", "fg:#a1a1aa"),+ ])++ kb_dir = paths["knowledge"]+ if not kb_is_empty(kb_dir):+ _mark_onboarded()+ return True++ print()+ print(f" {bold}Welcome to podcli{reset}")+ print(f" {gray}Six questions, then podcli scores clips against your show instead of a generic template.{reset}")+ print()++ start = _wizard_ask(questionary.confirm("Set it up now?", default=True, style=qstyle), on_eof=False)+ if start is None:+ return False+ if not start:+ _mark_onboarded()+ print(f" {gray}Later: run{reset} podcli knowledge init {gray}and fill in the templates.{reset}\n")+ return True++ questions = [+ ("show_name", "Show name:"),+ ("hosts", "Host names (comma separated):"),+ ("audience", "Who watches, in one line:"),+ ("language", "Main language:"),+ ("format", "Format (e.g. interview, 60 min, weekly):"),+ ("voice", "The show's voice in three words:"),+ ]+ answers = {}+ for key, prompt in questions:+ value = _wizard_ask(questionary.text(prompt, style=qstyle))+ if value is None:+ return False+ answers[key] = value.strip()++ if not answers["show_name"]:+ _mark_onboarded()+ print(f" {gray}Nothing to save. Run{reset} podcli knowledge init {gray}when you're ready.{reset}\n")+ return True++ os.makedirs(kb_dir, exist_ok=True)+ for fname, content in (+ ("01-brand-identity.md", _render_brand_identity(answers)),+ ("02-voice-and-tone.md", _render_voice_and_tone(answers)),+ ):+ with open(os.path.join(kb_dir, fname), "w", encoding="utf-8") as f:+ f.write(content)+ print(f"\n {green}✓{reset} 01-brand-identity.md")+ print(f" {green}✓{reset} 02-voice-and-tone.md")++ cmd_knowledge(argparse.Namespace(knowledge_action="init"))++ nxt = _wizard_ask(questionary.select(+ "The other 12 files are starter templates. Next:",+ choices=[+ questionary.Choice("Draft them from an existing channel", value="bootstrap"),+ questionary.Choice("Fill them in later", value="later"),+ ],+ style=qstyle,+ ))++ if nxt is None:+ return False+ if nxt == "bootstrap":+ print(f"\n {gray}In Claude Code, run:{reset} {accent}/bootstrap-knowledge <channel-url>{reset}")+ print(f" {gray}It reads the channel and drafts the remaining files for you.{reset}")+ else:+ print(f"\n {gray}The files live in{reset} {kb_dir}")+ print(f" {gray}Fill in the [brackets] whenever you like. Start with 04-shorts-creation-guide.md.{reset}")++ _mark_onboarded()+ print()+ return True++def main():parser = argparse.ArgumentParser(prog="podcli",@@ -3519,7 +3827,7 @@ def main():# ── process ──proc = sub.add_parser("process", help="Process a video into clips")proc.add_argument("video", nargs="?", default=None, help="Path to podcast video file (optional if preset has video_path)")- proc.add_argument("-t", "--transcript", help="Path to transcript file (.txt or .json)")+ proc.add_argument("-t", "--transcript", help="Path to transcript file (.srt, .vtt, .txt, or .json)")proc.add_argument("-n", "--top", type=int, help="Number of top clips to export (default: 5)")proc.add_argument("-o", "--output", help="Output directory (default: ./clips)")proc.add_argument("-p", "--preset", help="Load a saved preset")@@ -3599,7 +3907,7 @@ def main():help="Save handle/platforms/outro-title/accent/bg as the default brand and exit")# ── ui (Studio web dashboard) ──- sub.add_parser("ui", aliases=["webui"], help="Open the Studio web UI (http://localhost:3847)")+ sub.add_parser("ui", aliases=["webui"], help=f"Open the Studio web UI (http://localhost:{DEFAULT_PORT})")# ── presets ──pre = sub.add_parser("presets", help="Manage presets")@@ -3743,6 +4051,7 @@ def main():# ── knowledge ──kb = sub.add_parser("knowledge", help="Manage knowledge base files")kb_sub = kb.add_subparsers(dest="knowledge_action")+ kb_sub.add_parser("init", help="Create the 14 starter templates (never overwrites)")kb_sub.add_parser("list", help="List all knowledge files")kb_read = kb_sub.add_parser("read", help="Print a knowledge file")kb_read.add_argument("filename", help="File name (e.g. 01-brand-identity)")@@ -3847,6 +4156,10 @@ def main():print_help()return+ if _needs_onboarding() and not _first_run_setup():+ print(" Setup cancelled. Your command did not run.", file=sys.stderr)+ sys.exit(130)+if args.command == "process":if not getattr(args, "no_banner", False):print()@@ -3896,7 +4209,7 @@ def main():def launch_webui():- """Launch the Studio web UI server (http://localhost:3847)."""+ """Launch the Studio web UI server (PODCLI_PORT, PORT, else 3847)."""import subprocess as spimport shutil as _shutil@@ -3907,7 +4220,7 @@ def launch_webui():reset = "\033[0m"backend_dir = os.path.dirname(os.path.abspath(__file__))- port = os.environ.get("PORT", "3847")+ port = resolve_web_server_port()node = os.environ.get("PODCLI_NODE") or _shutil.which("node")studio = os.environ.get("PODCLI_STUDIO") or os.path.join(backend_dir, "..", "studio")server = os.path.join(studio, "web-server.mjs")@@ -3918,6 +4231,8 @@ def launch_webui():# same Python backend + ffmpeg via the env below.env = {**os.environ,+ # Pin both: an inherited PODCLI_PORT outranks PORT in the studio's resolver.+ "PODCLI_PORT": str(port),"PORT": str(port),"PODCLI_BACKEND": backend_dir,"PYTHON_PATH": sys.executable,@@ -4523,8 +4838,7 @@ def _interactive_config():if action == "webui":import webbrowser- port = os.environ.get("PORT", "3847")- url = f"http://localhost:{port}/config"+ url = f"{web_server_url()}/config"print(f"\n {gray}Config UI:{reset} {url}")print(f" {dim}Serve the UI first if needed: npm run build && npm run ui:prod{reset}\n")webbrowser.open(url)@@ -4817,7 +5131,7 @@ def _interactive_knowledge():])kb_dir = paths["knowledge"]- files = sorted(f for f in os.listdir(kb_dir) if f.endswith(".md")) if os.path.isdir(kb_dir) else []+ files = kb_files(kb_dir)# Show current filescmd_knowledge(_ap.Namespace(knowledge_action="list"))@@ -4829,13 +5143,18 @@ def _interactive_knowledge():if files:actions.insert(1, questionary.Choice("Read a file", value="read"))actions.append(questionary.Choice("Delete a file", value="delete"))+ else:+ actions.insert(0, questionary.Choice("Create the 14 starter templates", value="init"))actions.append(questionary.Choice("← Back", value="_back"))action = questionary.select("Knowledge base:", choices=actions, style=qstyle).ask()if action is None or action == "_back":return- if action == "read":+ if action == "init":+ cmd_knowledge(_ap.Namespace(knowledge_action="init"))++ elif action == "read":choice = questionary.select("Which file?", choices=files, style=qstyle).ask()if choice:cmd_knowledge(_ap.Namespace(knowledge_action="read", filename=choice))diff --git a/backend/config/server.py b/backend/config/server.pynew file mode 100644index 0000000..f01da5d--- /dev/null+++ b/backend/config/server.py@@ -0,0 +1,22 @@+from __future__ import annotations++import os+from typing import Mapping++DEFAULT_PORT = 3847+++def resolve_web_server_port(env: Mapping[str, str] | None = None) -> int:+ """Mirror of resolveWebServerPort in src/config/server.ts. The Python launcher+ and the Node studio must agree on the port or the CLI prints a dead URL."""+ env = os.environ if env is None else env+ raw = env.get("PODCLI_PORT") or env.get("PORT")+ try:+ port = int(str(raw).strip())+ except (TypeError, ValueError):+ return DEFAULT_PORT+ return port if 0 < port <= 65535 else DEFAULT_PORT+++def web_server_url(env: Mapping[str, str] | None = None) -> str:+ return f"http://localhost:{resolve_web_server_port(env)}"diff --git a/backend/main.py b/backend/main.pyindex e5848cd..bb52b4e 100644--- a/backend/main.py+++ b/backend/main.py@@ -27,9 +27,13 @@ try:load_dotenv(os.environ.get("PODCLI_ENV_FILE") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".env"))except ImportError:pass+import threadingimport tracebackfrom version import VERSION+# Serializes event writes so parallel clip workers can't interleave JSON lines.+_emit_lock = threading.Lock()+def emit_progress(task_id: str, stage: str, percent: int, message: str, **extra):"""Write a progress event to stderr (picked up by TypeScript executor)."""@@ -40,7 +44,8 @@ def emit_progress(task_id: str, stage: str, percent: int, message: str, **extra)"message": message,}event.update(extra)- print(json.dumps(event), file=sys.stderr, flush=True)+ with _emit_lock:+ print(json.dumps(event), file=sys.stderr, flush=True)def emit_result(task_id: str, status: str, data=None, error=None):@@ -53,7 +58,8 @@ def emit_result(task_id: str, status: str, data=None, error=None):result["data"] = dataif error is not None:result["error"] = error- print(json.dumps(result), flush=True)+ with _emit_lock:+ print(json.dumps(result), flush=True)def handle_ping(task_id: str, params: dict):@@ -76,6 +82,16 @@ def handle_transcribe(task_id: str, params: dict):os.environ["PODCLI_ENGINE"] = engineif params.get("assemblyai_api_key"):os.environ["ASSEMBLYAI_API_KEY"] = params["assemblyai_api_key"]++ # One shared 16 kHz mono wav feeds transcription, energy and reactions+ # instead of decoding the source three times.+ shared_wav = None+ try:+ from services.audio_extract import extract_wav_16k_mono+ shared_wav = extract_wav_16k_mono(file_path)+ except Exception:+ shared_wav = None+try:result = transcribe_file(file_path=file_path,@@ -85,50 +101,59 @@ def handle_transcribe(task_id: str, params: dict):enable_diarization=params.get("enable_diarization", True),num_speakers=params.get("num_speakers"),progress_callback=lambda pct, msg: emit_progress(task_id, "transcribing", pct, msg),+ wav_path=shared_wav,)- finally:- if previous_engine is None:- os.environ.pop("PODCLI_ENGINE", None)- else:- os.environ["PODCLI_ENGINE"] = previous_engine- if previous_assemblyai_key is None:- os.environ.pop("ASSEMBLYAI_API_KEY", None)- else:- os.environ["ASSEMBLYAI_API_KEY"] = previous_assemblyai_key- # Apply word corrections (Whisper misheard proper nouns)- apply_corrections(result.get("words", []), result.get("segments", []))-- # Auto-pack: emit compact LLM-readable markdown alongside raw JSON.- # Pulls energy data so the packed view includes peak moments for clip reasoning.- try:- from services.audio_analyzer import extract_audio_energy+ # Apply word corrections (Whisper misheard proper nouns)+ apply_corrections(result.get("words", []), result.get("segments", []))- cache_hash = compute_cache_hash(file_path) + engine_cache_suffix(result.get("engine") or engine)energy_data = Nonetry:- energy_data = extract_audio_energy(file_path)+ from services.audio_analyzer import extract_audio_energy+ energy_data = extract_audio_energy(file_path, wav_path=shared_wav)except Exception:pass # energy is a nice-to-haveevents_data = Nonetry:from services.audio_events import extract_audio_events- events_data = extract_audio_events(file_path)+ events_data = extract_audio_events(file_path, wav_path=shared_wav)except Exception:pass # reactions are a nice-to-have- packed_path, packed_md = write_packed(- result,- cache_hash,- source_label=os.path.basename(file_path),- energy_data=energy_data,- events_data=events_data,- )- result["packed_path"] = packed_path- result["packed_size_bytes"] = len(packed_md.encode("utf-8"))- except Exception as e:- # Non-fatal — transcription result is still useful without the packed view- emit_progress(task_id, "packing", 99, f"Packer skipped: {e}")+ # Cached so clip suggestion reuses these instead of decoding the source again.+ from services.signal_cache import save_signals+ save_signals(file_path, energy_data=energy_data, events_data=events_data)++ # Auto-pack: emit compact LLM-readable markdown alongside raw JSON.+ # Pulls energy data so the packed view includes peak moments for clip reasoning.+ try:+ cache_hash = compute_cache_hash(file_path) + engine_cache_suffix(result.get("engine") or engine)+ packed_path, packed_md = write_packed(+ result,+ cache_hash,+ source_label=os.path.basename(file_path),+ energy_data=energy_data,+ events_data=events_data,+ )+ result["packed_path"] = packed_path+ result["packed_size_bytes"] = len(packed_md.encode("utf-8"))+ except Exception as e:+ # Non-fatal — transcription result is still useful without the packed view+ emit_progress(task_id, "packing", 99, f"Packer skipped: {e}")+ finally:+ if previous_engine is None:+ os.environ.pop("PODCLI_ENGINE", None)+ else:+ os.environ["PODCLI_ENGINE"] = previous_engine+ if previous_assemblyai_key is None:+ os.environ.pop("ASSEMBLYAI_API_KEY", None)+ else:+ os.environ["ASSEMBLYAI_API_KEY"] = previous_assemblyai_key+ if shared_wav and os.path.exists(shared_wav):+ try:+ os.unlink(shared_wav)+ except OSError:+ passemit_result(task_id, "success", data=result)@@ -164,65 +189,102 @@ def handle_create_clip(task_id: str, params: dict):emit_result(task_id, "success", data=result)+def _render_concurrency() -> int:+ raw = (os.environ.get("PODCLI_RENDER_CONCURRENCY") or "").strip()+ if raw:+ try:+ return max(1, int(raw))+ except ValueError:+ pass+ return 2 if (os.cpu_count() or 1) >= 8 else 1++def handle_batch_clips(task_id: str, params: dict):- """Create multiple clips in sequence."""+ """Create multiple clips with a bounded worker pool."""+ from concurrent.futures import ThreadPoolExecutorfrom services.clip_generator import generate_clipfrom services import asset_storeclips = params["clips"]- results = []total = len(clips)+ results = [None] * total+ completed = 0+ completed_lock = threading.Lock()- for i, clip in enumerate(clips):+ def render_one(i: int, clip: dict) -> dict:emit_progress(task_id,"batch",int((i / total) * 100),f"Processing clip {i + 1}/{total}...",)+ result = generate_clip(+ video_path=params["video_path"],+ start_second=clip["start_second"],+ end_second=clip["end_second"],+ caption_style=clip.get("caption_style", "hormozi"),+ crop_strategy=clip.get("crop_strategy", "face"),+ format=clip.get("format", params.get("format", "vertical")),+ transcript_words=params.get("transcript_words", []),+ title=clip.get("title", f"clip_{i + 1}"),+ output_dir=params.get("output_dir"),+ logo_path=asset_store.resolve(clip.get("logo_path") or params.get("logo_path")),+ outro_path=asset_store.resolve(params.get("outro_path")),+ intro_path=asset_store.resolve(clip.get("intro_path") or params.get("intro_path")),+ clean_fillers=params.get("clean_fillers", True),+ face_map=params.get("face_map"),+ keep_segments=clip.get("keep_segments"),+ allow_ass_fallback=clip.get("allow_ass_fallback", params.get("allow_ass_fallback", False)),+ use_ass_captions=clip.get("use_ass_captions", params.get("use_ass_captions", False)),+ keep_caption_overlay=clip.get(+ "keep_caption_overlay", params.get("keep_caption_overlay", False)+ ),+ progress_callback=lambda pct, msg, _i=i: emit_progress(+ task_id, "batch", int((_i / total) * 100 + pct / total), msg+ ),+ )+ return {+ "clip_index": i,+ "status": "success",+ "start_second": clip["start_second"],+ "end_second": clip["end_second"],+ **result,+ }++ def run_and_record(i: int, clip: dict) -> None:+ nonlocal completedtry:- result = generate_clip(- video_path=params["video_path"],- start_second=clip["start_second"],- end_second=clip["end_second"],- caption_style=clip.get("caption_style", "hormozi"),- crop_strategy=clip.get("crop_strategy", "face"),- format=clip.get("format", params.get("format", "vertical")),- transcript_words=params.get("transcript_words", []),- title=clip.get("title", f"clip_{i + 1}"),- output_dir=params.get("output_dir"),- logo_path=asset_store.resolve(clip.get("logo_path") or params.get("logo_path")),- outro_path=asset_store.resolve(params.get("outro_path")),- intro_path=asset_store.resolve(clip.get("intro_path") or params.get("intro_path")),- clean_fillers=params.get("clean_fillers", True),- face_map=params.get("face_map"),- keep_segments=clip.get("keep_segments"),- allow_ass_fallback=clip.get("allow_ass_fallback", params.get("allow_ass_fallback", False)),- use_ass_captions=clip.get("use_ass_captions", params.get("use_ass_captions", False)),- keep_caption_overlay=clip.get(- "keep_caption_overlay", params.get("keep_caption_overlay", False)- ),- progress_callback=lambda pct, msg, _i=i: emit_progress(- task_id, "batch", int((_i / total) * 100 + pct / total), msg- ),- )- row = {+ row = results[i] = render_one(i, clip)+ message = f"Clip {i + 1}/{total} complete"+ except Exception as e:+ row = results[i] = {"clip_index": i,- "status": "success",- "start_second": clip["start_second"],- "end_second": clip["end_second"],- **result,+ "status": "error",+ "start_second": clip.get("start_second"),+ "end_second": clip.get("end_second"),+ "error": str(e),}- results.append(row)- emit_progress(- task_id,- "clip_complete",- int(((i + 1) / total) * 100),- f"Clip {i + 1}/{total} complete",- clip_result=row,- )- except Exception as e:- results.append({"clip_index": i, "status": "error", "error": str(e)})+ message = f"Clip {i + 1}/{total} failed"+ with completed_lock:+ completed += 1+ done = completed+ emit_progress(+ task_id,+ "clip_complete",+ int((done / total) * 100),+ message,+ clip_result=row,+ )++ workers = min(_render_concurrency(), max(1, total))+ if workers <= 1:+ for i, clip in enumerate(clips):+ run_and_record(i, clip)+ else:+ with ThreadPoolExecutor(max_workers=workers) as pool:+ futures = [pool.submit(run_and_record, i, clip) for i, clip in enumerate(clips)]+ for f in futures:+ f.result()emit_result(task_id,@@ -230,7 +292,7 @@ def handle_batch_clips(task_id: str, params: dict):data={"results": results,"total_clips": total,- "successful_clips": sum(1 for r in results if r["status"] == "success"),+ "successful_clips": sum(1 for r in results if r and r["status"] == "success"),},)@@ -524,9 +586,101 @@ def handle_corrections(task_id: str, params: dict):emit_result(task_id, "error", error=f"Unknown corrections action: {action}")+def _extract_signals(+ task_id: str,+ video_path: str,+ want_energy: bool,+ want_events: bool,+) -> tuple[list | None, list | None]:+ """Decode the source once and derive whichever profiles aren't cached yet."""+ from services.audio_events import is_available as audio_events_available++ want_events = want_events and audio_events_available()+ if not want_energy and not want_events:+ return None, None++ wav_path = None+ try:+ from services.audio_extract import extract_wav_16k_mono+ emit_progress(task_id, "suggesting", 2, "Extracting audio...")+ wav_path = extract_wav_16k_mono(video_path)+ except Exception:+ wav_path = None++ energy_data = None+ events_data = None+ try:+ if want_energy:+ emit_progress(task_id, "suggesting", 5, "Analyzing audio energy...")+ try:+ from services.audio_analyzer import extract_audio_energy+ energy_data = extract_audio_energy(video_path, wav_path=wav_path)+ except Exception:+ pass # energy is a nice-to-have+ if want_events:+ emit_progress(task_id, "suggesting", 15, "Detecting laughter and reactions...")+ try:+ from services.audio_events import extract_audio_events+ events_data = extract_audio_events(video_path, wav_path=wav_path)+ except Exception:+ pass # reactions are a nice-to-have+ finally:+ if wav_path and os.path.exists(wav_path):+ try:+ os.unlink(wav_path)+ except OSError:+ pass++ return energy_data, events_data+++def _signal_profiles_for_suggest(+ task_id: str,+ params: dict,+) -> tuple[list | None, list | None, list | None]:+ """Energy and reaction profiles for the suggester: caller-supplied first, then+ what transcription cached for this video, and only then a fresh analysis."""+ from services.audio_events import reaction_times as reaction_times_from_events+ from services.signal_cache import load_signals, save_signals++ energy_data = params.get("energy_data")+ events_data = params.get("events_data")+ anchors = params.get("reaction_times")+ if anchors is not None:+ anchors = [float(t) for t in anchors]++ video_path = params.get("video_path")+ if video_path and os.path.exists(video_path) and (energy_data is None or events_data is None):+ cached = load_signals(video_path)+ if energy_data is None:+ energy_data = cached.get("energy_data")+ if events_data is None:+ events_data = cached.get("events_data")++ if energy_data is None or events_data is None:+ fresh_energy, fresh_events = _extract_signals(+ task_id,+ video_path,+ want_energy=energy_data is None,+ want_events=events_data is None,+ )+ save_signals(video_path, energy_data=fresh_energy, events_data=fresh_events)+ energy_data = energy_data if energy_data is not None else fresh_energy+ events_data = events_data if events_data is not None else fresh_events++ if anchors is None and events_data:+ anchors = reaction_times_from_events(events_data)++ return energy_data, events_data, anchors++def handle_suggest_clips(task_id: str, params: dict):"""AI-powered clip suggestion using Claude/Codex and PodStack knowledge base."""- from services.claude_suggest import suggest_initial_with_claude, _find_ai_cli_candidates+ from services.claude_suggest import (+ _find_ai_cli_candidates,+ select_clips_with_signal_scores,+ suggest_initial_with_claude,+ )segments = params.get("segments", [])top_n = params.get("top_n", 5)@@ -548,12 +702,15 @@ def handle_suggest_clips(task_id: str, params: dict):returnerrors: list[str] = []+ energy_data, events_data, reaction_times = _signal_profiles_for_suggest(task_id, params)+ candidate_top_n = top_n * 2 if energy_data or events_data else top_nclips = suggest_initial_with_claude(segments=segments,- top_n=top_n,+ top_n=candidate_top_n,exclude_clips=existing_clips,progress_callback=lambda pct, msg: emit_progress(task_id, "suggesting", pct, msg),error_sink=errors,+ reaction_times=reaction_times,)if clips is None:@@ -561,6 +718,12 @@ def handle_suggest_clips(task_id: str, params: dict):emit_result(task_id, "error", error=detail)return+ clips = select_clips_with_signal_scores(+ clips,+ top_n=top_n,+ energy_data=energy_data,+ events_data=events_data,+ )emit_result(task_id, "success", data={"clips": clips})diff --git a/backend/services/audio_analyzer.py b/backend/services/audio_analyzer.pyindex 9edb0d3..50fd72b 100644--- a/backend/services/audio_analyzer.py+++ b/backend/services/audio_analyzer.py@@ -6,6 +6,7 @@ then identifies energy peaks (loud moments, laughs, emphasis).Used by the clip suggestor to boost scores for high-energy segments."""+import osimport subprocessimport jsonimport re@@ -14,22 +15,32 @@ from typing import Optional, Callablefrom utils.proc import run as proc_run+_ANALYSIS_RATE = 16000++def extract_audio_energy(video_path: str,window_sec: float = 1.0,+ wav_path: str = None,) -> list[dict]:"""- Extract per-second RMS energy levels from a video's audio track.+ Extract per-window RMS energy levels from a video's audio track.Returns list of {time, rms, peak} dicts, one per window.+ wav_path: optional pre-extracted 16 kHz mono WAV — skips decoding the+ video again when the orchestration layer already extracted the audio."""- # Use ffmpeg astats filter on audio only (-vn skips video decoding,- # which is the main bottleneck on long podcasts).+ input_path = wav_path if wav_path and os.path.exists(wav_path) else video_path+ # astats' reset counts filter frames, not seconds, so pin the frame size+ # to exactly one window with asetnsamples and reset every frame.+ # (-vn skips video decoding, the main bottleneck on long podcasts.)+ window_samples = max(1, int(_ANALYSIS_RATE * window_sec))cmd = ["ffmpeg",- "-i", video_path,+ "-i", input_path,"-vn",- "-af", f"astats=metadata=1:reset={int(1/window_sec)},"+ "-af", f"aresample={_ANALYSIS_RATE},asetnsamples=n={window_samples},"+ f"astats=metadata=1:reset=1,"f"ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-","-f", "null", "-",]@@ -59,7 +70,7 @@ def extract_audio_energy(if not energy_data:# Fallback: use volumedetect for a simpler analysis- return _fallback_energy(video_path)+ return _fallback_energy(input_path)return energy_data@@ -167,6 +178,7 @@ def get_energy_profile(video_path: str,segments: list[dict],progress_callback: Optional[Callable] = None,+ wav_path: str = None,) -> dict:"""Full pipeline: extract energy data and score all segments.@@ -176,7 +188,7 @@ def get_energy_profile(if progress_callback:progress_callback(0, "Analyzing audio energy...")- energy_data = extract_audio_energy(video_path)+ energy_data = extract_audio_energy(video_path, wav_path=wav_path)if progress_callback:progress_callback(70, "Scoring segments by energy...")diff --git a/backend/services/audio_events.py b/backend/services/audio_events.pyindex 3ae6e86..7735e0d 100644--- a/backend/services/audio_events.py+++ b/backend/services/audio_events.py@@ -13,22 +13,26 @@ it anti-correlates with speech at the frame level, which makes it a reliable ancfor extending a clip backwards to the moment that caused the reaction."""+from __future__ import annotations+import csv+import osimport subprocessimport tempfileimport wavefrom pathlib import Pathfrom typing import Optional, Callable-import numpy as np-from utils.proc import run as proc_run+# Guarded together: on a partial runtime, reaction detection turns itself off rather+# than taking down every other backend task with an import error.try:+ import numpy as npimport onnxruntime as ort- _ORT_AVAILABLE = True+ _RUNTIME_AVAILABLE = Trueexcept ImportError:- _ORT_AVAILABLE = False+ _RUNTIME_AVAILABLE = False_MODELS_DIR = Path(__file__).resolve().parents[1] / "models"_MODEL_PATH = _MODELS_DIR / "yamnet.onnx"@@ -41,6 +45,9 @@ _CHEER_NAMES = ("Cheering", "Applause", "Whoop")_SCREAM_NAMES = ("Screaming",)_SPEECH_NAMES = ("Speech",)+_REACTION_CHANNELS = ("laughter", "cheering", "screaming")+REACTION_THRESHOLD = 0.15+_session = None_class_index: dict[str, list[int]] = {}@@ -69,7 +76,7 @@ def _load_class_index() -> dict[str, list[int]]:def _get_session():global _session, _class_index- if not _ORT_AVAILABLE or not _MODEL_PATH.exists():+ if not _RUNTIME_AVAILABLE or not _MODEL_PATH.exists():return Noneif _session is None:_session = ort.InferenceSession(@@ -80,13 +87,30 @@ def _get_session():def is_available() -> bool:- """True if onnxruntime and the YAMNet model are both present."""- return _ORT_AVAILABLE and _MODEL_PATH.exists()+ """True if onnxruntime, numpy and the YAMNet model are all present."""+ return _RUNTIME_AVAILABLE and _MODEL_PATH.exists()+++def _read_waveform_16k_mono(video_path: str, wav_path: Optional[str] = None) -> Optional[np.ndarray]:+ """Extract audio as a float32 [-1, 1] mono waveform at 16 kHz via ffmpeg.+ wav_path: optional pre-extracted 16 kHz mono WAV — read directly, no decode.+ """+ if wav_path and os.path.exists(wav_path):+ try:+ with wave.open(wav_path) as w:+ frames = w.readframes(w.getnframes())+ except (wave.Error, OSError):+ return None+ if not frames:+ return None+ return np.frombuffer(frames, dtype=np.int16).astype(np.float32) / 32768.0-def _read_waveform_16k_mono(video_path: str) -> Optional[np.ndarray]:- """Extract audio as a float32 [-1, 1] mono waveform at 16 kHz via ffmpeg."""- with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as tmp:+ # delete=False + manual unlink: on Windows the open NamedTemporaryFile+ # handle blocks ffmpeg from writing to the same path.+ tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)+ tmp.close()+ try:cmd = ["ffmpeg", "-y", "-i", video_path,"-vn", "-ar", "16000", "-ac", "1",@@ -95,14 +119,22 @@ def _read_waveform_16k_mono(video_path: str) -> Optional[np.ndarray]:result = proc_run(cmd, timeout=600, check=False)if result.returncode != 0:return None- with wave.open(tmp.name) as w:- frames = w.readframes(w.getnframes())+ try:+ with wave.open(tmp.name) as w:+ frames = w.readframes(w.getnframes())+ except (wave.Error, OSError):+ return None+ finally:+ try:+ os.unlink(tmp.name)+ except OSError:+ passif not frames:return Nonereturn np.frombuffer(frames, dtype=np.int16).astype(np.float32) / 32768.0-def extract_audio_events(video_path: str) -> list[dict]:+def extract_audio_events(video_path: str, wav_path: Optional[str] = None) -> list[dict]:"""Run YAMNet over a video's audio and return per-frame reaction probabilities.@@ -114,7 +146,7 @@ def extract_audio_events(video_path: str) -> list[dict]:if session is None:return []- waveform = _read_waveform_16k_mono(video_path)+ waveform = _read_waveform_16k_mono(video_path, wav_path=wav_path)if waveform is None or waveform.size == 0:return []@@ -163,7 +195,27 @@ def extract_audio_events(video_path: str) -> list[dict]:def _reaction_level(event: dict) -> float:"""Combined reaction strength for one frame: the loudest reaction channel."""- return max(event["laughter"], event["cheering"], event["screaming"])+ return max(event[channel] for channel in _REACTION_CHANNELS)+++def reaction_times(+ events_data: list[dict],+ threshold: float = REACTION_THRESHOLD,+) -> list[float]:+ """Timestamps of frames whose reaction level clears `threshold`."""+ return [e["time"] for e in events_data if _reaction_level(e) >= threshold]+++def dominant_reaction(events_data: list[dict], start: float, end: float) -> Optional[str]:+ """Name of the strongest reaction channel in [start, end]: laughter, cheering+ or screaming. None if nothing reacted in that range."""+ frames = [e for e in events_data if start <= e["time"] <= end]+ if not frames:+ return None+ peak = max(frames, key=_reaction_level)+ if _reaction_level(peak) <= 0:+ return None+ return max(_REACTION_CHANNELS, key=lambda channel: peak[channel])def compute_event_scores(@@ -200,7 +252,8 @@ def get_event_profile(video_path: str,segments: list[dict],progress_callback: Optional[Callable] = None,- reaction_threshold: float = 0.15,+ reaction_threshold: float = REACTION_THRESHOLD,+ wav_path: Optional[str] = None,) -> dict:"""Full pipeline: detect audio events and score all segments.@@ -215,22 +268,18 @@ def get_event_profile(if progress_callback:progress_callback(0, "Detecting laughter and reactions...")- events_data = extract_audio_events(video_path)+ events_data = extract_audio_events(video_path, wav_path=wav_path)if progress_callback:progress_callback(70, "Scoring segments by reaction...")segment_scores = compute_event_scores(events_data, segments)- reaction_times = [- e["time"] for e in events_data if _reaction_level(e) >= reaction_threshold- ]-if progress_callback:progress_callback(100, "Reaction analysis complete")return {"events_data": events_data,"segment_scores": segment_scores,- "reaction_times": reaction_times,+ "reaction_times": reaction_times(events_data, reaction_threshold),}diff --git a/backend/services/audio_extract.py b/backend/services/audio_extract.pynew file mode 100644index 0000000..f9a6883--- /dev/null+++ b/backend/services/audio_extract.py@@ -0,0 +1,49 @@+"""Shared 16 kHz mono WAV extraction.++The transcription, energy, and reaction analyzers all consume the same+16 kHz mono PCM audio. Extracting it once in the orchestration layer and+passing the wav path down avoids decoding a long source video 3-5 times+per run.+"""++import os+import tempfile+from typing import Optional++from utils.proc import run as proc_run+++def extract_wav_16k_mono(+ media_path: str,+ wav_path: Optional[str] = None,+ timeout: int = 1800,+) -> str:+ """Extract audio as 16 kHz mono 16-bit PCM WAV. Returns the wav path.++ When wav_path is None a temp file is created; the caller owns cleanup.+ """+ owns_wav = wav_path is None+ if owns_wav:+ fd, wav_path = tempfile.mkstemp(prefix="podcli_audio_", suffix=".wav")+ os.close(fd)+ cmd = [+ "ffmpeg", "-y", "-loglevel", "error",+ "-i", media_path,+ "-vn",+ "-acodec", "pcm_s16le",+ "-ar", "16000",+ "-ac", "1",+ wav_path,+ ]+ try:+ result = proc_run(cmd, timeout=timeout, check=False)+ if result.returncode != 0:+ raise RuntimeError(f"Audio extraction failed: {(result.stderr or '')[-300:]}")+ except Exception:+ if owns_wav:+ try:+ os.unlink(wav_path)+ except OSError:+ pass+ raise+ return wav_pathdiff --git a/backend/services/caption_renderer.py b/backend/services/caption_renderer.pyindex 1342971..8731fe8 100644--- a/backend/services/caption_renderer.py+++ b/backend/services/caption_renderer.py@@ -133,6 +133,36 @@ def render_captions(CAPTION_GAP_FILL_MAX = 0.4 # seconds+CHUNK_BREAK_GAP = 0.8 # seconds of silence that forces a new caption chunk+_TERMINAL_PUNCTUATION = (".", "?", "!")+++def _chunk_words(words: list[dict], chunk_size: int) -> list[list[dict]]:+ """Group words into caption chunks.++ Fixed word counts alone straddle sentence ends, speaker turns and pauses,+ so a chunk also breaks after terminal punctuation, on a speaker change,+ or across an inter-word gap longer than CHUNK_BREAK_GAP.+ """+ chunks: list[list[dict]] = []+ current: list[dict] = []+ for w in words:+ if current:+ prev = current[-1]+ gap_break = float(w.get("start", 0)) - float(prev.get("end", 0)) > CHUNK_BREAK_GAP+ speaker_break = (+ w.get("speaker") is not None+ and prev.get("speaker") is not None+ and w.get("speaker") != prev.get("speaker")+ )+ sentence_break = str(prev.get("word", "")).strip().endswith(_TERMINAL_PUNCTUATION)+ if len(current) >= chunk_size or gap_break or speaker_break or sentence_break:+ chunks.append(current)+ current = []+ current.append(w)+ if current:+ chunks.append(current)+ return chunksdef _hold_through_gap(chunks: list[list[dict]], idx: int, end: float, offset: float) -> float:@@ -157,10 +187,7 @@ def _render_hormozi(words: list[dict], style: dict, offset: float) -> str:chunk_size = style["words_per_chunk"]uppercase = style["uppercase"]- chunks = []- for i in range(0, len(words), chunk_size):- chunk = words[i : i + chunk_size]- chunks.append(chunk)+ chunks = _chunk_words(words, chunk_size)for idx, chunk in enumerate(chunks):if not chunk:@@ -200,9 +227,7 @@ def _render_karaoke(words: list[dict], style: dict, offset: float) -> str:events = []sentence_size = style.get("words_per_chunk", 5)- sentences = []- for i in range(0, len(words), sentence_size):- sentences.append(words[i : i + sentence_size])+ sentences = _chunk_words(words, sentence_size)for idx, sentence in enumerate(sentences):if not sentence:@@ -238,9 +263,7 @@ def _render_subtle(words: list[dict], style: dict, offset: float) -> str:events = []line_size = style.get("words_per_chunk", 5)- lines = []- for i in range(0, len(words), line_size):- lines.append(words[i : i + line_size])+ lines = _chunk_words(words, line_size)for idx, line_words in enumerate(lines):if not line_words:@@ -502,11 +525,7 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:play_res_y = 1920spacing = 2 # ASS Spacing field from header- # Group words into chunks- chunks = []- for i in range(0, len(words), chunk_size):- chunk = words[i : i + chunk_size]- chunks.append(chunk)+ chunks = _chunk_words(words, chunk_size)for chunk_idx, chunk in enumerate(chunks):if not chunk:@@ -582,7 +601,24 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:line_left_x = (play_res_x - full_line_w) // 2line_geometry.append((line_center_ys[li], line_left_x, full_line_w, raw_space_w))- # For each word: emit pill + text (both explicitly positioned)+ chunk_start_ts = seconds_to_ass(chunk_start)+ chunk_end_ts = seconds_to_ass(chunk_end)++ # Layer 1: the text layout is static for the whole chunk, so each word+ # is emitted once for the chunk span. Only the karaoke pill below needs+ # per-word events.+ for li, line in enumerate(lines):+ lcy_l, llx_l, _, asp_w = line_geometry[li]+ wx = llx_l+ for pi, (_, text, ww) in enumerate(line):+ wcx = int(wx + ww // 2)+ events.append(+ f"Dialogue: 1,{chunk_start_ts},{chunk_end_ts},BrandedNormal,,0,0,0,,"+ f"{{\\an5\\pos({wcx},{lcy_l})}}{text}"+ )+ wx += ww + asp_w++ # Layer 0: per-word pill behind the active wordfor wi, w in enumerate(chunk):w_start = max(0, w["start"] - offset)@@ -632,7 +668,6 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:draw_offset_x = pill_w // 2draw_offset_y = pill_h // 2- # Layer 0: Pill — positioned at word center with \an5events.append(f"Dialogue: 0,{start_ts},{end_ts},BrandedNormal,,0,0,0,,"f"{{\\an7\\pos({word_cx - draw_offset_x},{line_cy - draw_offset_y})"@@ -642,16 +677,4 @@ def _render_branded(words: list[dict], style: dict, offset: float) -> str:f"{drawing}{{\\p0}}")- # Layer 1: Each word positioned with \an5\pos for perfect pill alignment- for li, line in enumerate(lines):- lcy_l, llx_l, _, asp_w = line_geometry[li]- wx = llx_l- for pi, (_, text, ww) in enumerate(line):- wcx = int(wx + ww // 2)- events.append(- f"Dialogue: 1,{start_ts},{end_ts},BrandedNormal,,0,0,0,,"- f"{{\\an5\\pos({wcx},{lcy_l})}}{text}"- )- wx += ww + asp_w-return header + "\n".join(events) + "\n"diff --git a/backend/services/claude_suggest.py b/backend/services/claude_suggest.pyindex a4cda23..e12f8d2 100644--- a/backend/services/claude_suggest.py+++ b/backend/services/claude_suggest.py@@ -16,6 +16,8 @@ import tempfilefrom typing import Optional, Callablefrom config.paths import paths+from services.audio_analyzer import compute_energy_scores+from services.audio_events import compute_event_scores, dominant_reactionsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from presets import MIN_CLIP_DURATION, MAX_CLIP_DURATION, TARGET_CLIP_DURATION_MIN, TARGET_CLIP_DURATION_MAX@@ -473,12 +475,31 @@ def _load_existing_shorts(episodes_path: str) -> list[str]:return []+MAX_REACTION_ANCHORS = 40+++def _format_reaction_anchors(reaction_times: list[float] | None) -> str:+ """Prompt block listing detected laughter/reaction peaks as anchor moments."""+ if not reaction_times:+ return ""+ anchors = sorted({round(float(t), 1) for t in reaction_times})[:MAX_REACTION_ANCHORS]+ times = ", ".join(f"{t:.1f}s" for t in anchors)+ return (+ "\nAUDIENCE REACTION ANCHORS (detected laughter/cheering peaks, in seconds):\n"+ f"{times}\n"+ "The moment that CAUSED each reaction sits just before its anchor. "+ "Clips that contain or lead into an anchor are strong candidates — "+ "prefer them when quality is otherwise equal.\n"+ )++def _build_prompt(transcript_text: str,segment_count: int,duration_min: float,top_n: int,exclude_clips: list[dict] | None = None,+ reaction_times: list[float] | None = None,) -> str:"""Build the prompt for Claude to extract clips.@@ -487,7 +508,8 @@ def _build_prompt("""# Load knowledge base files inline — prioritized by relevance to clip selection- kb_context = ""+ from services.knowledge_base import load_kb_context, warn_missing_context+kb_dir = paths["knowledge"]# (filename, max_chars) — higher priority files get more budget_kb_files = [@@ -500,18 +522,9 @@ def _build_prompt(("08-topics-themes.md", 1000), # topic areas, audience interest map("00-master-instructions.md", 1500), # quality gate, auto-detection rules]- for fname, max_chars in _kb_files:- fpath = os.path.join(kb_dir, fname)- if os.path.exists(fpath):- try:- with open(fpath, encoding="utf-8") as f:- content = f.read().strip()- # Skip template-only files (uncustomized placeholders)- if content.count("[Your Show Name]") > 2 and len(content) < 500:- continue- kb_context += f"\n--- {fname} ---\n{content[:max_chars]}\n"- except Exception:- pass+ kb_context = load_kb_context(_kb_files, kb_dir)+ if not kb_context:+ warn_missing_context("clip scoring")# Load existing shorts from episode database for duplicate avoidanceepisodes_path = os.path.join(kb_dir, "03-episodes-database.md")@@ -568,7 +581,7 @@ MOMENT SELECTION (think like a TikTok editor):{f"KNOWLEDGE BASE:{kb_context}" if kb_context else ""}{f"EXISTING SHORTS (avoid duplicating these moments):{chr(10).join('- ' + s for s in existing_shorts)}" if existing_shorts else ""}-{excluded_ranges}+{excluded_ranges}{_format_reaction_anchors(reaction_times)}Score each moment on 4 dimensions (1-5 each):- standalone: Makes sense without episode context?@@ -898,6 +911,7 @@ def suggest_with_claude(progress_callback: Optional[Callable[[int, str], None]] = None,timeout: int = 900,error_sink: Optional[list[str]] = None,+ reaction_times: list[float] | None = None,) -> Optional[list[dict]]:"""Use an AI CLI (Claude Code or Codex) to extract the best clip moments.@@ -926,6 +940,7 @@ def suggest_with_claude(duration_min,top_n,exclude_clips=exclude_clips,+ reaction_times=reaction_times,)# Write prompt to temp file to avoid shell escaping issues.@@ -1091,6 +1106,7 @@ def suggest_initial_with_claude(exclude_clips: list[dict] | None = None,progress_callback: Optional[Callable[[int, str], None]] = None,error_sink: Optional[list[str]] = None,+ reaction_times: list[float] | None = None,) -> Optional[list[dict]]:"""Initial clip discovery entry point.@@ -1108,6 +1124,7 @@ def suggest_initial_with_claude(progress_callback=progress_callback,error_sink=error_sink,timeout=180,+ reaction_times=reaction_times,)start_bound = float(segments[0].get("start", 0))@@ -1139,6 +1156,7 @@ def suggest_initial_with_claude(progress_callback=progress_callback,error_sink=error_sink,timeout=180,+ reaction_times=reaction_times,)if progress_callback:@@ -1169,6 +1187,9 @@ def suggest_initial_with_claude(),error_sink=error_sink,timeout=90,+ reaction_times=[+ t for t in (reaction_times or []) if bucket["start"] <= t <= bucket["end"]+ ] or None,)if not bucket_clips:continue@@ -1192,6 +1213,7 @@ def suggest_initial_with_claude(),error_sink=error_sink,timeout=120,+ reaction_times=reaction_times,)if fallback_clips:deduped = _dedupe_clips_by_range(deduped + fallback_clips)@@ -1199,6 +1221,57 @@ def suggest_initial_with_claude(return _select_top_by_score(deduped, top_n) if deduped else None+REACTION_BLEND_WEIGHT = 0.2+ENERGY_BLEND_WEIGHT = 0.1+++def blend_signal_scores(+ clips: list[dict],+ energy_data: list[dict] | None = None,+ events_data: list[dict] | None = None,+ reaction_weight: float = REACTION_BLEND_WEIGHT,+ energy_weight: float = ENERGY_BLEND_WEIGHT,+) -> list[dict]:+ """Blend per-clip reaction/energy peaks into AI-selected clip scores.++ The AI score (0-20) stays primary: the 0-10 signal scores are added at+ modest weight (max +3 combined), so laughter or an energy spike breaks+ ties rather than overruling editorial judgment. Mutates and returns+ `clips`, preserving their order.+ """+ if not clips or (not energy_data and not events_data):+ return clips++ ranges = [+ {"start": float(c.get("start_second", 0)), "end": float(c.get("end_second", 0))}+ for c in clips+ ]+ reaction_scores = compute_event_scores(events_data or [], ranges)+ energy_scores = compute_energy_scores(energy_data or [], ranges)++ for clip, rng, r_score, e_score in zip(clips, ranges, reaction_scores, energy_scores):+ boost = round(reaction_weight * r_score + energy_weight * e_score, 2)+ if boost <= 0:+ continue+ clip["signal_boost"] = boost+ clip["score"] = round(float(clip.get("score", 0)) + boost, 2)+ if r_score > 3:+ label = dominant_reaction(events_data or [], rng["start"], rng["end"]) or "reaction"+ if label not in (clip.get("reasons") or []):+ clip.setdefault("reasons", []).append(label)+ return clips+++def select_clips_with_signal_scores(+ clips: list[dict],+ top_n: int,+ energy_data: list[dict] | None = None,+ events_data: list[dict] | None = None,+) -> list[dict]:+ blended = blend_signal_scores(clips, energy_data=energy_data, events_data=events_data)+ return _select_top_by_score(blended, top_n)++def _bucket_coverage_seconds(existing_clips: list[dict], start: float, end: float) -> float:"""Total selected-clip overlap inside a time bucket."""covered = 0.0diff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.pyindex f111a25..1f7c613 100644--- a/backend/services/clip_generator.py+++ b/backend/services/clip_generator.py@@ -11,6 +11,7 @@ import tempfileimport shutilimport subprocessimport re+import threadingfrom typing import Optional, Callablefrom utils.proc import run as proc_run, ProcError@@ -234,6 +235,65 @@ def _apply_local_transition_smoothing(return False+_output_path_lock = threading.Lock()+_reserved_output_paths: set[str] = set()+++def _reserve_output_path(output_dir: str, stem: str, ext: str) -> str:+ """Claim an output path no other clip in this run can take.++ Titles come from an LLM and are not deduped, so two clips in one batch can+ share a stem. Rendering both to the same path would interleave the copy and+ the in-place autofix re-encode into one corrupt file while both report+ success. Reservations are per-process, so re-rendering a clip in a later run+ still overwrites its own output instead of piling up suffixes.+ """+ with _output_path_lock:+ candidate = os.path.join(output_dir, f"{stem}{ext}")+ n = 2+ while candidate in _reserved_output_paths:+ candidate = os.path.join(output_dir, f"{stem}-{n}{ext}")+ n += 1+ _reserved_output_paths.add(candidate)+ return candidate+++def _reframe_can_jump(+ reframe: bool,+ crop_strategy: str,+ crop_keyframes: list = None,+ keep_segments: list = None,+) -> bool:+ """Whether this render can contain hard visual jumps worth an autofix pass.++ The pass is only skipped where a jump is impossible: no reframe at all, a+ fixed centre crop, or a manual crop held on a single keyframe. Every+ tracked strategy can snap the crop between subjects, so it gets smoothed.+ Speaker labels are not consulted: the default whisper.cpp engine skips+ diarization, so they are absent exactly when face tracking is doing the+ most snapping.+ """+ if keep_segments and len(keep_segments) > 1:+ return True+ if not reframe:+ return False+ if crop_strategy == "center":+ return False+ if crop_strategy == "manual":+ return bool(crop_keyframes and len(crop_keyframes) > 1)+ return True+++def _transition_autofix_passes(jumps_possible: bool) -> int:+ raw = (os.environ.get("PODCLI_TRANSITION_AUTOFIX_PASSES") or "").strip()+ if raw:+ try:+ return max(0, min(int(raw), 2))+ except ValueError:+ pass+ return 2 if jumps_possible else 0++def _auto_fix_transition_jumps(video_path: str, max_passes: int = 1) -> bool:"""Bounded auto-fix for jumpy transitions. Never loops indefinitely.@@ -460,11 +520,17 @@ def _render_with_remotion(# Prepare words JSON (adjust timestamps by offset)adjusted_words = []for w in words:- adjusted_words.append({+ adjusted = {"word": w.get("word", ""),"start": round(w["start"] - time_offset, 3),"end": round(w["end"] - time_offset, 3),- })+ }+ # The chunker starts a new caption card on a speaker change. Dropping the+ # field here left that rule dead in the render while the studio preview,+ # which keeps it, chunked the same words differently.+ if w.get("speaker") is not None:+ adjusted["speaker"] = w["speaker"]+ adjusted_words.append(adjusted)# Extract face Y positions so captions can avoid overlapping faces# Probe video dimensions@@ -916,20 +982,27 @@ def generate_clip(if progress_callback:progress_callback(95, "Saving final clip...")- output_filename = f"{safe_filename(title)}_short.mp4"-if output_dir:os.makedirs(output_dir, exist_ok=True)- final_path = os.path.join(output_dir, output_filename)+ final_path = _reserve_output_path(output_dir, f"{safe_filename(title)}_short", ".mp4")else:- final_path = os.path.join(work_dir, output_filename)+ fd, final_path = tempfile.mkstemp(+ prefix=f"{safe_filename(title)}_short_", suffix=".mp4"+ )+ os.close(fd)shutil.copy2(final_video_path, final_path)# Optional bounded QA/autofix pass for transition jumps.# Hard-capped to avoid any infinite rerender loop.- max_autofix_passes = int(os.environ.get("PODCLI_TRANSITION_AUTOFIX_PASSES", "2") or "2")- max_autofix_passes = max(0, min(max_autofix_passes, 2))+ max_autofix_passes = _transition_autofix_passes(+ _reframe_can_jump(+ reframe=spec.reframe,+ crop_strategy=crop_strategy,+ crop_keyframes=crop_keyframes,+ keep_segments=keep_segments,+ )+ )if max_autofix_passes > 0:if progress_callback:progress_callback(97, "Quality gate: checking transitions...")@@ -956,11 +1029,17 @@ def generate_clip(if length_warning:out["warning"] = length_warningif keep_caption_overlay and caption_overlay_path and os.path.exists(caption_overlay_path):- out["caption_overlay_path"] = caption_overlay_path- out["cropped_source_path"] = cropped_path+ # Copy out of work_dir before cleanup so the returned paths survive.+ base, _ = os.path.splitext(final_path)+ persisted_overlay = f"{base}_captions.mov"+ shutil.copy2(caption_overlay_path, persisted_overlay)+ out["caption_overlay_path"] = persisted_overlay+ if os.path.exists(cropped_path):+ persisted_source = f"{base}_source.mp4"+ shutil.copy2(cropped_path, persisted_source)+ out["cropped_source_path"] = persisted_sourcereturn outfinally:- # Clean up temp files (but not if output is in work_dir)- if output_dir and os.path.exists(work_dir):+ if os.path.exists(work_dir):shutil.rmtree(work_dir, ignore_errors=True)diff --git a/backend/services/content_generator.py b/backend/services/content_generator.pyindex b6a76f6..99b20c1 100644--- a/backend/services/content_generator.py+++ b/backend/services/content_generator.py@@ -12,8 +12,8 @@ import tempfileimport threadingfrom typing import Optional, Callable-from config.paths import pathsfrom services.claude_suggest import _engine_label, _find_ai_cli_candidates, _run_ai_command+from services.knowledge_base import load_kb_context as kb_load_context, warn_missing_contextCONTENT_KB_FILES = [@@ -25,22 +25,14 @@ CONTENT_KB_FILES = []-def load_kb_context(files: Optional[list[tuple[str, int]]] = None) -> str:+def load_kb_context(+ files: Optional[list[tuple[str, int]]] = None,+ task: str = "content generation",+) -> str:"""Load PodStack knowledge base files as inline prompt context."""- kb_dir = paths["knowledge"]- kb_context = ""- for fname, max_chars in files if files is not None else CONTENT_KB_FILES:- fpath = os.path.join(kb_dir, fname)- if os.path.exists(fpath):- try:- with open(fpath, encoding="utf-8") as kf:- content = kf.read().strip()- # Skip uncustomized templates- if content.count("[Your Show Name]") > 2 and len(content) < 500:- continue- kb_context += f"\n--- {fname} ---\n{content[:max_chars]}\n"- except Exception:- pass+ kb_context = kb_load_context(files if files is not None else CONTENT_KB_FILES)+ if not kb_context:+ warn_missing_context(task)return kb_context@@ -278,7 +270,7 @@ def generate_clip_content(if progress_callback:progress_callback(0, f"Generating content via {label}...")- kb_context = load_kb_context()+ kb_context = load_kb_context(task="title and description generation")# Extract transcript text for this clip's time rangeclip_start = clip.get("start_second", 0)diff --git a/backend/services/knowledge_base.py b/backend/services/knowledge_base.pynew file mode 100644index 0000000..be5b75b--- /dev/null+++ b/backend/services/knowledge_base.py@@ -0,0 +1,121 @@+"""Knowledge base helpers shared by the CLI and the AI prompt builders."""++from __future__ import annotations++import os+import re+import sys+from pathlib import Path++from config.paths import paths++TEMPLATES_DIR = Path(__file__).resolve().parents[1] / "templates" / "knowledge"++# The studio writes README.md into the knowledge dir; it is not user content.+IGNORED_FILES = {"readme.md"}++_PLACEHOLDER = re.compile(r"\[[^\[\]\n]{1,120}\]")+_MD_LINK = re.compile(r"\[[^\]\n]+\]\([^)\n]*\)")+_CODE_FENCE = re.compile(r"```.*?```", re.DOTALL)+_TABLE_RULE = set("|-: ")++# Tuned against the shipped templates (line ratio 0.62-0.92, char ratio 0.34-0.73) and+# against filled files, which keep the odd legitimate bracket ("[guest]", "[00:00]").+MIN_PLACEHOLDERS = 3+PLACEHOLDER_LINE_RATIO = 0.6+PLACEHOLDER_CHAR_RATIO = 0.3+++def _body_lines(content: str) -> list[str]:+ text = _CODE_FENCE.sub("", content)+ text = _MD_LINK.sub("", text)+ lines = []+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ if set(line) <= _TABLE_RULE:+ continue+ lines.append(line)+ return lines+++def is_unfilled_template(content: str, filename: str | None = None) -> bool:+ """True when a knowledge file is still a starter template nobody filled in."""+ stripped = content.strip()+ if not stripped:+ return True++ if filename:+ shipped = TEMPLATES_DIR / os.path.basename(filename)+ try:+ if shipped.is_file() and shipped.read_text(encoding="utf-8").strip() == stripped:+ return True+ except OSError:+ pass++ lines = _body_lines(stripped)+ if not lines:+ return True+ body = "\n".join(lines)+ placeholders = _PLACEHOLDER.findall(body)+ if len(placeholders) < MIN_PLACEHOLDERS:+ return False+ char_ratio = sum(len(p) for p in placeholders) / len(body)+ line_ratio = sum(1 for line in lines if _PLACEHOLDER.search(line)) / len(lines)+ return line_ratio >= PLACEHOLDER_LINE_RATIO or char_ratio >= PLACEHOLDER_CHAR_RATIO+++def kb_files(kb_dir: str | None = None) -> list[str]:+ """Markdown files in the knowledge base that the user owns."""+ directory = kb_dir or paths["knowledge"]+ if not os.path.isdir(directory):+ return []+ return sorted(+ f for f in os.listdir(directory)+ if f.endswith(".md") and f.lower() not in IGNORED_FILES+ )+++def is_empty(kb_dir: str | None = None) -> bool:+ return not kb_files(kb_dir)+++def load_kb_context(files: list[tuple[str, int]], kb_dir: str | None = None) -> str:+ """Inline knowledge base files as prompt context, skipping unfilled templates."""+ directory = kb_dir or paths["knowledge"]+ kb_context = ""+ for fname, max_chars in files:+ fpath = os.path.join(directory, fname)+ if not os.path.exists(fpath):+ continue+ try:+ with open(fpath, encoding="utf-8") as f:+ content = f.read().strip()+ except OSError:+ continue+ if is_unfilled_template(content, fname):+ continue+ kb_context += f"\n--- {fname} ---\n{content[:max_chars]}\n"+ return kb_context+++SETUP_HINT = (+ "Run: podcli knowledge init, then fill in the [brackets], "+ "or run /bootstrap-knowledge in your agent to draft them from an existing channel."+)++_warned = False+++def warn_missing_context(task: str) -> None:+ """One stderr line per run when the knowledge base holds no usable show context."""+ global _warned+ if _warned:+ return+ _warned = True+ print(+ f"Warning: no show context in the knowledge base, {task} is running without it. {SETUP_HINT}",+ file=sys.stderr,+ flush=True,+ )diff --git a/backend/services/saliency.py b/backend/services/saliency.pyindex a1dc36f..2e8d910 100644--- a/backend/services/saliency.py+++ b/backend/services/saliency.py@@ -230,6 +230,9 @@ def detect_highlights(words: Optional[list[dict]] = None,reaction_threshold: float = 0.06,progress_callback: Optional[Callable] = None,+ energy_data: Optional[list[dict]] = None,+ events_data: Optional[list[dict]] = None,+ wav_path: Optional[str] = None,) -> list[dict]:"""Generate highlight clips from a video's fused signal curve.@@ -239,21 +242,26 @@ def detect_highlights(preferred over `segments`. Without any transcript, boundaries snap to audio lulls.`reaction_threshold` is the laughter/cheer level that counts as a reaction — low(~0.06) for conversational chuckles, higher for loud belly-laughs/crowds.+ `energy_data`/`events_data` accept the profiles the orchestration layer already+ computed so the source audio isn't decoded again; `wav_path` is a pre-extracted+ 16 kHz mono WAV used when extraction is still needed.Returns clip dicts compatible with the render pipeline:{title, start_second, end_second, duration, score, reasons, preview}."""profile = get_profile(profile_name)snap_units = sentences_from_words(words) if words else segments- if progress_callback:- progress_callback(10, "Analyzing audio energy...")- energy_data = extract_audio_energy(video_path)-- events_data = []- if audio_events_available():+ if energy_data is None:if progress_callback:- progress_callback(40, "Detecting laughter and reactions...")- events_data = extract_audio_events(video_path)+ progress_callback(10, "Analyzing audio energy...")+ energy_data = extract_audio_energy(video_path, wav_path=wav_path)++ if events_data is None:+ events_data = []+ if audio_events_available():+ if progress_callback:+ progress_callback(40, "Detecting laughter and reactions...")+ events_data = extract_audio_events(video_path, wav_path=wav_path)last_times = [e["time"] for e in energy_data] + [e["time"] for e in events_data]if not last_times:diff --git a/backend/services/signal_cache.py b/backend/services/signal_cache.pynew file mode 100644index 0000000..791cb27--- /dev/null+++ b/backend/services/signal_cache.py@@ -0,0 +1,52 @@+"""Disk cache for a video's audio signals (energy, reactions).++Transcription already decodes the audio and runs both analyzers, so clip+suggestion reads the profiles from here instead of decoding the source again.+Keyed on the video's content hash, not the engine: the signals come from the+audio, not from the transcript.+"""++from __future__ import annotations++import json+import os+from typing import Any, Optional++from config.paths import paths+from services.transcript_packer import compute_cache_hash+++def _signals_path(video_path: str) -> str:+ return os.path.join(paths["cache"], "signals", f"{compute_cache_hash(video_path)}.json")+++def load_signals(video_path: str) -> dict[str, Any]:+ """Cached {energy_data, events_data} for a video, or {} if absent."""+ try:+ with open(_signals_path(video_path), encoding="utf-8") as f:+ return json.load(f)+ except (OSError, ValueError):+ return {}+++def save_signals(+ video_path: str,+ energy_data: Optional[list[dict]] = None,+ events_data: Optional[list[dict]] = None,+) -> None:+ """Merge the given profiles into the cache. Best-effort: a cache miss later+ only costs a re-analysis."""+ payload = load_signals(video_path)+ if energy_data is not None:+ payload["energy_data"] = energy_data+ if events_data is not None:+ payload["events_data"] = events_data+ if not payload:+ return+ try:+ path = _signals_path(video_path)+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "w", encoding="utf-8") as f:+ json.dump(payload, f)+ except (OSError, ValueError):+ passdiff --git a/backend/services/speaker_detection.py b/backend/services/speaker_detection.pyindex d610bba..5022d62 100644--- a/backend/services/speaker_detection.py+++ b/backend/services/speaker_detection.py@@ -235,8 +235,9 @@ def assign_speakers_to_words("""Assign speaker labels to individual words.- Uses the midpoint of each word's timestamp to determine- which speaker segment it falls within.+ Picks the speaker whose diarization segment overlaps the word the most —+ at turn boundaries several segments can touch a word, and the first+ match is often the previous speaker trailing off."""if not speaker_segments:for w in words:@@ -244,16 +245,21 @@ def assign_speakers_to_words(return wordsfor w in words:- midpoint = (w["start"] + w["end"]) / 2-- # Find which speaker segment contains this midpoint- assigned = None+ speaker_overlap = {}for sp in speaker_segments:- if sp["start"] <= midpoint <= sp["end"]:- assigned = sp["speaker"]- break+ overlap = min(w["end"], sp["end"]) - max(w["start"], sp["start"])+ if overlap > 0:+ speaker_overlap[sp["speaker"]] = speaker_overlap.get(sp["speaker"], 0) + overlap- w["speaker"] = assigned+ if speaker_overlap:+ w["speaker"] = max(speaker_overlap, key=speaker_overlap.get)+ else:+ # Zero-length or gap words: fall back to midpoint containment.+ midpoint = (w["start"] + w["end"]) / 2+ w["speaker"] = next(+ (sp["speaker"] for sp in speaker_segments if sp["start"] <= midpoint <= sp["end"]),+ None,+ )return wordsdiff --git a/backend/services/transcription.py b/backend/services/transcription.pyindex 9b34476..1a5d4af 100644--- a/backend/services/transcription.py+++ b/backend/services/transcription.py@@ -58,7 +58,7 @@ def _whispercpp_ready(model_size: str) -> bool:return _whispercpp_cli() is not None and os.path.exists(_whispercpp_model(model_size))-def _transcribe_with_whispercpp(file_path, model_size, language, progress_callback):+def _transcribe_with_whispercpp(file_path, model_size, language, progress_callback, wav_path=None):from services import transcription_whispercpp as wcppif progress_callback:@@ -80,6 +80,7 @@ def _transcribe_with_whispercpp(file_path, model_size, language, progress_callbalanguage=language,vad=vad,vad_model=os.environ.get("PODCLI_WHISPERCPP_VAD_MODEL") or None,+ wav_path=wav_path,)if progress_callback:progress_callback(50, "Transcription complete")@@ -334,6 +335,7 @@ def _attach_speakers_and_faces(enable_diarization,num_speakers,progress_callback,+ wav_path=None,):"""Merge speaker diarization + face analysis into a transcribed result.Shared by both engines; face analysis (OpenCV) runs even when diarization@@ -359,17 +361,22 @@ def _attach_speakers_and_faces(if progress_callback:progress_callback(55, "Extracting audio for speaker detection...")- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:- wav_path = tmp.name+ shared_wav = wav_path if wav_path and os.path.exists(wav_path) else None+ if shared_wav:+ diar_wav = shared_wav+ else:+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:+ diar_wav = tmp.nametry:- extract_audio_wav(file_path, wav_path)+ if not shared_wav:+ extract_audio_wav(file_path, diar_wav)if progress_callback:progress_callback(60, "Running speaker diarization...")speaker_segments = run_diarization(- wav_path,+ diar_wav,num_speakers=num_speakers,progress_callback=lambda pct, msg: (progress_callback(60 + int(pct * 0.3), msg) if progress_callback else None@@ -391,8 +398,8 @@ def _attach_speakers_and_faces()finally:- if os.path.exists(wav_path):- os.unlink(wav_path)+ if not shared_wav and os.path.exists(diar_wav):+ os.unlink(diar_wav)except ImportError as e:diarization_warning = f"Speaker detection unavailable: {e}"@@ -447,10 +454,14 @@ def transcribe_file(enable_diarization: bool = True,num_speakers: Optional[int] = None,progress_callback: Optional[Callable[[int, str], None]] = None,+ wav_path: Optional[str] = None,) -> dict:"""Transcribe a video/audio file with word-level timestamps and speaker detection.+ wav_path: optional pre-extracted 16 kHz mono WAV shared across analysis+ stages — used by whisper.cpp and diarization instead of re-decoding.+Returns:{"transcript": str,@@ -496,7 +507,9 @@ def transcribe_file() from eif use_cpp:- base = _transcribe_with_whispercpp(file_path, model_size, language, progress_callback)+ base = _transcribe_with_whispercpp(+ file_path, model_size, language, progress_callback, wav_path=wav_path+ )base["engine"] = "whispercpp"# whisper.cpp is the no-torch path: importing torch for diarization can# hard-crash native runtimes. Skip diarization, keep face analysis (OpenCV).@@ -588,5 +601,6 @@ def transcribe_file("engine": "whisper-py",}return _attach_speakers_and_faces(- file_path, base, enable_diarization, num_speakers, progress_callback+ file_path, base, enable_diarization, num_speakers, progress_callback,+ wav_path=wav_path,)diff --git a/backend/services/transcription_whispercpp.py b/backend/services/transcription_whispercpp.pyindex d62f8be..de32502 100644--- a/backend/services/transcription_whispercpp.py+++ b/backend/services/transcription_whispercpp.py@@ -146,6 +146,7 @@ def transcribe_file(threads: int = 4,vad: bool = False,vad_model: Optional[str] = None,+ wav_path: Optional[str] = None,**_ignored,) -> dict:if not os.path.exists(file_path):@@ -154,10 +155,13 @@ def transcribe_file(raise FileNotFoundError(f"ggml model not found: {model_path}")tmpdir = tempfile.mkdtemp(prefix="wcpp_")- wav = os.path.join(tmpdir, "audio.wav")out_base = os.path.join(tmpdir, "out")try:- _extract_wav(file_path, wav, ffmpeg)+ if wav_path and os.path.exists(wav_path):+ wav = wav_path+ else:+ wav = os.path.join(tmpdir, "audio.wav")+ _extract_wav(file_path, wav, ffmpeg)cmd = [whisper_cli, "-m", model_path, "-f", wav, "-ojf","-of", out_base, "-t", str(threads)]diff --git a/backend/services/video_cut.py b/backend/services/video_cut.pyindex c064941..5c41ddc 100644--- a/backend/services/video_cut.py+++ b/backend/services/video_cut.py@@ -21,10 +21,14 @@ def cut_segment() -> str:"""Extract a single time segment from a video file.- Uses `-ss` before `-i` with re-encoding for frame-accurate- timestamps. The fast preset + CRF 18 is a deliberate quality- trade-off: we'll re-encode again in the final pipeline, so this- pass prioritizes speed.+ Always re-encodes with `-ss` before `-i` for frame-accurate timestamps.+ Stream copy is not an option here: with `-c copy` ffmpeg can only start at+ the keyframe at-or-before the cut point, so any boundary off the GOP grid+ silently emits up to a full GOP of earlier content while the duration still+ checks out, which offsets every burned-in caption. CRF 16 keeps this+ intermediate visually lossless through the later crop/caption/audio+ re-encodes; the fast preset holds the speed cost to a few percent+ over the old CRF 18 pass."""duration = end_second - start_second@@ -33,7 +37,7 @@ def cut_segment("-ss", str(start_second),"-i", input_path,"-t", str(duration),- "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-profile:v", "high",+ "-c:v", "libx264", "-crf", "16", "-preset", "fast", "-profile:v", "high","-c:a", "aac", "-b:a", "192k","-avoid_negative_ts", "make_zero",output_path,diff --git a/backend/services/video_processor.py b/backend/services/video_processor.pyindex 36256bd..7256662 100644--- a/backend/services/video_processor.py+++ b/backend/services/video_processor.py@@ -959,6 +959,27 @@ def _pick_tracking_face(return face, side_ok or near_anchor+def _face_sample_indices(total_frames: int, fps: float) -> list[int]:+ """Frame indices for face sampling: every frame for the first 0.5s, every+ other frame until 1s (to catch a face before gestures), then ~10 fps."""+ sample_step = max(1, int(fps / 10))+ dense_end_frame = int(fps * 0.5)+ semi_dense_end_frame = int(fps * 1.0)+ semi_dense_step = max(1, sample_step // 2)++ indices = []+ frame_idx = 0+ while frame_idx < total_frames:+ indices.append(frame_idx)+ if frame_idx < dense_end_frame:+ frame_idx += 1+ elif frame_idx < semi_dense_end_frame:+ frame_idx += semi_dense_step+ else:+ frame_idx += sample_step+ return indices++def _track_and_crop(input_path: str,output_path: str,@@ -1006,31 +1027,26 @@ def _track_and_crop(return None# ── Dense face sampling (~10 fps, 2× at clip start) ──────────- sample_step = max(1, int(fps / 10))- # Sample every frame for the first 0.5s, then every other frame- # until 1s, to maximise the chance of catching a face before gestures.- dense_end_frame = int(fps * 0.5)- semi_dense_end_frame = int(fps * 1.0)- dense_step = 1- semi_dense_step = max(1, sample_step // 2)+ # grab() advances cheaply, retrieve() decodes only sampled frames — far+ # cheaper than a cap.set() seek (keyframe re-decode) per sample.+ sample_indices = _face_sample_indices(total_frames, fps)detections = [] # [(time, faces), ...]- frame_idx = 0- while frame_idx < total_frames:- cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)- ret, frame = cap.read()+ next_pos = 0+ frame_idx = -1+ while next_pos < len(sample_indices):+ if not cap.grab():+ break+ frame_idx += 1+ if frame_idx < sample_indices[next_pos]:+ continue+ next_pos += 1+ ret, frame = cap.retrieve()if not ret:- frame_idx += sample_stepcontinuet = frame_idx / fpsfaces = detect_faces(detector, frame, width, height)detections.append((t, faces))- if frame_idx < dense_end_frame:- frame_idx += dense_step- elif frame_idx < semi_dense_end_frame:- frame_idx += semi_dense_step- else:- frame_idx += sample_stepcap.release()diff --git a/backend/templates/knowledge/00-master-instructions.md b/backend/templates/knowledge/00-master-instructions.mdnew file mode 100644index 0000000..acd2c1f--- /dev/null+++ b/backend/templates/knowledge/00-master-instructions.md@@ -0,0 +1,31 @@+# Master instructions++How the AI should operate when producing content for this show. Fill in every `[bracket]`, then delete this line.++## Operating rules++1. Read `01-brand-identity.md` and `02-voice-and-tone.md` before writing anything.+2. Check `03-episodes-database.md` before suggesting moments so published clips are not repeated.+3. Apply the quality gate below to every title, description, and thumbnail line.+4. Log what worked and what did not in `13-learnings.md` after each episode retro.++## Quality gate++Before outputting any content, verify:++- Would the target viewer click this?+- Does it earn attention in the first 5 seconds?+- Does the content deliver what the hook promises?+- Does the clip stand alone without episode context?+- Zero banned words from `02-voice-and-tone.md`.+- Does it sound like a person talking, not a press release?++## Auto-detection++- Transcript text or file provided: process it into scored moments.+- Asked for titles, descriptions, or thumbnails: use the matching guide file.+- Asked to "process episode": run the full pipeline.++## Show-specific overrides++[Anything this show does differently from the defaults above, or "none yet".]diff --git a/backend/templates/knowledge/01-brand-identity.md b/backend/templates/knowledge/01-brand-identity.mdnew file mode 100644index 0000000..d4f8b51--- /dev/null+++ b/backend/templates/knowledge/01-brand-identity.md@@ -0,0 +1,28 @@+# Brand identity++## Show++- Name: [Show name]+- One-line positioning: [Who it is for and what they get, in one sentence]+- Format: [Interview / co-hosted conversation / solo commentary], [typical length], [publishing cadence]+- Language: [Primary language, plus any mixing]++## Hosts++| Host | Role | Voice in one line |+|------|------|-------------------|+| [Name] | [Host / co-host] | [e.g. asks blunt questions, plays devil's advocate] |++## Audience++- Who watches: [age range, occupation, what they care about]+- Why they watch: [the job the show does for them: learn X, feel Y, keep up with Z]+- Where they watch: [YouTube long-form / Shorts / TikTok / Instagram / podcast apps]++## Promise++Every episode should leave the viewer with: [the consistent takeaway that makes someone subscribe].++## What this show is not++[2-3 things the show deliberately avoids, e.g. news recaps, guest promo hours.]diff --git a/backend/templates/knowledge/02-voice-and-tone.md b/backend/templates/knowledge/02-voice-and-tone.mdnew file mode 100644index 0000000..8e63904--- /dev/null+++ b/backend/templates/knowledge/02-voice-and-tone.md@@ -0,0 +1,30 @@+# Voice and tone++## Voice fingerprint++Describe how this show talks in 3-5 adjectives with a line of explanation each:++- [e.g. Direct: says the thing plainly, no wind-up]+- [e.g. Curious: questions over hot takes]+- [adjective]: [what it means in practice]++## The coffee test++Every line of copy should sound like something a host would actually say to a friend over coffee. If it reads like marketing, rewrite it.++Passes: "[example sentence in the show's real voice]"+Fails: "[example of the corporate/hype version of the same sentence]"++## Banned words and phrases++Words that must never appear in titles, descriptions, or thumbnails:++- [e.g. insane, mind-blowing, game-changer]+- [e.g. you won't believe]+- [add the cliches your niche is drowning in]++## Punctuation and style++- [e.g. sentence case titles, no all-caps words]+- [e.g. numerals over spelled-out numbers]+- [e.g. emoji policy: none / max one per description]diff --git a/backend/templates/knowledge/03-episodes-database.md b/backend/templates/knowledge/03-episodes-database.mdnew file mode 100644index 0000000..55d9d33--- /dev/null+++ b/backend/templates/knowledge/03-episodes-database.md@@ -0,0 +1,20 @@+# Episodes database++Tracks every episode and every short produced from it, so new suggestions never duplicate published clips. Add a section per episode, newest first.++## Template++### EP[number]: [episode title]++- Guest: [name, or "none"]+- Recorded: [date] | Published: [date]+- Link: [URL]+- Core topics: [3-5 topics]++Shorts produced:++| # | Moment (timestamps) | Title | Platform | Status |+|---|---------------------|-------|----------|--------|+| 1 | [00:14:20-00:15:05] | [published title] | [YouTube Shorts] | [published / scheduled / dropped] |++Moments considered but not used: [timestamps + one-line reason, so they can be reconsidered or skipped later].diff --git a/backend/templates/knowledge/04-shorts-creation-guide.md b/backend/templates/knowledge/04-shorts-creation-guide.mdnew file mode 100644index 0000000..2dff923--- /dev/null+++ b/backend/templates/knowledge/04-shorts-creation-guide.md@@ -0,0 +1,33 @@+# Shorts creation guide++What makes a moment worth clipping for this show.++## Moment selection criteria++Score candidate moments against these, best first:++1. [e.g. A strong claim someone could disagree with]+2. [e.g. A specific story with a turn: setup, tension, payoff]+3. [e.g. A number or fact the viewer did not know]+4. [e.g. Genuine laughter or an emotional beat]+5. [e.g. Practical advice the viewer can apply today]++## Hard rules++- Standalone: no episode context required to follow the clip.+- Length: [e.g. 25-55 seconds, hard cap 90].+- The hook must land inside the first [3] seconds.+- Skip: [e.g. inside jokes, sponsor reads, name-drops without payoff].++## Clip shapes that work for this show++| Shape | Description | Example moment |+|-------|-------------|----------------|+| [Hot take] | [guest says the quiet part out loud] | [ep + timestamp once you have one] |+| [Story] | [complete micro-story with a punchline] | [example] |++## Editing preferences++- Caption style: [branded / hormozi / karaoke / subtle]+- Format: [9:16 / 16:9 / 1:1]+- [Anything else: logo, intro/outro, music policy]diff --git a/backend/templates/knowledge/05-title-formulas.md b/backend/templates/knowledge/05-title-formulas.mdnew file mode 100644index 0000000..a1f3097--- /dev/null+++ b/backend/templates/knowledge/05-title-formulas.md@@ -0,0 +1,29 @@+# Title formulas++## Rules++- Under [70] characters. Main keyword in the first 3 words.+- Sentence case unless the platform convention differs.+- Zero banned words from `02-voice-and-tone.md`.+- The title must be true: the clip has to deliver it.++## Shapes++| Shape | Pattern | Example for this show |+|-------|---------|-----------------------|+| Claim | [Strong statement the clip defends] | [fill after first episodes] |+| Question | [The question the clip answers] | [example] |+| Number | [Specific stat or count as the hook] | [example] |+| Contrast | [Expectation vs what actually happened] | [example] |+| Quote | [The most striking line, verbatim] | [example] |++## Show-specific patterns++Patterns that have worked (move proven ones here from `13-learnings.md`):++- [pattern + example]++## Never++- [e.g. clickbait that the clip does not pay off]+- [e.g. titles that need the guest's name to make sense, unless the guest is the draw]diff --git a/backend/templates/knowledge/06-descriptions-template.md b/backend/templates/knowledge/06-descriptions-template.mdnew file mode 100644index 0000000..3bfa966--- /dev/null+++ b/backend/templates/knowledge/06-descriptions-template.md@@ -0,0 +1,34 @@+# Descriptions template++## Shorts description formula++1. First line: [restate or extend the hook, since only the first line shows before "more"]+2. [One line of context or the payoff]+3. Call to action: [e.g. "Full episode: [link]"]+4. Hashtags: [3-5, most specific first]++Example skeleton:++```+[Hook line]+[Context or payoff line]+Full episode: [link]+#[niche] #[topic] #[show-name]+```++## Long-form description formula++1. [2-3 sentence summary in the show's voice]+2. Timestamps: [chapter list]+3. Guest links: [socials, project]+4. Standard footer: see `12-quick-reference.md`++## Hashtag pools++- Always: [#show-name, #core-niche]+- Rotate by topic: [#topic-a, #topic-b, #topic-c]++## SEO keywords++Primary: [3-5 phrases people actually search]+Secondary: [long-tail variants]diff --git a/backend/templates/knowledge/07-thumbnail-guide.md b/backend/templates/knowledge/07-thumbnail-guide.mdnew file mode 100644index 0000000..533e5ce--- /dev/null+++ b/backend/templates/knowledge/07-thumbnail-guide.md@@ -0,0 +1,30 @@+# Thumbnail guide++## Brand kit++- Colors: [primary hex], [accent hex], [text hex]+- Font: [name, weight]+- Logo placement: [corner / none]++## Layouts++### 16:9 (long-form)++- [e.g. Host or guest face right third, text left two thirds]+- Text: max [4] words per line, max [2] lines+- [Expression guidance: real reaction frames over posed shots]++### 9:16 (shorts)++- [e.g. Text top quarter, face center, captions burn into lower third]+- Text: max [3] words per line++## Text rules++- Never repeat the title verbatim: the thumbnail adds a second angle.+- Zero banned words from `02-voice-and-tone.md`.+- [Case and punctuation preference]++## Reference thumbnails++[Links or file paths to 3-5 thumbnails whose style this show imitates, with one line on why each works.]diff --git a/backend/templates/knowledge/08-topics-themes.md b/backend/templates/knowledge/08-topics-themes.mdnew file mode 100644index 0000000..07ca35d--- /dev/null+++ b/backend/templates/knowledge/08-topics-themes.md@@ -0,0 +1,24 @@+# Topics and themes++## Core topics++The 3-6 subjects this show keeps returning to:++| Topic | Why the audience cares | Example angle |+|-------|------------------------|---------------|+| [topic] | [the itch it scratches] | [a concrete episode or clip angle] |++## Audience mapping++| Audience segment | Topics they engage with | Content that reaches them |+|------------------|-------------------------|---------------------------|+| [segment] | [topics] | [shorts / long-form / both] |++## Evergreen vs timely++- Evergreen: [topics that work any week]+- Timely: [topic types worth covering fast, and how fast]++## Off-limits++[Topics the show deliberately does not touch, and why.]diff --git a/backend/templates/knowledge/09-content-workflow.md b/backend/templates/knowledge/09-content-workflow.mdnew file mode 100644index 0000000..55ddd86--- /dev/null+++ b/backend/templates/knowledge/09-content-workflow.md@@ -0,0 +1,26 @@+# Content workflow++The end-to-end path from recording to published clips for this show.++## Phases++1. Plan: [who preps guest questions and when; use /plan-episode]+2. Record: [setup notes: camera count, mic, where files land]+3. Process: run /produce-shorts (or /process-transcript for moments only)+4. Review: [who approves titles and clips before publishing]+5. Publish: [platforms, days, times; use /publish-checklist]+6. Retro: run /retro-episode after [7] days of data++## Cadence++- Episodes: [e.g. one per week, recorded Tuesdays]+- Shorts per episode: [target count]+- Publishing schedule: [e.g. shorts daily at 17:00 local]++## Responsibilities++| Step | Owner |+|------|-------|+| [editing] | [name / AI] |+| [approval] | [name] |+| [publishing] | [name / scheduled] |diff --git a/backend/templates/knowledge/10-internal-processing.md b/backend/templates/knowledge/10-internal-processing.mdnew file mode 100644index 0000000..943e50d--- /dev/null+++ b/backend/templates/knowledge/10-internal-processing.md@@ -0,0 +1,26 @@+# Internal processing++Auto-execution rules for the AI when running pipelines for this show. These defaults apply when the user does not specify otherwise.++## Defaults++- Moments per episode: extract [8-15], surface the top [5]+- Clip length: [25-55] seconds+- Caption style: [branded]+- Format: [9:16]+- Titles per clip: [8] options, best first++## Decisions the AI may make alone++- [e.g. dropping a moment that fails the standalone test]+- [e.g. trimming clip boundaries by up to 3 seconds for a cleaner cut]++## Decisions that need a human++- [e.g. publishing anything]+- [e.g. clips involving sensitive topics: list them]+- [e.g. changing a guest's meaning through editing]++## When unsure++[Default behavior: e.g. present both options with a recommendation instead of guessing.]diff --git a/backend/templates/knowledge/11-inspiration-channels.md b/backend/templates/knowledge/11-inspiration-channels.mdnew file mode 100644index 0000000..a9484a2--- /dev/null+++ b/backend/templates/knowledge/11-inspiration-channels.md@@ -0,0 +1,18 @@+# Inspiration channels++Channels and creators whose clips work, as reference material. Study structure, not content: hooks, pacing, caption style, thumbnail language.++## Reference channels++| Channel | Niche | What to steal (structurally) |+|---------|-------|------------------------------|+| [name + link] | [niche] | [e.g. cold-open question hooks, 40s average length] |++## Hook patterns observed++- [e.g. starts mid-sentence at the emotional peak, context comes second]+- [pattern + which channel does it well]++## What not to copy++- [e.g. their all-caps thumbnail style clashes with our brand]diff --git a/backend/templates/knowledge/12-quick-reference.md b/backend/templates/knowledge/12-quick-reference.mdnew file mode 100644index 0000000..21efd22--- /dev/null+++ b/backend/templates/knowledge/12-quick-reference.md@@ -0,0 +1,27 @@+# Quick reference++Copy-paste resources used across episodes. Keep this current: everything here gets pasted verbatim.++## Links++- Show: [main channel URL]+- All platforms: [YouTube / Spotify / Apple / TikTok / Instagram]+- Website or newsletter: [URL]++## Standard description footer++```+[Subscribe line]+[Platform links block]+[Contact or sponsor line]+```++## Boilerplate++- Guest intro line: "[template with [guest] placeholder]"+- Sponsor disclosure: "[exact required wording]"++## Hashtag sets++- Default: [#a #b #c]+- [Topic]: [#x #y #z]diff --git a/backend/templates/knowledge/13-learnings.md b/backend/templates/knowledge/13-learnings.mdnew file mode 100644index 0000000..f841f94--- /dev/null+++ b/backend/templates/knowledge/13-learnings.md@@ -0,0 +1,19 @@+# Learnings++Cross-episode performance patterns. /retro-episode appends here; move proven patterns into the guide files (titles into `05`, moments into `04`) once they repeat.++## Confirmed patterns++| Date | Pattern | Evidence |+|------|---------|----------|+| [date] | [what worked] | [clip + metric] |++## Disproven assumptions++| Date | What we believed | What the data showed |+|------|------------------|----------------------|++## Open experiments++| Started | Hypothesis | How we will know |+|---------|------------|------------------|diff --git a/cli/internal/config/config.go b/cli/internal/config/config.goindex ef972fe..09103cd 100644--- a/cli/internal/config/config.go+++ b/cli/internal/config/config.go@@ -7,13 +7,16 @@ import ("fmt""os""strings"+ "time""podcli/internal/paths")type Config struct {Update struct {- Auto *bool `json:"auto,omitempty"`+ Auto *bool `json:"auto,omitempty"`+ Latest string `json:"latest,omitempty"`+ CheckedAt string `json:"checkedAt,omitempty"`} `json:"update"`}@@ -52,6 +55,27 @@ func AutoUpdate() bool {return true}+// CachedUpdateCheck returns the last seen release tag when the check is fresher+// than maxAge, so routine commands skip the network round-trip.+func CachedUpdateCheck(maxAge time.Duration) (string, bool) {+ c := Load()+ if c.Update.Latest == "" || c.Update.CheckedAt == "" {+ return "", false+ }+ at, err := time.Parse(time.RFC3339, c.Update.CheckedAt)+ if err != nil || time.Since(at) > maxAge {+ return "", false+ }+ return c.Update.Latest, true+}++func RecordUpdateCheck(latest string) {+ c := Load()+ c.Update.Latest = latest+ c.Update.CheckedAt = time.Now().UTC().Format(time.RFC3339)+ c.Save()+}+func Get(key string) (string, error) {switch key {case "update.auto":diff --git a/cli/internal/podstack/podstack.go b/cli/internal/podstack/podstack.goindex 9a5d346..6a05b37 100644--- a/cli/internal/podstack/podstack.go+++ b/cli/internal/podstack/podstack.go@@ -15,6 +15,8 @@ import ("sort""strings""syscall"++ "podcli/internal/paths")//go:generate sh sync.sh@@ -56,6 +58,23 @@ func IsCommand(name string) bool {return false}+// warnEmptyKnowledge nudges toward `podcli knowledge init` before a workflow+// runs against a blank knowledge base. README.md does not count: the studio+// writes one into the knowledge dir, and it carries no show context.+func warnEmptyKnowledge() {+ kb := filepath.Join(paths.Home(), "knowledge")+ entries, err := os.ReadDir(kb)+ if err == nil {+ for _, e := range entries {+ name := e.Name()+ if strings.HasSuffix(name, ".md") && !strings.EqualFold(name, "README.md") {+ return+ }+ }+ }+ fmt.Fprintf(os.Stderr, " %sKnowledge base is empty.%s Run %spodcli knowledge init%s first, or %s/bootstrap-knowledge%s in your agent, so the workflow knows your show.\n", colYellow, colReset, colAccent, colReset, colAccent, colReset)+}+// installCommands writes the embedded slash-command files into// <project>/.claude/commands so the agent can resolve /<cmd>. Existing files are// left untouched, so a user's local edits win.@@ -121,6 +140,7 @@ func Run(cmd string, args []string) int {if err := installCommands(project); err != nil {fmt.Fprintf(os.Stderr, " %swarning:%s could not install slash commands: %v\n", colYellow, colReset, err)}+ warnEmptyKnowledge()prompt := "/" + cmdif len(promptArgs) > 0 {diff --git a/cli/internal/provision/download_test.go b/cli/internal/provision/download_test.gonew file mode 100644index 0000000..c5a7a99--- /dev/null+++ b/cli/internal/provision/download_test.go@@ -0,0 +1,234 @@+package provision++import (+ "crypto/sha256"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++func TestDownloadRequiresPinnedChecksum(t *testing.T) {+ err := download("https://example.invalid/x", filepath.Join(t.TempDir(), "x"), "", "x")+ if err == nil || !strings.Contains(err.Error(), "no pinned checksum") {+ t.Fatalf("download with empty checksum should hard-error, got %v", err)+ }+}++func TestDownloadReplacesExistingChecksumMismatch(t *testing.T) {+ payload := []byte("verified payload")+ want := fmt.Sprintf("%x", sha256.Sum256(payload))+ var hits atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ w.Write(payload)+ }))+ defer srv.Close()++ dest := filepath.Join(t.TempDir(), "model.bin")+ if err := os.WriteFile(dest, []byte("unverified payload"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := download(srv.URL, dest, want, "model"); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(dest)+ if err != nil {+ t.Fatal(err)+ }+ if string(got) != string(payload) {+ t.Fatalf("download retained existing payload: %q", got)+ }+ if hits.Load() != 1 {+ t.Fatalf("replacement download hits = %d, want 1", hits.Load())+ }+}++func TestArtifactStateRequiresMatchingKeyAndContents(t *testing.T) {+ dir := t.TempDir()+ bin := filepath.Join(dir, "tool")+ if err := os.WriteFile(bin, []byte("verified"), 0o755); err != nil {+ t.Fatal(err)+ }+ if artifactAt(dir, "release-a", bin) {+ t.Fatal("artifact without verification state was trusted")+ }+ if err := writeArtifactState(dir, "release-a", bin); err != nil {+ t.Fatal(err)+ }+ if !artifactAt(dir, "release-a", bin) {+ t.Fatal("matching verified artifact was rejected")+ }+ if artifactAt(dir, "release-b", bin) {+ t.Fatal("artifact verified for an older release was trusted")+ }+ if err := os.WriteFile(bin, []byte("mutated"), 0o755); err != nil {+ t.Fatal(err)+ }+ if artifactAt(dir, "release-a", bin) {+ t.Fatal("mutated artifact was trusted")+ }+}++func TestAllModelsPinned(t *testing.T) {+ for size, m := range models {+ if len(m.SHA256) != 64 {+ t.Errorf("model %s has no pinned sha256", size)+ }+ }+}++func TestFFmpegSpecsPinnedAndVersioned(t *testing.T) {+ for platform, specs := range ffmpegSpecs {+ for _, a := range specs {+ if len(a.SHA256) != 64 {+ t.Errorf("%s: %s has no pinned sha256", platform, a.URL)+ }+ for _, mutable := range []string{"latest", "getrelease", "ffmpeg-release-"} {+ if strings.Contains(a.URL, mutable) {+ t.Errorf("%s: %s is a mutable URL (%q)", platform, a.URL, mutable)+ }+ }+ }+ }+}++func TestVerifyDownloadFailsClosed(t *testing.T) {+ archive := filepath.Join(t.TempDir(), "a.bin")+ if err := os.WriteFile(archive, []byte("payload"), 0o644); err != nil {+ t.Fatal(err)+ }++ missing := httptest.NewServer(http.NotFoundHandler())+ defer missing.Close()+ if err := verifyDownload(archive, missing.URL, "a.bin"); err == nil {+ t.Fatal("missing checksums manifest should fail closed")+ }++ noEntry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprintln(w, "abc123 other.bin")+ }))+ defer noEntry.Close()+ if err := verifyDownload(archive, noEntry.URL, "a.bin"); err == nil {+ t.Fatal("missing checksum entry should fail closed")+ }+}++func TestVerifyReleaseAssetFailsClosedWithoutManifest(t *testing.T) {+ err := verifyReleaseAsset(map[string]string{}, "whisper-cli-linux-amd64", "/nonexistent")+ if err == nil || !strings.Contains(err.Error(), "checksums.txt") {+ t.Fatalf("release without checksums.txt should fail closed, got %v", err)+ }+}++func TestAcquireLockReleaseAndStaleTakeover(t *testing.T) {+ dest := filepath.Join(t.TempDir(), "artifact")+ unlock, err := acquireLock(dest)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(dest + ".lock"); err != nil {+ t.Fatalf("lock file missing while held: %v", err)+ }+ unlock()+ if _, err := os.Stat(dest + ".lock"); !os.IsNotExist(err) {+ t.Fatalf("lock file should be gone after release, got %v", err)+ }++ if err := os.WriteFile(dest+".lock", []byte("999999"), 0o644); err != nil {+ t.Fatal(err)+ }+ stale := time.Now().Add(-2 * time.Hour)+ if err := os.Chtimes(dest+".lock", stale, stale); err != nil {+ t.Fatal(err)+ }+ unlock, err = acquireLock(dest)+ if err != nil {+ t.Fatalf("stale lock should be taken over, got %v", err)+ }+ unlock()+}++func TestDownloadOnceSendsIfRangeAndRestartsOnChange(t *testing.T) {+ var gotIfRange, gotRange string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotIfRange = r.Header.Get("If-Range")+ gotRange = r.Header.Get("Range")+ w.Header().Set("ETag", `"v2"`)+ w.WriteHeader(http.StatusOK)+ io.WriteString(w, "FRESH")+ }))+ defer srv.Close()++ tmp := filepath.Join(t.TempDir(), "f.part")+ if err := os.WriteFile(tmp, []byte("OLDDATA"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(validatorPath(tmp), []byte(`"v1"`), 0o644); err != nil {+ t.Fatal(err)+ }++ done, err := downloadOnce(srv.URL, tmp, "test", downloadHTTPClient())+ if err != nil || !done {+ t.Fatalf("downloadOnce = %v, %v", done, err)+ }+ if gotRange == "" {+ t.Fatal("resume should send Range")+ }+ if gotIfRange != `"v1"` {+ t.Fatalf("If-Range = %q, want stored validator", gotIfRange)+ }+ b, _ := os.ReadFile(tmp)+ if string(b) != "FRESH" {+ t.Fatalf("full response should truncate stale part file, got %q", b)+ }+ v, _ := os.ReadFile(validatorPath(tmp))+ if string(v) != `"v2"` {+ t.Fatalf("validator = %q, want new ETag", v)+ }+}++func TestStallGuardAbortsIdleBody(t *testing.T) {+ pr, pw := io.Pipe()+ defer pw.Close()+ g := newStallGuard(pr, 50*time.Millisecond)+ defer g.stop()++ _, err := g.Read(make([]byte, 1))+ if err == nil || !strings.Contains(err.Error(), "stalled") {+ t.Fatalf("idle body should surface a stall error, got %v", err)+ }+}++func TestGithubAPIGetRateLimitAndToken(t *testing.T) {+ limited := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer limited.Close()+ _, err := githubAPIGet(limited.URL)+ if err == nil || !strings.Contains(err.Error(), "GITHUB_TOKEN") {+ t.Fatalf("403 should report the rate limit and suggest GITHUB_TOKEN, got %v", err)+ }++ var auth string+ ok := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ auth = r.Header.Get("Authorization")+ io.WriteString(w, "{}")+ }))+ defer ok.Close()+ t.Setenv("GITHUB_TOKEN", "tok123")+ resp, err := githubAPIGet(ok.URL)+ if err != nil {+ t.Fatal(err)+ }+ resp.Body.Close()+ if auth != "Bearer tok123" {+ t.Fatalf("Authorization = %q, want bearer token", auth)+ }+}diff --git a/cli/internal/provision/lock_test.go b/cli/internal/provision/lock_test.gonew file mode 100644index 0000000..941346a--- /dev/null+++ b/cli/internal/provision/lock_test.go@@ -0,0 +1,239 @@+package provision++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++// A loaded CI runner can starve the heartbeat goroutine for tens of+// milliseconds, so keep the stale window far larger than the heartbeat rather+// than scaling both down together: a tight ratio makes a healthy lock look+// abandoned, which is the very thing these tests are meant to catch.+func shortLockTimings(t *testing.T, wait, stale time.Duration) {+ heartbeat, prevStale, poll, prevWait := lockHeartbeat, lockStale, lockPoll, lockWait+ t.Cleanup(func() { lockHeartbeat, lockStale, lockPoll, lockWait = heartbeat, prevStale, poll, prevWait })+ lockHeartbeat, lockStale, lockPoll, lockWait = 20*time.Millisecond, stale, 5*time.Millisecond, wait+}++func TestHeldLockIsNotStolenAfterStaleWindow(t *testing.T) {+ shortLockTimings(t, 400*time.Millisecond, 500*time.Millisecond)+ dest := filepath.Join(t.TempDir(), "artifact")+ lock := dest + ".lock"++ unlock, err := acquireLock(dest)+ if err != nil {+ t.Fatal(err)+ }+ time.Sleep(5 * lockStale)++ if dropStaleLock(lock) {+ t.Fatal("a heartbeated lock was treated as abandoned")+ }+ if _, err := os.Stat(lock); err != nil {+ t.Fatalf("lock file gone while held: %v", err)+ }+ if _, err := acquireLock(dest); err == nil || !strings.Contains(err.Error(), "timed out") {+ t.Fatalf("second process should wait out a live lock, got %v", err)+ }++ unlock()+ unlock2, err := acquireLock(dest)+ if err != nil {+ t.Fatalf("lock should be free after release, got %v", err)+ }+ unlock2()+}++func TestSupersededOwnerCannotHeartbeatOrReleaseReplacement(t *testing.T) {+ shortLockTimings(t, 400*time.Millisecond, 500*time.Millisecond)+ dest := filepath.Join(t.TempDir(), "artifact")+ lock := dest + ".lock"++ unlock, err := acquireLock(dest)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.Remove(lock); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(lock, []byte("replacement-owner"), 0o644); err != nil {+ t.Fatal(err)+ }+ replacementTime := time.Now().Add(-time.Hour)+ if err := os.Chtimes(lock, replacementTime, replacementTime); err != nil {+ t.Fatal(err)+ }++ time.Sleep(3 * lockHeartbeat)+ info, err := os.Stat(lock)+ if err != nil {+ t.Fatal(err)+ }+ if !info.ModTime().Equal(replacementTime) {+ t.Fatalf("superseded owner heartbeated replacement lock: got %v want %v", info.ModTime(), replacementTime)+ }+ unlock()+ got, err := os.ReadFile(lock)+ if err != nil {+ t.Fatalf("superseded owner removed replacement lock: %v", err)+ }+ if string(got) != "replacement-owner" {+ t.Fatalf("replacement ownership changed to %q", got)+ }+}++func TestLockOwnersReceiveUniqueTokens(t *testing.T) {+ dest := filepath.Join(t.TempDir(), "artifact")+ lock := dest + ".lock"++ unlock, err := acquireLock(dest)+ if err != nil {+ t.Fatal(err)+ }+ first, err := os.ReadFile(lock)+ if err != nil {+ t.Fatal(err)+ }+ unlock()++ unlock, err = acquireLock(dest)+ if err != nil {+ t.Fatal(err)+ }+ second, err := os.ReadFile(lock)+ if err != nil {+ t.Fatal(err)+ }+ unlock()++ if string(first) == string(second) {+ t.Fatalf("lock ownership token was reused: %q", first)+ }+}++func TestStaleLockTakeoverIsExclusive(t *testing.T) {+ // Stale window well past the hold time, so a winner's lock is fresh on its+ // own creation stamp and exclusivity does not hinge on heartbeat scheduling.+ shortLockTimings(t, 10*time.Second, 3*time.Second)+ dest := filepath.Join(t.TempDir(), "artifact")+ lock := dest + ".lock"+ if err := os.WriteFile(lock, []byte("999999"), 0o644); err != nil {+ t.Fatal(err)+ }+ stale := time.Now().Add(-time.Hour)+ if err := os.Chtimes(lock, stale, stale); err != nil {+ t.Fatal(err)+ }++ var live, maxLive, failures atomic.Int32+ var wg sync.WaitGroup+ for i := 0; i < 8; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ unlock, err := acquireLock(dest)+ if err != nil {+ failures.Add(1)+ return+ }+ defer unlock()+ n := live.Add(1)+ for {+ m := maxLive.Load()+ if n <= m || maxLive.CompareAndSwap(m, n) {+ break+ }+ }+ time.Sleep(20 * time.Millisecond)+ live.Add(-1)+ }()+ }+ wg.Wait()++ if got := maxLive.Load(); got != 1 {+ t.Fatalf("%d processes held the lock at once; the stale takeover is not exclusive", got)+ }+ if got := failures.Load(); got != 0 {+ t.Fatalf("%d waiters never acquired the lock", got)+ }+ if _, err := os.Stat(lock); !os.IsNotExist(err) {+ t.Fatalf("lock file should be gone after the last release, got %v", err)+ }+ if _, err := os.Stat(lock + ".takeover"); !os.IsNotExist(err) {+ t.Fatalf("takeover token should not outlive the takeover, got %v", err)+ }+}++func TestDownloadPathIsUniquePerURL(t *testing.T) {+ t.Setenv("PODCLI_HOME", t.TempDir())+ const name = "studio-bundle.tar.gz"+ v1, err := downloadPath("https://github.com/o/r/releases/download/v2.4.7/"+name, name)+ if err != nil {+ t.Fatal(err)+ }+ v2, err := downloadPath("https://github.com/o/r/releases/download/v2.4.8/"+name, name)+ if err != nil {+ t.Fatal(err)+ }+ if v1 == v2 {+ t.Fatal("an archive cached for one release must not be reused for the next")+ }+ if !strings.HasSuffix(v1, name) || !strings.HasSuffix(v2, name) {+ t.Fatalf("archive names should stay recognizable: %s / %s", v1, v2)+ }+ if filepath.Dir(v1) != filepath.Dir(v2) {+ t.Fatalf("archives should share the downloads dir: %s / %s", v1, v2)+ }+}++func TestFetchClearsResumeSidecarsWhenDestExists(t *testing.T) {+ dir := t.TempDir()+ dest := filepath.Join(dir, "archive.tar.gz")+ for _, f := range []string{dest, dest + ".part", validatorPath(dest + ".part")} {+ if err := os.WriteFile(f, []byte("x"), 0o644); err != nil {+ t.Fatal(err)+ }+ }++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Error("fetch hit the network for an artifact already on disk")+ }))+ defer srv.Close()++ if err := fetch(srv.URL, dest, "archive", downloadHTTPClient()); err != nil {+ t.Fatal(err)+ }+ for _, f := range []string{dest + ".part", validatorPath(dest + ".part"), dest + ".lock"} {+ if _, err := os.Stat(f); !os.IsNotExist(err) {+ t.Errorf("%s should not survive a completed fetch", filepath.Base(f))+ }+ }+}++func TestFetchRefusesUntrustedRedirectWithoutRetrying(t *testing.T) {+ var hits atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ http.Redirect(w, r, "https://attacker.example/payload", http.StatusFound)+ }))+ defer srv.Close()++ dest := filepath.Join(t.TempDir(), "artifact")+ err := fetch(srv.URL, dest, "artifact", downloadHTTPClient())+ if err == nil || !strings.Contains(err.Error(), "untrusted host") {+ t.Fatalf("redirect off the allowlist should fail, got %v", err)+ }+ if hits.Load() != 1 {+ t.Fatalf("a refused redirect is permanent, but it was retried %d times", hits.Load())+ }+ if have(dest) {+ t.Fatal("nothing should be written for a refused download")+ }+}diff --git a/cli/internal/provision/offline_test.go b/cli/internal/provision/offline_test.gonew file mode 100644index 0000000..7757651--- /dev/null+++ b/cli/internal/provision/offline_test.go@@ -0,0 +1,113 @@+package provision++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "sync/atomic"+ "testing"+)++func writeHealthyPython(t *testing.T) string {+ t.Helper()+ bin := PythonBin()+ if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(bin, []byte("python"), 0o755); err != nil {+ t.Fatal(err)+ }+ encodings := filepath.Join(pythonRoot(bin), "lib", "python3.12", "encodings", "__init__.py")+ if runtime.GOOS == "windows" {+ encodings = filepath.Join(pythonRoot(bin), "Lib", "encodings", "__init__.py")+ }+ if err := os.MkdirAll(filepath.Dir(encodings), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(encodings, []byte("x"), 0o644); err != nil {+ t.Fatal(err)+ }+ return bin+}++// An installed runtime must not depend on the network. Resolving the upstream release+// on every run made podcli unusable offline, spent a rate-limited GitHub API call per+// invocation, and re-provisioned whenever upstream published a new build.+func TestEnsurePythonSkipsNetworkForInstalledRuntime(t *testing.T) {+ var hits atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ w.WriteHeader(http.StatusInternalServerError)+ }))+ defer srv.Close()+ t.Cleanup(func(orig string) func() {+ return func() { pythonReleasesAPI = orig }+ }(pythonReleasesAPI))+ pythonReleasesAPI = srv.URL++ t.Setenv("PODCLI_HOME", t.TempDir())+ bin := writeHealthyPython(t)++ // A runtime installed before artifact state existed is adopted, not re-downloaded.+ if _, err := EnsurePython(""); err != nil {+ t.Fatalf("installed runtime should not need the network: %v", err)+ }+ if got := hits.Load(); got != 0 {+ t.Fatalf("release API called %d times for an installed runtime, want 0", got)+ }++ // And again, now that state is recorded.+ if _, err := EnsurePython(""); err != nil {+ t.Fatalf("second run should not need the network: %v", err)+ }+ if got := hits.Load(); got != 0 {+ t.Fatalf("release API called %d times on re-run, want 0", got)+ }++ // A swapped binary is still rejected: the local check verifies content, it does not+ // merely note the file exists.+ if err := os.WriteFile(bin, []byte("tampered"), 0o755); err != nil {+ t.Fatal(err)+ }+ if _, err := EnsurePython(""); err == nil {+ t.Fatal("tampered python runtime was trusted")+ }+ if hits.Load() == 0 {+ t.Fatal("tampered python runtime did not trigger re-provisioning")+ }+}++// `podcli setup` is the one path that may re-provision, so it is the one path that+// still asks upstream what the current build is.+func TestSetupStillVerifiesAgainstUpstream(t *testing.T) {+ var hits atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ w.WriteHeader(http.StatusInternalServerError)+ }))+ defer srv.Close()+ t.Cleanup(func(orig string) func() {+ return func() { pythonReleasesAPI = orig }+ }(pythonReleasesAPI))+ pythonReleasesAPI = srv.URL++ t.Setenv("PODCLI_HOME", t.TempDir())+ writeHealthyPython(t)+ if _, err := EnsurePython(""); err != nil {+ t.Fatal(err)+ }+ if hits.Load() != 0 {+ t.Fatal("baseline run should not have hit the network")+ }++ VerifyRemote = true+ t.Cleanup(func() { VerifyRemote = false })+ if _, err := EnsurePython(""); err == nil {+ t.Fatal("setup should surface the upstream lookup failure")+ }+ if hits.Load() == 0 {+ t.Fatal("setup did not re-verify against upstream")+ }+}diff --git a/cli/internal/provision/provision.go b/cli/internal/provision/provision.goindex 262e6c2..2af7c71 100644--- a/cli/internal/provision/provision.go+++ b/cli/internal/provision/provision.go@@ -5,9 +5,11 @@ import ("archive/tar""archive/zip""compress/gzip"+ "crypto/rand""crypto/sha256""encoding/hex""encoding/json"+ "errors""fmt""io""net/http"@@ -16,6 +18,8 @@ import ("path/filepath""runtime""strings"+ "sync"+ "sync/atomic""time""podcli/internal/paths"@@ -23,7 +27,12 @@ import (type model struct {URL string- SHA256 string // empty: verification skipped+ SHA256 string+}++type artifactState struct {+ Key string `json:"key"`+ Files map[string]string `json:"files"`}var models = map[string]model{@@ -32,10 +41,12 @@ var models = map[string]model{SHA256: "60ed5bc3dd14eea856493d334349b405782ddcaf0028d4b5df4088345fba2efe",},"tiny.en": {- URL: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.en.bin",+ URL: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.en.bin",+ SHA256: "921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1f",},"small": {- URL: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin",+ URL: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin",+ SHA256: "1be3a9b2063867b937e64e2ec7483364a79917e157fa98c5d94b5c1fffea987b",},}@@ -59,9 +70,6 @@ func have(p string) bool {func EnsureModel(size string) (string, error) {dest := ModelPath(size)- if have(dest) {- return dest, nil- }m, ok := models[size]if !ok {return "", fmt.Errorf("unknown model size %q (known: base, tiny.en, small)", size)@@ -74,9 +82,6 @@ func EnsureModel(size string) (string, error) {func EnsureVADModel() (string, error) {dest := VADModelPath()- if have(dest) {- return dest, nil- }if err := download(vadURL, dest, vadSHA, "silero-vad"); err != nil {return "", err}@@ -85,38 +90,286 @@ func EnsureVADModel() (string, error) {const maxAttempts = 6+// Fetch downloads url into dest with resume, progress, and stall detection.+// Exported so self-update reuses the same download path.+func Fetch(url, dest, label string) error { return fetch(url, dest, label, downloadHTTPClient()) }++// FetchGuarded is Fetch with a caller-supplied redirect allowlist. Self-update+// passes its GitHub-only allowlist: provisioning also trusts the model and+// ffmpeg CDNs, and the podcli binary must not be redirectable to any of them.+func FetchGuarded(url, dest, label string, allowHost func(string) bool) error {+ return fetch(url, dest, label, guardedHTTPClient(allowHost, 60*time.Second))+}+// fetch resumes via HTTP Range across transient stalls rather than restarting,-// writing to dest atomically.-func fetch(url, dest, label string) error {+// writing to dest atomically. A per-destination lock file serializes concurrent+// podcli processes so they don't append to the same .part file.+func fetch(url, dest, label string, client *http.Client) error {if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {return err}+ unlock, err := acquireLock(dest)+ if err != nil {+ return err+ }+ defer unlock()tmp := dest + ".part"+ if have(dest) {+ // Another process finished it while we waited; its .part is gone, but a+ // resume file from an earlier interrupted attempt may still sit here.+ os.Remove(tmp)+ os.Remove(validatorPath(tmp))+ return nil+ }var lastErr errorfor attempt := 1; attempt <= maxAttempts; attempt++ {- done, err := downloadOnce(url, tmp, label)+ done, err := downloadOnce(url, tmp, label, client)if err == nil && done {lastErr = nilbreak}+ if errors.Is(err, ErrUntrustedRedirect) {+ os.Remove(tmp)+ os.Remove(validatorPath(tmp))+ return err+ }lastErr = errfmt.Fprintf(os.Stderr, "\n %s interrupted (attempt %d/%d): %v - resuming\n", label, attempt, maxAttempts, err)time.Sleep(time.Duration(attempt) * time.Second)}if lastErr != nil {os.Remove(tmp)+ os.Remove(validatorPath(tmp))return lastErr}+ os.Remove(validatorPath(tmp))return os.Rename(tmp, dest)}-func download(url, dest, wantSHA, label string) error {- if err := fetch(url, dest, label); err != nil {- return err+// downloadPath places transient archives inside the managed dir rather than the+// world-shared temp dir, where a predictable name could be pre-planted by+// another local user. The dir persists across runs, so name derives from the+// source URL: a completed archive is only reused for the exact release it came+// from, never for the next one published under the same asset name.+func downloadPath(url, name string) (string, error) {+ dir := filepath.Join(paths.RuntimeDir(), "downloads")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return "", err+ }+ sum := sha256.Sum256([]byte(url))+ return filepath.Join(dir, "podcli-"+hex.EncodeToString(sum[:8])+"-"+name), nil+}++// removeArchive drops an extracted archive and the sidecars fetch leaves beside+// it. The downloads dir is persistent, so anything left there outlives the+// release it belongs to.+func removeArchive(path string) {+ os.Remove(path)+ os.Remove(path + ".part")+ os.Remove(validatorPath(path + ".part"))+}++var (+ lockHeartbeat = 20 * time.Second+ lockStale = 2 * time.Minute+ lockPoll = time.Second+ lockWait = 30 * time.Minute+ // A sharing violation on Windows clears as soon as the pending delete+ // completes; anything that outlasts this many polls is a real error.+ lockTransientRetries = 10+)++// acquireLock serializes provisioning of one artifact across processes via an+// O_EXCL sentinel. The holder heartbeats the lock while it works, so a healthy+// but slow download (ggml-small.bin on a thin link) is never mistaken for a+// crashed one and stolen mid-flight.+func acquireLock(dest string) (func(), error) {+ lock := dest + ".lock"+ deadline := time.Now().Add(lockWait)+ transient := 0+ for {+ if _, err := os.Stat(lock + ".takeover"); err == nil {+ if time.Now().After(deadline) {+ return nil, fmt.Errorf("timed out waiting for %s (another podcli may be provisioning; delete the file if not)", lock)+ }+ time.Sleep(lockPoll)+ continue+ }+ token, err := ownershipToken()+ if err != nil {+ return nil, err+ }+ f, err := os.OpenFile(lock, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)+ if err == nil {+ if _, err := f.WriteString(token); err != nil {+ f.Close()+ os.Remove(lock)+ return nil, err+ }+ if err := f.Sync(); err != nil {+ f.Close()+ os.Remove(lock)+ return nil, err+ }+ if err := f.Close(); err != nil {+ os.Remove(lock)+ return nil, err+ }+ if _, err := os.Stat(lock + ".takeover"); err == nil {+ removeOwnedLock(lock, token)+ time.Sleep(lockPoll)+ continue+ }+ return holdLock(lock, token), nil+ }+ if os.IsExist(err) {+ transient = 0+ if dropStaleLock(lock) {+ continue+ }+ } else {+ // Windows reports a sharing violation rather than "already exists"+ // while another process's delete of the lock is still pending, so a+ // racing acquirer must retry instead of treating it as fatal.+ transient+++ if transient > lockTransientRetries {+ return nil, err+ }+ }+ if time.Now().After(deadline) {+ return nil, fmt.Errorf("timed out waiting for %s (another podcli may be provisioning; delete the file if not)", lock)+ }+ time.Sleep(lockPoll)+ }+}++// holdLock keeps the lock's mtime fresh until the returned unlock runs.+func holdLock(lock, token string) func() {+ done := make(chan struct{})+ stopped := make(chan struct{})+ go func() {+ defer close(stopped)+ t := time.NewTicker(lockHeartbeat)+ defer t.Stop()+ for {+ select {+ case <-t.C:+ f, err := os.OpenFile(lock, os.O_RDWR, 0)+ if err != nil {+ return+ }+ owner := make([]byte, len(token))+ n, readErr := f.ReadAt(owner, 0)+ if readErr != nil && readErr != io.EOF {+ f.Close()+ return+ }+ if string(owner[:n]) != token {+ f.Close()+ return+ }+ if _, err := f.WriteAt([]byte(token), 0); err != nil {+ f.Close()+ return+ }+ f.Close()+ case <-done:+ return+ }+ }+ }()+ var once sync.Once+ return func() {+ once.Do(func() {+ close(done)+ <-stopped+ removeOwnedLock(lock, token)+ })+ }+}++func ownershipToken() (string, error) {+ b := make([]byte, 16)+ if _, err := rand.Read(b); err != nil {+ return "", err+ }+ return hex.EncodeToString(b), nil+}++func lockOwner(lock string) (string, error) {+ b, err := os.ReadFile(lock)+ if err != nil {+ return "", err+ }+ return strings.TrimSpace(string(b)), nil+}++func removeOwnedLock(lock, token string) bool {+ owner, err := lockOwner(lock)+ if err != nil || owner != token {+ return false+ }+ return os.Remove(lock) == nil+}++// dropStaleLock removes a lock whose holder stopped heartbeating, reporting+// whether it did. Removal is itself serialized by an O_EXCL takeover token:+// otherwise two processes seeing the same stale lock both remove and recreate+// it, the second deleting the first's fresh lock, and both then append to the+// same .part file.+func dropStaleLock(lock string) bool {+ token := lock + ".takeover"+ if fi, err := os.Stat(token); err == nil && time.Since(fi.ModTime()) > lockStale {+ if owner, readErr := lockOwner(token); readErr == nil {+ removeOwnedLock(token, owner)+ }+ return false+ }+ takeoverOwner, err := ownershipToken()+ if err != nil {+ return false+ }+ f, err := os.OpenFile(token, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)+ if err != nil {+ return false // another process is taking over; wait for its lock instead}+ if _, err := f.WriteString(takeoverOwner); err != nil {+ f.Close()+ removeOwnedLock(token, takeoverOwner)+ return false+ }+ f.Close()+ defer removeOwnedLock(token, takeoverOwner)+ fi, err := os.Stat(lock)+ if err != nil || time.Since(fi.ModTime()) <= lockStale {+ return false+ }+ owner, err := lockOwner(lock)+ if err != nil {+ return false+ }+ fi, err = os.Stat(lock)+ if err != nil || time.Since(fi.ModTime()) <= lockStale {+ return false+ }+ return removeOwnedLock(lock, owner)+}++func download(url, dest, wantSHA, label string) error {if wantSHA == "" {- fmt.Fprintf(os.Stderr, " (no pinned checksum for %s - skipped verification)\n", label)- return nil+ return fmt.Errorf("no pinned checksum for %s - refusing unverified download", label)+ }+ if have(dest) {+ got, err := sha256file(dest)+ if err == nil && strings.EqualFold(got, wantSHA) {+ return nil+ }+ if err := os.Remove(dest); err != nil {+ return fmt.Errorf("remove unverified %s: %w", label, err)+ }+ }+ if err := fetch(url, dest, label, downloadHTTPClient()); err != nil {+ return err}got, err := sha256file(dest)if err != nil {@@ -129,29 +382,97 @@ func download(url, dest, wantSHA, label string) error {return nil}-// verifyDownload checks a downloaded archive against an upstream sha256sum-style-// manifest. Fails closed on a mismatch (removes the file); fails open with a-// warning when the manifest or its entry can't be fetched, so a transient-// network issue on the sums file doesn't block provisioning.-func verifyDownload(archive, sumsURL, name string) error {- resp, err := downloadHTTPClient().Get(sumsURL)+func artifactStatePath(dir string) string {+ return filepath.Join(dir, ".podcli-artifacts")+}++// VerifyRemote makes the Ensure* functions re-resolve the upstream build and+// re-provision when it differs from what is installed. Only `podcli setup` sets it.+// Every other command relies on the local artifact state instead: resolving the+// upstream release on each run left a fully-provisioned install unable to work+// offline, spent an unauthenticated GitHub API call (60/hr/IP) per invocation, and+// re-downloaded the runtime whenever upstream published a new build.+var VerifyRemote bool++func readArtifactState(dir string) (artifactState, bool) {+ b, err := os.ReadFile(artifactStatePath(dir))if err != nil {- fmt.Fprintf(os.Stderr, " (could not fetch checksums for %s - skipped verification)\n", name)- return nil+ return artifactState{}, false}- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- fmt.Fprintf(os.Stderr, " (no checksums for %s - skipped verification)\n", name)- return nil+ var state artifactState+ if json.Unmarshal(b, &state) != nil {+ return artifactState{}, false}- data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))+ return state, true+}++func artifactContentsMatch(dir string, state artifactState, files ...string) bool {+ if len(state.Files) != len(files) {+ return false+ }+ for _, file := range files {+ rel, err := filepath.Rel(dir, file)+ if err != nil {+ return false+ }+ got, err := sha256file(file)+ if err != nil || !strings.EqualFold(got, state.Files[rel]) {+ return false+ }+ }+ return true+}++func artifactAt(dir, key string, files ...string) bool {+ state, ok := readArtifactState(dir)+ return ok && state.Key == key && artifactContentsMatch(dir, state, files...)+}++// artifactReady reports whether an installed artifact can be used without asking the+// network which build is current. Recorded hashes are re-verified, so a corrupted or+// swapped binary is still rejected. A runtime installed before artifact state existed+// is adopted with an empty key: it was checksum-verified at download time, and forcing+// every existing install to re-download on first run would be worse. The empty key+// never matches an upstream key, so the next `podcli setup` re-verifies it properly.+func artifactReady(dir string, files ...string) bool {+ state, ok := readArtifactState(dir)+ if !ok {+ return writeArtifactState(dir, "", files...) == nil+ }+ return artifactContentsMatch(dir, state, files...)+}++func writeArtifactState(dir, key string, files ...string) error {+ state := artifactState{Key: key, Files: make(map[string]string, len(files))}+ for _, file := range files {+ rel, err := filepath.Rel(dir, file)+ if err != nil {+ return err+ }+ sum, err := sha256file(file)+ if err != nil {+ return err+ }+ state.Files[rel] = sum+ }+ b, err := json.Marshal(state)if err != nil {return err}- want := ParseChecksums(data)[name]- if want == "" {- fmt.Fprintf(os.Stderr, " (no checksum entry for %s - skipped verification)\n", name)- return nil+ tmp := artifactStatePath(dir) + ".tmp"+ if err := os.WriteFile(tmp, b, 0o644); err != nil {+ return err+ }+ return os.Rename(tmp, artifactStatePath(dir))+}++// verifyDownload checks a downloaded archive against an upstream sha256sum-style+// manifest. Fails closed: a manifest that can't be fetched or has no entry for+// the asset means the download cannot be trusted.+func verifyDownload(archive, sumsURL, name string) error {+ want, err := downloadChecksum(sumsURL, name)+ if err != nil {+ return err}got, err := sha256file(archive)if err != nil {@@ -164,7 +485,29 @@ func verifyDownload(archive, sumsURL, name string) error {return nil}-func downloadOnce(url, tmp, label string) (bool, error) {+func downloadChecksum(sumsURL, name string) (string, error) {+ resp, err := downloadHTTPClient().Get(sumsURL)+ if err != nil {+ return "", fmt.Errorf("cannot verify %s: fetching checksums failed: %w", name, err)+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return "", fmt.Errorf("cannot verify %s: HTTP %d fetching checksums", name, resp.StatusCode)+ }+ data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))+ if err != nil {+ return "", err+ }+ want := ParseChecksums(data)[name]+ if want == "" {+ return "", fmt.Errorf("cannot verify %s: no entry in upstream checksums", name)+ }+ return want, nil+}++func validatorPath(tmp string) string { return tmp + ".validator" }++func downloadOnce(url, tmp, label string, client *http.Client) (bool, error) {var start int64if fi, err := os.Stat(tmp); err == nil {start = fi.Size()@@ -176,8 +519,13 @@ func downloadOnce(url, tmp, label string) (bool, error) {}if start > 0 {req.Header.Set("Range", fmt.Sprintf("bytes=%d-", start))+ // If-Range makes the server ignore Range when the file changed upstream,+ // so a resumed .part can't end up stitched from two different builds.+ if v, err := os.ReadFile(validatorPath(tmp)); err == nil && len(v) > 0 {+ req.Header.Set("If-Range", strings.TrimSpace(string(v)))+ }}- resp, err := downloadHTTPClient().Do(req)+ resp, err := client.Do(req)if err != nil {return false, err}@@ -187,10 +535,17 @@ func downloadOnce(url, tmp, label string) (bool, error) {case http.StatusRequestedRangeNotSatisfiable:return true, nil // already complete on diskcase http.StatusOK:- if start > 0 { // server ignored Range — restart cleanly+ if start > 0 { // server ignored Range or the file changed — restart cleanlyos.Truncate(tmp, 0)start = 0}+ if v := resp.Header.Get("ETag"); v != "" {+ os.WriteFile(validatorPath(tmp), []byte(v), 0o644)+ } else if v := resp.Header.Get("Last-Modified"); v != "" {+ os.WriteFile(validatorPath(tmp), []byte(v), 0o644)+ } else {+ os.Remove(validatorPath(tmp))+ }case http.StatusPartialContent:default:return false, fmt.Errorf("HTTP %d", resp.StatusCode)@@ -202,8 +557,10 @@ func downloadOnce(url, tmp, label string) (bool, error) {}defer out.Close()+ body := newStallGuard(resp.Body, 60*time.Second)+ defer body.stop()pw := &progress{label: label, total: start + resp.ContentLength, written: start}- _, copyErr := io.Copy(io.MultiWriter(out, pw), resp.Body)+ _, copyErr := io.Copy(io.MultiWriter(out, pw), body)if copyErr != nil {return false, copyErr}@@ -211,6 +568,38 @@ func downloadOnce(url, tmp, label string) (bool, error) {return true, nil}+// stallGuard aborts a body read that stops delivering bytes: the timer closes+// the connection, which surfaces here as a stall error and triggers the retry+// loop in fetch.+type stallGuard struct {+ body io.ReadCloser+ timeout time.Duration+ timer *time.Timer+ stalled atomic.Bool+}++func newStallGuard(body io.ReadCloser, timeout time.Duration) *stallGuard {+ g := &stallGuard{body: body, timeout: timeout}+ g.timer = time.AfterFunc(timeout, func() {+ g.stalled.Store(true)+ body.Close()+ })+ return g+}++func (g *stallGuard) Read(p []byte) (int, error) {+ n, err := g.body.Read(p)+ if n > 0 {+ g.timer.Reset(g.timeout)+ }+ if err != nil && err != io.EOF && g.stalled.Load() {+ return n, fmt.Errorf("stalled: no data for %s", g.timeout)+ }+ return n, err+}++func (g *stallGuard) stop() { g.timer.Stop() }+// symlinkTargetInside reports whether a symlink at linkPath pointing to linkname// resolves within root (root has a trailing separator). Absolute targets and// any path that escapes via .. are rejected — this is the symlink half of the@@ -274,26 +663,47 @@ func sha256file(path string) (string, error) {}type ffArchive struct {- URL string- Bins []string+ URL string+ SHA256 string+ Bins []string}-// Static ffmpeg sources are not yet pinned by checksum (upstream "latest" URLs).+// Pinned, versioned upstream archives, verified by SHA-256 before extraction.// darwin/arm64 is absent on purpose: evermeet.cx only builds x86_64, so Apple// Silicon is served by our own release asset (see releaseFFmpeg).var ffmpegSpecs = map[string][]ffArchive{"darwin/amd64": {- {URL: "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip", Bins: []string{"ffmpeg"}},- {URL: "https://evermeet.cx/ffmpeg/getrelease/ffprobe/zip", Bins: []string{"ffprobe"}},+ {+ URL: "https://evermeet.cx/ffmpeg/ffmpeg-8.1.2.zip",+ SHA256: "e91df72a1ee7c26606f90dd2dd4dcccc6a75140ff9ea6fdd50faae828b82ba69",+ Bins: []string{"ffmpeg"},+ },+ {+ URL: "https://evermeet.cx/ffmpeg/ffprobe-8.1.2.zip",+ SHA256: "399b93f0b9862f69767afa343e90c2f48d7e7958cadbb6deb76a012d0e3b7ce3",+ Bins: []string{"ffprobe"},+ },},"linux/amd64": {- {URL: "https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz", Bins: []string{"ffmpeg", "ffprobe"}},+ {+ URL: "https://johnvansickle.com/ffmpeg/old-releases/ffmpeg-6.0.1-amd64-static.tar.xz",+ SHA256: "28268bf402f1083833ea269331587f60a242848880073be8016501d864bd07a5",+ Bins: []string{"ffmpeg", "ffprobe"},+ },},"linux/arm64": {- {URL: "https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-arm64-static.tar.xz", Bins: []string{"ffmpeg", "ffprobe"}},+ {+ URL: "https://johnvansickle.com/ffmpeg/old-releases/ffmpeg-6.0.1-arm64-static.tar.xz",+ SHA256: "7dbd8e2f47bd83de591b9d6ea70e67d32d9aa97e7d47ae402b60c2fe3fd4d0ab",+ Bins: []string{"ffmpeg", "ffprobe"},+ },},"windows/amd64": {- {URL: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip", Bins: []string{"ffmpeg.exe", "ffprobe.exe"}},+ {+ URL: "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-07-12-13-16/ffmpeg-n8.1.2-22-g94138f6973-win64-gpl-8.1.zip",+ SHA256: "cb11f1a2628555d1ce3de984ae1dd488a26d85092d23219c574de76efbe2a62e",+ Bins: []string{"ffmpeg.exe", "ffprobe.exe"},+ },},}@@ -303,13 +713,43 @@ func WhisperCLIBin() string {return filepath.Join(paths.RuntimeDir(), "whisper", "whisper-cli"+paths.ExeSuffix())}-func latestReleaseAssets() (map[string]string, error) {- req, _ := http.NewRequest(http.MethodGet, "https://api.github.com/repos/"+podcliRepo+"/releases/latest", nil)+// githubAPIGet fetches a GitHub API URL, authenticating with GITHUB_TOKEN when+// set so provisioning doesn't burn the 60/hour unauthenticated quota.+func githubAPIGet(url string) (*http.Response, error) {+ req, _ := http.NewRequest(http.MethodGet, url, nil)req.Header.Set("Accept", "application/vnd.github+json")+ if tok := os.Getenv("GITHUB_TOKEN"); tok != "" {+ req.Header.Set("Authorization", "Bearer "+tok)+ }resp, err := releaseHTTPClient().Do(req)if err != nil {return nil, err}+ if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {+ resp.Body.Close()+ return nil, fmt.Errorf("GitHub rate limit (HTTP %d) - retry later or set GITHUB_TOKEN", resp.StatusCode)+ }+ return resp, nil+}++var releaseAssetsOnce sync.Once+var releaseAssetsMap map[string]string+var releaseAssetsErr error++// latestReleaseAssets is fetched once per process: setup asks for it per+// artifact, and unauthenticated GitHub API calls are rate limited.+func latestReleaseAssets() (map[string]string, error) {+ releaseAssetsOnce.Do(func() {+ releaseAssetsMap, releaseAssetsErr = fetchLatestReleaseAssets()+ })+ return releaseAssetsMap, releaseAssetsErr+}++func fetchLatestReleaseAssets() (map[string]string, error) {+ resp, err := githubAPIGet("https://api.github.com/repos/" + podcliRepo + "/releases/latest")+ if err != nil {+ return nil, err+ }defer resp.Body.Close()if resp.StatusCode != http.StatusOK {return nil, fmt.Errorf("no published release (HTTP %d)", resp.StatusCode)@@ -352,21 +792,32 @@ func allowedReleaseHost(h string) bool {return strings.HasSuffix(h, ".githubusercontent.com")}-func releaseHTTPClient() *http.Client {+// ErrUntrustedRedirect marks a download diverted off its allowlist. Callers that+// wrap Fetch in a retry loop must not treat it as a transient failure.+var ErrUntrustedRedirect = errors.New("refusing redirect to untrusted host")++func guardedHTTPClient(allowHost func(string) bool, headerTimeout time.Duration) *http.Client {return &http.Client{- Transport: &http.Transport{ResponseHeaderTimeout: 30 * time.Second},+ Transport: &http.Transport{+ Proxy: http.ProxyFromEnvironment,+ ResponseHeaderTimeout: headerTimeout,+ },CheckRedirect: func(req *http.Request, via []*http.Request) error {if len(via) >= 10 {return fmt.Errorf("too many redirects")}- if !allowedReleaseHost(req.URL.Hostname()) {- return fmt.Errorf("refusing redirect to untrusted host %q", req.URL.Hostname())+ if !allowHost(req.URL.Hostname()) {+ return fmt.Errorf("%w %q", ErrUntrustedRedirect, req.URL.Hostname())}return nil},}}+func releaseHTTPClient() *http.Client {+ return guardedHTTPClient(allowedReleaseHost, 30*time.Second)+}+// allowedDownloadHost pins large-binary/model downloads to their known source// hosts and CDNs. Several of these payloads (Node, CPython, ffmpeg) are not// checksum-verified, so blocking redirects to unknown hosts is the main defense@@ -391,18 +842,7 @@ func allowedDownloadHost(h string) bool {}func downloadHTTPClient() *http.Client {- return &http.Client{- Transport: &http.Transport{ResponseHeaderTimeout: 60 * time.Second},- CheckRedirect: func(req *http.Request, via []*http.Request) error {- if len(via) >= 10 {- return fmt.Errorf("too many redirects")- }- if !allowedDownloadHost(req.URL.Hostname()) {- return fmt.Errorf("refusing redirect to untrusted host %q", req.URL.Hostname())- }- return nil- },- }+ return guardedHTTPClient(allowedDownloadHost, 60*time.Second)}func httpGetBytes(url string) ([]byte, error) {@@ -418,24 +858,13 @@ func httpGetBytes(url string) ([]byte, error) {}// verifyReleaseAsset checks the file at path against the release's checksums.txt.-// It fails closed on a real checksum mismatch, but fails open (with a warning)-// when checksums.txt or the asset's entry is absent — so a release published-// before checksum manifests, or a CI hiccup, never bricks an install.+// Fails closed: checksums.txt is published with every release, so a missing+// manifest, a failed fetch, or a missing entry all mean the asset can't be+// trusted.func verifyReleaseAsset(assets map[string]string, assetName, path string) error {- sumsURL, ok := assets["checksums.txt"]- if !ok {- fmt.Fprintf(os.Stderr, " (no checksums.txt in release - skipped verification of %s)\n", assetName)- return nil- }- data, err := httpGetBytes(sumsURL)+ want, err := releaseAssetChecksum(assets, assetName)if err != nil {- fmt.Fprintf(os.Stderr, " (could not fetch checksums.txt: %v - skipped verification of %s)\n", err, assetName)- return nil- }- want, ok := ParseChecksums(data)[assetName]- if !ok {- fmt.Fprintf(os.Stderr, " (no checksum entry for %s - skipped verification)\n", assetName)- return nil+ return err}got, err := sha256file(path)if err != nil {@@ -448,12 +877,27 @@ func verifyReleaseAsset(assets map[string]string, assetName, path string) errorreturn nil}+func releaseAssetChecksum(assets map[string]string, assetName string) (string, error) {+ sumsURL, ok := assets["checksums.txt"]+ if !ok {+ return "", fmt.Errorf("cannot verify %s: release has no checksums.txt (it is published with every release - retry later)", assetName)+ }+ data, err := httpGetBytes(sumsURL)+ if err != nil {+ return "", fmt.Errorf("cannot verify %s: fetching checksums.txt failed: %w", assetName, err)+ }+ want, ok := ParseChecksums(data)[assetName]+ if !ok {+ return "", fmt.Errorf("cannot verify %s: no entry in checksums.txt", assetName)+ }+ return want, nil+}+func EnsureWhisperCpp() (string, error) {bin := WhisperCLIBin()- if nativeBin(bin) {+ if !VerifyRemote && nativeBin(bin) && artifactReady(filepath.Dir(bin), bin) {return bin, nil}- os.Remove(bin)name := fmt.Sprintf("whisper-cli-%s-%s%s", runtime.GOOS, runtime.GOARCH, paths.ExeSuffix())assets, err := latestReleaseAssets()if err != nil {@@ -463,18 +907,28 @@ func EnsureWhisperCpp() (string, error) {if !ok {return "", fmt.Errorf("asset %s not in latest release", name)}- if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil {+ want, err := releaseAssetChecksum(assets, name)+ if err != nil {return "", err}- if err := fetch(url, bin, "whisper-cli"); err != nil {+ dir := filepath.Dir(bin)+ key := name + "|" + want+ if nativeBin(bin) && artifactAt(dir, key, bin) {+ return bin, nil+ }+ os.Remove(bin)+ if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil {return "", err}- if err := verifyReleaseAsset(assets, name, bin); err != nil {+ if err := download(url, bin, want, "whisper-cli"); err != nil {return "", err}if runtime.GOOS != "windows" {os.Chmod(bin, 0o755)}+ if err := writeArtifactState(dir, key, bin); err != nil {+ return "", err+ }return bin, nil}@@ -488,28 +942,56 @@ func FFprobeBin() string {func EnsureFFmpeg() (string, error) {bin := FFmpegBin()- if nativeBin(bin) && nativeBin(FFprobeBin()) {- return bin, nil- }+ probe := FFprobeBin()dir := filepath.Join(paths.RuntimeDir(), "ffmpeg")if err := os.MkdirAll(dir, 0o755); err != nil {return "", err}+ if !VerifyRemote && nativeBin(bin) && nativeBin(probe) && artifactReady(dir, bin, probe) {+ return bin, nil+ }if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {- return bin, releaseFFmpeg()+ assets, err := latestReleaseAssets()+ if err != nil {+ return "", err+ }+ key := ""+ checksums := map[string]string{}+ for _, tool := range []string{"ffmpeg", "ffprobe"} {+ name := fmt.Sprintf("%s-%s-%s", tool, runtime.GOOS, runtime.GOARCH)+ want, err := releaseAssetChecksum(assets, name)+ if err != nil {+ return "", err+ }+ checksums[name] = want+ key += name + "|" + want + "\n"+ }+ if nativeBin(bin) && nativeBin(probe) && artifactAt(dir, key, bin, probe) {+ return bin, nil+ }+ return bin, releaseFFmpeg(assets, checksums, key)}specs, ok := ffmpegSpecs[runtime.GOOS+"/"+runtime.GOARCH]if !ok {return "", fmt.Errorf("no ffmpeg build for %s/%s", runtime.GOOS, runtime.GOARCH)}+ key := ""+ for _, spec := range specs {+ key += spec.URL + "|" + spec.SHA256 + "\n"+ }+ if nativeBin(bin) && nativeBin(probe) && artifactAt(dir, key, bin, probe) {+ return bin, nil+ }for _, a := range specs {- sum := sha256.Sum256([]byte(a.URL))- archive := filepath.Join(os.TempDir(), "podcli-ff-"+hex.EncodeToString(sum[:8]))- if err := fetch(a.URL, archive, "ffmpeg-archive"); err != nil {+ archive, err := downloadPath(a.URL, "ffmpeg-archive")+ if err != nil {return "", err}- err := extractBins(archive, a.Bins, dir)- os.Remove(archive)+ if err := download(a.URL, archive, a.SHA256, "ffmpeg-archive"); err != nil {+ return "", err+ }+ err = extractBins(archive, a.Bins, dir)+ removeArchive(archive)if err != nil {return "", err}@@ -517,17 +999,16 @@ func EnsureFFmpeg() (string, error) {if !have(bin) {return "", fmt.Errorf("ffmpeg missing after extraction in %s", dir)}+ if err := writeArtifactState(dir, key, bin, probe); err != nil {+ return "", err+ }return bin, nil}// Apple Silicon builds ship with the release, checksum-verified like whisper-cli.// No upstream publishes an arm64 macOS static, so ffmpeg used to arrive as an// x86_64 binary that ran under Rosetta at roughly a third of native encode speed.-func releaseFFmpeg() error {- assets, err := latestReleaseAssets()- if err != nil {- return err- }+func releaseFFmpeg(assets, checksums map[string]string, key string) error {for tool, bin := range map[string]string{"ffmpeg": FFmpegBin(), "ffprobe": FFprobeBin()} {name := fmt.Sprintf("%s-%s-%s", tool, runtime.GOOS, runtime.GOARCH)url, ok := assets[name]@@ -535,17 +1016,14 @@ func releaseFFmpeg() error {return fmt.Errorf("asset %s not in latest release", name)}os.Remove(bin)- if err := fetch(url, bin, tool); err != nil {- return err- }- if err := verifyReleaseAsset(assets, name, bin); err != nil {+ if err := download(url, bin, checksums[name], tool); err != nil {return err}if err := os.Chmod(bin, 0o755); err != nil {return fmt.Errorf("chmod %s: %w", bin, err)}}- return nil+ return writeArtifactState(filepath.Dir(FFmpegBin()), key, FFmpegBin(), FFprobeBin())}func extractBins(archive string, bins []string, dest string) error {@@ -684,14 +1162,14 @@ func pythonRoot(bin string) string {// pythonAssetURL resolves a python-build-standalone install_only tarball for// this platform via the GitHub latest-release API, so it tracks upstream// without a hardcoded version that rots.+var pythonReleasesAPI = "https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest"+func pythonAssetURL() (url, name, sumsURL string, err error) {triple, ok := pyTriples[runtime.GOOS+"/"+runtime.GOARCH]if !ok {return "", "", "", fmt.Errorf("no python build for %s/%s", runtime.GOOS, runtime.GOARCH)}- req, _ := http.NewRequest(http.MethodGet, "https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest", nil)- req.Header.Set("Accept", "application/vnd.github+json")- resp, err := releaseHTTPClient().Do(req)+ resp, err := githubAPIGet(pythonReleasesAPI)if err != nil {return "", "", "", err}@@ -734,32 +1212,42 @@ func pythonAssetURL() (url, name, sumsURL string, err error) {func EnsurePython(requirements string) (string, error) {bin := PythonBin()- if !pythonHealthy(bin) {- root := pythonRoot(bin)- if err := os.RemoveAll(root); err != nil {- return "", fmt.Errorf("remove corrupted Python runtime %s: %w (close any running podcli or Python subprocesses)", root, err)- }+ root := pythonRoot(bin)+ if VerifyRemote || !pythonHealthy(bin) || !artifactReady(root, bin) {url, name, sumsURL, err := pythonAssetURL()if err != nil {return "", err}- sum := sha256.Sum256([]byte(url))- archive := filepath.Join(os.TempDir(), "podcli-py-"+hex.EncodeToString(sum[:8])+".tar.gz")- if err := fetch(url, archive, "cpython"); err != nil {- return "", err+ if sumsURL == "" {+ return "", fmt.Errorf("cannot verify %s: release has no SHA256SUMS asset", name)}- if sumsURL != "" {- if err := verifyDownload(archive, sumsURL, name); err != nil {- return "", err- }- }- err = extractTarGz(archive, paths.RuntimeDir())- os.Remove(archive)+ want, err := downloadChecksum(sumsURL, name)if err != nil {return "", err}- if !pythonHealthy(bin) {- return "", fmt.Errorf("python runtime missing stdlib encodings after extraction")+ key := name + "|" + want+ if !pythonHealthy(bin) || !artifactAt(root, key, bin) {+ if err := os.RemoveAll(root); err != nil {+ return "", fmt.Errorf("remove corrupted Python runtime %s: %w (close any running podcli or Python subprocesses)", root, err)+ }+ archive, err := downloadPath(url, "cpython.tar.gz")+ if err != nil {+ return "", err+ }+ if err := download(url, archive, want, "cpython"); err != nil {+ return "", err+ }+ err = extractTarGz(archive, paths.RuntimeDir())+ removeArchive(archive)+ if err != nil {+ return "", err+ }+ if !pythonHealthy(bin) {+ return "", fmt.Errorf("python runtime missing stdlib encodings after extraction")+ }+ if err := writeArtifactState(root, key, bin); err != nil {+ return "", err+ }}}if requirements != "" {@@ -901,18 +1389,38 @@ func extractTarGz(archive, dest string) error {return nil}+// stderrIsTTY gates \r-style in-place progress: piped to a file or CI log, the+// carriage returns would pile up as one unreadable line, so non-TTY output gets+// periodic full lines instead.+var stderrIsTTY = func() bool {+ fi, err := os.Stderr.Stat()+ return err == nil && fi.Mode()&os.ModeCharDevice != 0+}()+type progress struct {label stringtotal int64written int64lastPct intlastTick time.Time+ lastLine time.Time}func (p *progress) Write(b []byte) (int, error) {n := len(b)p.written += int64(n)now := time.Now()+ if !stderrIsTTY {+ if now.Sub(p.lastLine) >= 5*time.Second {+ p.lastLine = now+ if p.total > 0 {+ fmt.Fprintf(os.Stderr, " fetching %s ... %d%% (%d/%d MB)\n", p.label, int(p.written*100/p.total), p.written>>20, p.total>>20)+ } else {+ fmt.Fprintf(os.Stderr, " fetching %s ... %d MB\n", p.label, p.written>>20)+ }+ }+ return n, nil+ }if now.Sub(p.lastTick) < 200*time.Millisecond {return n, nil}@@ -930,5 +1438,9 @@ func (p *progress) Write(b []byte) (int, error) {}func (p *progress) done() {+ if !stderrIsTTY {+ fmt.Fprintf(os.Stderr, " fetching %s ... done (%d MB)\n", p.label, p.written>>20)+ return+ }fmt.Fprintf(os.Stderr, "\r fetching %s ... done (%d MB)%s\n", p.label, p.written>>20, " ")}diff --git a/cli/internal/provision/studio.go b/cli/internal/provision/studio.goindex aaa10b2..a264ab4 100644--- a/cli/internal/provision/studio.go+++ b/cli/internal/provision/studio.go@@ -53,7 +53,7 @@ func writeBundleStamp(dir, version string) {func EnsureNode() (string, error) {bin := NodeBin()- if have(bin) {+ if !VerifyRemote && nativeBin(bin) && artifactReady(NodeDir(), bin) {return bin, nil}triple, ok := nodeTriples[runtime.GOOS+"/"+runtime.GOARCH]@@ -66,18 +66,26 @@ func EnsureNode() (string, error) {}base := fmt.Sprintf("node-v%s-%s", nodeVersion, triple)url := fmt.Sprintf("https://nodejs.org/dist/v%s/%s.%s", nodeVersion, base, ext)- archive := filepath.Join(os.TempDir(), "podcli-"+base+"."+ext)- if err := fetch(url, archive, "node"); err != nil {+ sumsURL := fmt.Sprintf("https://nodejs.org/dist/v%s/SHASUMS256.txt", nodeVersion)+ want, err := downloadChecksum(sumsURL, base+"."+ext)+ if err != nil {return "", err}- defer os.Remove(archive)- if err := verifyDownload(archive, fmt.Sprintf("https://nodejs.org/dist/v%s/SHASUMS256.txt", nodeVersion), base+"."+ext); err != nil {+ key := base + "|" + want+ if nativeBin(bin) && artifactAt(NodeDir(), key, bin) {+ return bin, nil+ }+ archive, err := downloadPath(url, base+"."+ext)+ if err != nil {+ return "", err+ }+ defer removeArchive(archive)+ if err := download(url, archive, want, "node"); err != nil {return "", err}if err := os.RemoveAll(NodeDir()); err != nil {return "", err}- var err errorif ext == "zip" {err = extractZipStrip1(archive, NodeDir())} else {@@ -92,6 +100,9 @@ func EnsureNode() (string, error) {if !have(bin) {return "", fmt.Errorf("node missing after extraction in %s", NodeDir())}+ if err := writeArtifactState(NodeDir(), key, bin); err != nil {+ return "", err+ }return bin, nil}@@ -115,11 +126,14 @@ func EnsureRemotion(version string) (string, error) {if !ok {return "", fmt.Errorf("asset %s not in latest release", name)}- archive := filepath.Join(os.TempDir(), "podcli-"+name)- if err := fetch(url, archive, "remotion"); err != nil {+ archive, err := downloadPath(url, name)+ if err != nil {+ return "", err+ }+ if err := fetch(url, archive, "remotion", downloadHTTPClient()); err != nil {return "", err}- defer os.Remove(archive)+ defer removeArchive(archive)if err := verifyReleaseAsset(assets, name, archive); err != nil {return "", err}@@ -183,11 +197,14 @@ func EnsureStudio(version string) (string, error) {if !ok {return "", fmt.Errorf("asset studio-bundle.tar.gz not in latest release")}- archive := filepath.Join(os.TempDir(), "podcli-studio-bundle.tar.gz")- if err := fetch(url, archive, "studio"); err != nil {+ archive, err := downloadPath(url, "studio-bundle.tar.gz")+ if err != nil {+ return "", err+ }+ if err := fetch(url, archive, "studio", downloadHTTPClient()); err != nil {return "", err}- defer os.Remove(archive)+ defer removeArchive(archive)if err := verifyReleaseAsset(assets, "studio-bundle.tar.gz", archive); err != nil {return "", err}diff --git a/cli/internal/update/update.go b/cli/internal/update/update.goindex 65a990d..932e722 100644--- a/cli/internal/update/update.go+++ b/cli/internal/update/update.go@@ -79,7 +79,10 @@ func allowedHost(h string) bool {func guardedClient() *http.Client {return &http.Client{- Transport: &http.Transport{ResponseHeaderTimeout: 30 * time.Second},+ Transport: &http.Transport{+ Proxy: http.ProxyFromEnvironment,+ ResponseHeaderTimeout: 30 * time.Second,+ },CheckRedirect: func(req *http.Request, via []*http.Request) error {if len(via) >= 10 {return fmt.Errorf("too many redirects")@@ -133,27 +136,46 @@ func newer(remote, current string) bool {return false}+const checkInterval = 24 * time.Hour+// NotifyIfOutdated prints a one-line notice when a newer release exists. Fast,-// silent on any error, and respects the off-switch.+// silent on any error, respects the off-switch, and hits the network at most+// once per day (result cached in config.json).func NotifyIfOutdated(current string) {if !config.AutoUpdate() {return}- tag, err := latestTag(1500 * time.Millisecond)- if err != nil {- return+ tag, ok := config.CachedUpdateCheck(checkInterval)+ if !ok {+ var err error+ tag, err = latestTag(1500 * time.Millisecond)+ if err != nil {+ return+ }+ config.RecordUpdateCheck(tag)}if newer(tag, current) {fmt.Fprintf(os.Stderr, " podcli %s available (you have %s) - run `podcli update`\n", tag, current)}}+// CleanupOldBinary removes the podcli.exe.old a Windows self-update leaves+// behind (the running exe can't be deleted during the swap). Best-effort: the+// file stays locked while the previous binary is still exiting.+func CleanupOldBinary() {+ if runtime.GOOS != "windows" {+ return+ }+ os.Remove(managedBin() + ".old")+}+func Run(current string) int {tag, err := latestTag(10 * time.Second)if err != nil {fmt.Fprintf(os.Stderr, "podcli: update check failed: %v\n", err)return 1}+ config.RecordUpdateCheck(tag)if !newer(tag, current) {fmt.Printf("podcli %s is up to date.\n", current)return 0@@ -228,20 +250,16 @@ func apply(tag string) error {}// verifyStaged checks the downloaded binary against the release's checksums.txt.-// Fails closed on a mismatch; fails open (warning) only when checksums.txt is-// absent, so an older release without a manifest still updates.+// Fails closed: updates always target the latest release, and checksums.txt is+// published with every release, so its absence means the binary can't be trusted.func verifyStaged(tag, staged string) error {resp, err := guardedClient().Get(checksumsURL(tag))if err != nil {- return err+ return fmt.Errorf("cannot verify update: fetching checksums.txt failed: %w", err)}defer resp.Body.Close()- if resp.StatusCode == http.StatusNotFound {- fmt.Fprintln(os.Stderr, " (no checksums.txt in release - skipped verification)")- return nil- }if resp.StatusCode != http.StatusOK {- return fmt.Errorf("HTTP %d fetching checksums.txt", resp.StatusCode)+ return fmt.Errorf("cannot verify update: HTTP %d fetching checksums.txt (it is published with every release - retry later)", resp.StatusCode)}data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))if err != nil {@@ -249,8 +267,7 @@ func verifyStaged(tag, staged string) error {}want, ok := provision.ParseChecksums(data)[assetName()]if !ok {- fmt.Fprintf(os.Stderr, " (no checksum entry for %s - skipped verification)\n", assetName())- return nil+ return fmt.Errorf("cannot verify update: no entry for %s in checksums.txt", assetName())}got, err := provision.Sha256File(staged)if err != nil {@@ -286,25 +303,10 @@ func swap(staged, dest string) error {return os.Rename(staged, dest)}+// downloadFile reuses provisioning's resumable download, but keeps this path's+// narrower redirect allowlist: provisioning also trusts the model and ffmpeg+// CDNs, and nothing outside GitHub may serve the podcli binary.func downloadFile(url, dest string) error {- resp, err := guardedClient().Get(url)- if err != nil {- return err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("HTTP %d for %s", resp.StatusCode, url)- }- tmp := dest + ".part"- f, err := os.Create(tmp)- if err != nil {- return err- }- _, err = io.Copy(f, resp.Body)- f.Close()- if err != nil {- os.Remove(tmp)- return err- }- return os.Rename(tmp, dest)+ os.Remove(dest) // a stale staged binary must not satisfy Fetch's have() check+ return provision.FetchGuarded(url, dest, "podcli", allowedHost)}diff --git a/cli/internal/update/update_test.go b/cli/internal/update/update_test.goindex c6ec7c7..aea0951 100644--- a/cli/internal/update/update_test.go+++ b/cli/internal/update/update_test.go@@ -3,10 +3,16 @@ package updateimport ("bytes""errors"+ "net/http"+ "net/http/httptest""os""path/filepath""strings""testing"+ "time"++ "podcli/internal/config"+ "podcli/internal/provision")func TestSwapReplacesBinary(t *testing.T) {@@ -47,6 +53,21 @@ func TestNewer(t *testing.T) {}}+func TestUpdateCheckCache(t *testing.T) {+ t.Setenv("PODCLI_HOME", t.TempDir())+ if _, ok := config.CachedUpdateCheck(24 * time.Hour); ok {+ t.Fatal("fresh config should have no cached check")+ }+ config.RecordUpdateCheck("9.9.9")+ tag, ok := config.CachedUpdateCheck(24 * time.Hour)+ if !ok || tag != "9.9.9" {+ t.Fatalf("cached check = %q, %v; want 9.9.9 within 24h", tag, ok)+ }+ if _, ok := config.CachedUpdateCheck(0); ok {+ t.Fatal("expired cache should force a re-check")+ }+}+func TestSelfUpdateFailureOmitsPackageManagerFallback(t *testing.T) {var out bytes.BufferprintSelfUpdateFailure(&out, errors.New("boom"))@@ -62,6 +83,26 @@ func TestSelfUpdateFailureOmitsPackageManagerFallback(t *testing.T) {}}+// The provisioning allowlist also trusts the model and ffmpeg CDNs; a release+// asset URL that redirects to one of them must still be refused for the binary.+func TestDownloadFileRefusesRedirectOffGitHub(t *testing.T) {+ for _, host := range []string{"https://evermeet.cx/payload", "https://huggingface.co/payload"} {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, host, http.StatusFound)+ }))+ dest := filepath.Join(t.TempDir(), "podcli.new")+ err := downloadFile(srv.URL, dest)+ srv.Close()++ if !errors.Is(err, provision.ErrUntrustedRedirect) {+ t.Fatalf("redirect to %s should be refused, got %v", host, err)+ }+ if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) {+ t.Fatalf("refused download left a staged binary behind: %v", statErr)+ }+ }+}+func TestDownloadFailureSuggestsRetry(t *testing.T) {var out bytes.BufferprintSelfUpdateFailure(&out, &phaseError{phase: phaseDownload, err: errors.New("network down")})diff --git a/cli/main.go b/cli/main.goindex 0a7da03..a6ba4ef 100644--- a/cli/main.go+++ b/cli/main.go@@ -22,6 +22,7 @@ import (func main() {os.Setenv("PODCLI_VERSION", Version)+ update.CleanupOldBinary()args := os.Args[1:]if len(args) == 0 {os.Exit(runEngine(args)) // backend's branded interactive menu@@ -107,7 +108,9 @@ func refreshStudioBundles() {func ensureRuntime() error {if _, ok := engine.BackendRoot(); !ok {fmt.Fprintln(os.Stderr, "First run - setting up podcli (one-time download)...")- setup(nil)+ if setup(nil) != 0 {+ return fmt.Errorf("first-run setup failed (see errors above) - run `podcli setup` to retry")+ }} else if err := refreshBackend(); err != nil {return err}@@ -266,6 +269,10 @@ func setup(args []string) int {refresh = true}}+ // setup is the one path that may re-provision, so it is the one path allowed to ask+ // upstream what the current build is. Every other command trusts the local artifact+ // state and stays offline-capable.+ provision.VerifyRemote = truefmt.Printf("Provisioning into %s\n", paths.Home())// Extracted from the binary, so it costs nothing and can't fail on a bad network.// First, so an interrupted or offline setup still leaves a backend matching this@@ -411,7 +418,7 @@ func mcpInstall() int {}func uninstall(args []string) int {- yes, dryRun := false, false+ yes, dryRun, purge := false, false, falsefor _, a := range args {switch a {case "--yes", "-y":@@ -419,7 +426,7 @@ func uninstall(args []string) int {case "--dry-run":dryRun = truecase "--purge":- // Kept for compatibility; uninstall already removes everything.+ purge = truecase "--help", "-h":printUninstallHelp()return 0@@ -436,11 +443,16 @@ func uninstall(args []string) int {if !pathContains(paths.BinDir(), self) {self = ""}- targets := uninstallTargets(home)+ targets := uninstallTargets(home, purge)links := podcliLinks(managed, self)fmt.Println("podcli uninstall")- fmt.Printf(" This will remove podcli and all managed data under: %s\n", home)+ if purge {+ fmt.Printf(" This will remove podcli and all managed data under: %s\n", home)+ } else {+ fmt.Printf(" This will remove podcli app files under: %s\n", home)+ fmt.Println(" User data (config, knowledge, presets, assets, history, cache) is kept - pass --purge to remove it too.")+ }for _, p := range targets {fmt.Printf(" remove: %s\n", p)}@@ -488,12 +500,26 @@ func uninstall(args []string) int {fmt.Fprintf(os.Stderr, " note: the running binary is still in use and was left in place: %s\n", self)fmt.Fprintln(os.Stderr, " Delete it after this command exits, or run the installer script with --uninstall.")}- fmt.Println("Done - podcli app files were removed.")+ if purge {+ fmt.Println("Done - podcli and all managed data were removed.")+ } else {+ fmt.Println("Done - podcli app files were removed (user data kept).")+ }return 0}-func uninstallTargets(home string) []string {- return []string{home}+// uninstallTargets lists what uninstall removes. By default only the app dirs+// go; user data (config.json, knowledge, presets, assets, history, cache) sits+// directly under home and survives unless --purge removes the whole dir.+func uninstallTargets(home string, purge bool) []string {+ if purge {+ return []string{home}+ }+ return []string{+ filepath.Join(home, "bin"),+ filepath.Join(home, "runtime"),+ filepath.Join(home, "models"),+ }}func podcliLinks(managed, self string) []string {@@ -598,12 +624,13 @@ func confirm(prompt string) bool {func printUninstallHelp() {fmt.Println(`Usage: podcli uninstall [--yes] [--dry-run] [--purge]-Removes podcli's managed folder, user data, and installer-created links.+Removes podcli's app files (bin, runtime, models) and installer-created links.+User data (config, knowledge, presets, assets, history, cache) is kept.Options:-y, --yes Do not prompt for confirmation--dry-run Show what would be removed without deleting anything- --purge Kept for compatibility; uninstall already removes everything`)+ --purge Also remove user data (deletes the entire podcli folder)`)}// backendStamp annotates an unmanaged or out-of-date backend, the drift thediff --git a/cli/uninstall_test.go b/cli/uninstall_test.goindex 1f6c6ad..c387593 100644--- a/cli/uninstall_test.go+++ b/cli/uninstall_test.go@@ -30,11 +30,32 @@ func TestLinkPointsToAbsoluteAndRelativeSymlinks(t *testing.T) {}}-func TestUninstallTargetsRemoveAllByDefault(t *testing.T) {+func TestUninstallTargetsKeepUserDataByDefault(t *testing.T) {home := filepath.Join(t.TempDir(), "podcli")- got := uninstallTargets(home)+ got := uninstallTargets(home, false)+ want := map[string]bool{+ filepath.Join(home, "bin"): true,+ filepath.Join(home, "runtime"): true,+ filepath.Join(home, "models"): true,+ }+ if len(got) != len(want) {+ t.Fatalf("uninstall targets = %v, want app dirs only", got)+ }+ for _, p := range got {+ if p == home {+ t.Fatalf("default uninstall must not remove the whole home dir")+ }+ if !want[p] {+ t.Fatalf("unexpected uninstall target %s", p)+ }+ }+}++func TestUninstallTargetsPurgeRemovesHome(t *testing.T) {+ home := filepath.Join(t.TempDir(), "podcli")+ got := uninstallTargets(home, true)if len(got) != 1 || got[0] != home {- t.Fatalf("uninstall targets = %v, want only %s", got, home)+ t.Fatalf("purge targets = %v, want only %s", got, home)}}diff --git a/docs/configuration.md b/docs/configuration.mdindex e6cdcdc..ba10292 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -12,11 +12,12 @@ Copy `.env.example` to `.env`, or export these in your shell. `setup.sh` copies| `PODCLI_QUALITY` | `high` | Render quality profile || `PODCLI_NO_UPDATE` | unset | Set to `1` to skip the update check. Same as `podcli config set update.auto off` || `PODCLI_LOG_LEVEL` | `info` | Logging verbosity |-| `PORT` | `3847` | Web studio port |+| `PODCLI_PORT` | `3847` | Web studio port. `PORT` also works. Set it in the MCP client's env too, or the MCP tools render without live studio progress || `HF_TOKEN` | unset | Hugging Face token, required for speaker diarization || `PODCLI_ENV_FILE` | `./.env` | Path to an alternate `.env` || `PODCLI_BACKEND` | resolved | Override the Python backend directory |-| `PODCLI_PYTHON` | resolved | Override the Python interpreter |+| `PODCLI_PYTHON` | resolved | Override the Python interpreter. The launcher exports the resolved path as `PYTHON_PATH` for internal use |+| `PODCLI_TRANSITION_AUTOFIX_PASSES` | auto | Transition QA/autofix passes. Runs only on reframes that can produce hard cuts. Set a number to force it, `0` disables; the renderer caps it at 2 || `FFMPEG_PATH` / `FFPROBE_PATH` | `ffmpeg` / `ffprobe` | Override the FFmpeg binaries |Installed builds provision their own Python, Node, FFmpeg, and whisper.cpp, so the@@ -62,7 +63,9 @@ podcli config migrate # apply## Transcript formatpodcli auto-transcribes with Whisper, and it accepts an existing transcript with-`--transcript`. Drag-drop `.txt`, `.srt`, and `.vtt` work in the studio.+`--transcript`: `.txt`, `.srt`, `.vtt`, and `.json` are detected by content. The+same formats drag-drop into the studio. When the video was transcribed before,+`--transcript` reuses the cached face map so speaker framing survives the swap.```Speaker Name (00:00)@@ -80,8 +83,9 @@ The time offset field (default `-1s`) shifts every timestamp to sync with the auengine reads them for voice rules and title formulas, and checks the episode databaseso it does not resuggest a moment you already published.-PodStack ships 13 starter templates covering brand identity, voice and tone, the-episode database, shorts criteria, title formulas, description templates, thumbnail-guides, topics, workflow, and quick reference. Fill them in with your show's details.+`podcli knowledge init` creates the 14 starter templates covering brand identity,+voice and tone, the episode database, shorts criteria, title formulas, description+templates, thumbnail guides, topics, workflow, quick reference, and cross-episode+learnings. Fill them in with your show's details.Edit them in the studio under Knowledge, or through the `knowledge_base` MCP tool.diff --git a/install.cmd b/install.cmdindex 81166cd..b8777e4 100644--- a/install.cmd+++ b/install.cmd@@ -2,17 +2,17 @@setlocalcd /d "%~dp0"-echo Installing podcli - this can take a few minutes (downloads Whisper, Python and Node packages)...+echo Installing podcli - downloads the prebuilt binary (runtimes are provisioned on first run)...echo.-powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0setup.ps1" -Install+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1"set "RC=%ERRORLEVEL%"echo.if not "%RC%"=="0" (echo Install failed with code %RC%. Review the messages above.) else (- echo Install complete. To open the studio, run: powershell -ExecutionPolicy Bypass -File setup.ps1 -Ui+ echo Install complete. Restart your terminal, then run: podcli)echo.pausediff --git a/install.ps1 b/install.ps1index 50a8608..e7d22d6 100644--- a/install.ps1+++ b/install.ps1@@ -53,7 +53,7 @@ if ($Uninstall) {if ($Purge) {$targets = @($homeDir)} else {- $targets = @($binDir, (Join-Path $homeDir 'runtime'), (Join-Path $homeDir 'models'), (Join-Path $homeDir 'tools'))+ $targets = @($binDir, (Join-Path $homeDir 'runtime'), (Join-Path $homeDir 'models'))}foreach ($p in $targets) {if (Test-Path $p) {diff --git a/install.sh b/install.shindex e0e0009..707ba04 100755--- a/install.sh+++ b/install.sh@@ -3,6 +3,7 @@# or ffmpeg needed; the binary provisions those itself on first run).# Usage: curl -fsSL https://raw.githubusercontent.com/nmbrthirteen/podcli/main/install.sh | sh# Uninstall: curl -fsSL https://raw.githubusercontent.com/nmbrthirteen/podcli/main/install.sh | sh -s -- --uninstall+# Purge: curl -fsSL https://raw.githubusercontent.com/nmbrthirteen/podcli/main/install.sh | sh -s -- --uninstall --purgeset -euREPO="nmbrthirteen/podcli"@@ -19,6 +20,8 @@ esacbin_dir="$home_dir/bin"if [ "${1:-}" = "--uninstall" ]; then+ purge=0+ [ "${2:-}" = "--purge" ] && purge=1echo "Uninstalling podcli..."for d in /usr/local/bin "$HOME/.local/bin"; dolink="$d/podcli"@@ -30,7 +33,12 @@ if [ "${1:-}" = "--uninstall" ]; thenfifidone- for p in "$bin_dir" "$home_dir/runtime" "$home_dir/models" "$home_dir/tools"; do+ if [ "$purge" = 1 ]; then+ set -- "$home_dir"+ else+ set -- "$bin_dir" "$home_dir/runtime" "$home_dir/models"+ fi+ for p in "$@"; doif [ -e "$p" ]; thenif rm -rf "$p"; thenecho " removed: $p"@@ -39,9 +47,13 @@ if [ "${1:-}" = "--uninstall" ]; thenfifidone- echo " removed app files from: $home_dir"- echo " kept user data (config, knowledge, presets, assets, history, cache)."- echo " To remove everything: rm -rf '$home_dir'"+ if [ "$purge" = 1 ]; then+ echo " removed podcli and all managed data from: $home_dir"+ else+ echo " removed app files from: $home_dir"+ echo " kept user data (config, knowledge, presets, assets, history, cache)."+ echo " To remove everything, re-run with: --uninstall --purge"+ fiexit 0fi@@ -52,7 +64,7 @@ case "$arch" inesactarget="${goos}-${goarch}"if [ "$target" = "darwin-amd64" ]; then- err "Intel Macs aren't supported yet (coming in v2.0.1). Apple Silicon, Linux, and Windows are available."+ err "Intel Macs aren't supported yet. Apple Silicon, Linux, and Windows are available."fimkdir -p "$bin_dir"diff --git a/plans/native-cli.md b/plans/native-cli.mdindex 32b9d0e..e405cf1 100644--- a/plans/native-cli.md+++ b/plans/native-cli.md@@ -1,11 +1,11 @@# podcli → Native CLI (codex-style)-> Goal: turn podcli from a git-clone + `setup.sh` + venv/npm hybrid into a **native CLI you install once and that auto-updates** — like `openai/codex`. Users run `npm i -g podcli` (or `bun add -g podcli`) and `podcli process video.mp4` just works, everywhere, with no Python/Node/FFmpeg setup.+> Goal: turn podcli from a git-clone + `setup.sh` + venv/npm hybrid into a **native CLI you install once and that auto-updates**, like `openai/codex`. Users run the install script (`curl -fsSL https://podcli.com/install.sh | sh`; npm distribution is out because the unscoped `podcli` name is blocked, see RELEASE.md) and `podcli process video.mp4` just works, everywhere, with no Python/Node/FFmpeg setup.## North star```-npm i -g podcli # or: bun add -g podcli+curl -fsSL https://podcli.com/install.sh | shpodcli process pod.mp4 --top 5→ first run: silently provisions a hermetic runtime (one time)→ 9:16 clips with burned captions@@ -38,8 +38,8 @@ You can't fold PyTorch + Chromium + FFmpeg into one static binary. So we **packa| **Transcription** | **whisper.cpp** replaces `openai-whisper`/PyTorch. GGUF models. Metal on Apple Silicon, CUDA/CPU elsewhere. ~145MB vs ~2GB. || **Bundle model** | Tiny launcher; **first run provisions the full core stack** (download-once, like today's `setup.sh` but automatic + cross-platform). || **Storage** | **Global** managed dir for runtimes + model cache (`%LOCALAPPDATA%\podcli` / `~/Library/Application Support/podcli` / `~/.local/share/podcli`). **Per-project** `.podcli/` (knowledge, output, history) stays in cwd — podcli stays project-scoped like git. |-| **Distribution** | **npm + bun only.** Thin wrapper package fetches the platform binary on install (codex-style). **No code signing, no brew/winget/curl\|sh/.exe.** |-| **Auto-update** | On launch: fast (~250ms, short-timeout) check against GitHub Releases. Newer → update then load. Offline/slow → proceed on current version (never blocks). Self-replace the managed binary in `~/.podcli/bin/`; if that's impossible, print the matching upgrade command (`npm i -g podcli` / `bun add -g podcli`). |+| **Distribution** | **Install script** (`curl -fsSL https://podcli.com/install.sh \| sh`, `irm https://podcli.com/install.ps1 \| iex`) fetching the platform binary from GitHub Releases. npm is out: the unscoped `podcli` name is blocked (see RELEASE.md). Code signing is not in place yet. |+| **Auto-update** | On launch: fast (~250ms, short-timeout) check against GitHub Releases, cached for 24h. Newer → update then load. Offline/slow → proceed on current version (never blocks). Self-replace the managed binary in the managed `bin/`; if that's impossible, print the matching install-script command. || **Update opt-out** | Persistent off switch: `podcli config set update.auto off` + `PODCLI_NO_UPDATE=1`. When off: no checks, runs installed version. `podcli update` still works on demand. || **AI features** | API key preferred → AI-CLI fallback → core works without. If a key is set, call the Claude/OpenAI API directly (self-contained); else shell to installed Claude/Codex CLI (today's behavior); else the video pipeline still works and AI features print how to enable them. || **Platforms** | macOS arm64, macOS x64, Linux x64, Linux arm64, Windows x64. |@@ -98,11 +98,11 @@ Clean seam: `backend/services/transcription.py::transcribe_file()` returns a fix- Remove `openai-whisper` from `requirements.txt`; confirm captions (karaoke/Hormozi/subtle) still render correctly.### Phase 2 — Distribution + self-update (→ first installable release)-- CI matrix builds the Go launcher for all **5 targets**.-- **npm + bun wrapper package**: `postinstall` downloads the platform binary into `~/.podcli/bin/`; `bin` shim execs it. Publish to npm (bun consumes the same registry).-- GitHub Release per version carries: the 5 binaries + a **version manifest** pinning required runtime versions (so an update knows what to re-provision).-- Self-update: fast on-launch check, atomic self-replace of the managed binary, npm/bun fallback message, `PODCLI_NO_UPDATE` + `config set update.auto off`, `podcli update`, keep-previous-binary for `podcli rollback`.-- **Ship.** `npm i -g podcli` → `podcli process` works hermetic on all 5 platforms and auto-updates. ← *this is the MVP gate.*+- CI matrix builds the Go launcher for all **4 targets** (darwin-arm64, linux-amd64, linux-arm64, windows-amd64).+- **Install script** resolves the latest release and drops the platform binary into the managed `bin/`, adding it to PATH.+- GitHub Release per version carries: the 4 launchers, the runtime assets (whisper-cli, ffmpeg, studio and remotion bundles), and `checksums.txt` covering every asset.+- Self-update: fast on-launch check, atomic self-replace of the managed binary, install-script fallback message, `PODCLI_NO_UPDATE` + `config set update.auto off`, `podcli update`, keep-previous-binary for `podcli rollback`.+- **Ship.** Install script → `podcli process` works hermetic on all 4 platforms and auto-updates. ← *this is the MVP gate.*### Phase 3 — Lazy tiers + studio- Demote OpenCV face-crop to lazy (center-crop default offline; fetch opencv on first smart crop — the center-crop fallback already exists at `cli.py:621`).diff --git a/remotion/bundle-cache.mjs b/remotion/bundle-cache.mjsindex d908f37..017c7a3 100644--- a/remotion/bundle-cache.mjs+++ b/remotion/bundle-cache.mjs@@ -2,9 +2,12 @@ import { bundle } from "@remotion/bundler";import path from "path";import fs from "fs";import crypto from "crypto";+import { createRequire } from "module";import { fileURLToPath } from "url";import { webpackOverride } from "./webpack-override.mjs";+const require = createRequire(import.meta.url);+const __dirname = path.dirname(fileURLToPath(import.meta.url));const PROJECT_ROOT = path.resolve(__dirname, "..");const CACHE_ROOT = process.env.PODCLI_CACHE_DIR@@ -13,12 +16,16 @@ const CACHE_ROOT = process.env.PODCLI_CACHE_DIRexport const CACHE_DIR = path.join(CACHE_ROOT, "remotion-bundle");const HASH_FILE = path.join(CACHE_DIR, ".hash");+const LOCK_DIR = `${CACHE_DIR}.lock`;+const LOCK_STALE_MS = 5 * 60 * 1000;+const LOCK_HEARTBEAT_MS = Math.floor(LOCK_STALE_MS / 3);const ENTRY_POINT = path.join(__dirname, "src", "index.ts");/**- * A bundle is a product of the compositions and the webpack config, so both- * feed the cache key. Keying on either alone silently serves a bundle built- * from inputs that no longer exist.+ * A bundle is a product of the compositions, the webpack config, and the+ * remotion/bundler versions that produced it, so all of them feed the cache+ * key. Keying on a subset silently serves a bundle built from inputs that no+ * longer exist.*/function currentHash() {const hash = crypto.createHash("md5");@@ -33,22 +40,127 @@ function currentHash() {walk(path.join(__dirname, "src"));hash.update(fs.readFileSync(path.join(__dirname, "webpack-override.mjs")));+ hash.update(`remotion@${require("remotion/package.json").version}`);+ hash.update(`@remotion/bundler@${require("@remotion/bundler/package.json").version}`);return hash.digest("hex");}+function cacheIsValid(want) {+ try {+ return (+ fs.existsSync(path.join(CACHE_DIR, "index.html")) &&+ fs.readFileSync(HASH_FILE, "utf-8").trim() === want+ );+ } catch {+ return false;+ }+}++const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++function removeStaleLock() {+ try {+ const entries = fs.readdirSync(LOCK_DIR, { withFileTypes: true });+ if (entries.length === 0) {+ if (Date.now() - fs.statSync(LOCK_DIR).mtimeMs > LOCK_STALE_MS) {+ fs.rmdirSync(LOCK_DIR);+ return true;+ }+ return false;+ }++ for (const entry of entries) {+ if (!entry.isFile()) continue;+ const tokenPath = path.join(LOCK_DIR, entry.name);+ if (Date.now() - fs.statSync(tokenPath).mtimeMs > LOCK_STALE_MS) {+ fs.rmSync(tokenPath, { force: true });+ }+ }+ fs.rmdirSync(LOCK_DIR);+ return true;+ } catch {+ return false;+ }+}++async function acquireLock() {+ const token = `${process.pid}-${crypto.randomUUID()}`;+ for (;;) {+ try {+ fs.mkdirSync(LOCK_DIR);+ const tokenPath = path.join(LOCK_DIR, token);+ try {+ fs.writeFileSync(tokenPath, token, { flag: "wx" });+ } catch (err) {+ try {+ fs.rmdirSync(LOCK_DIR);+ } catch {}+ throw err;+ }+ const lock = { token, tokenPath, heartbeat: undefined };+ lock.heartbeat = setInterval(() => {+ try {+ const now = new Date();+ fs.utimesSync(tokenPath, now, now);+ } catch {+ clearInterval(lock.heartbeat);+ }+ }, LOCK_HEARTBEAT_MS);+ lock.heartbeat.unref();+ return lock;+ } catch (err) {+ if (err.code !== "EEXIST") throw err;+ }+ if (removeStaleLock()) continue;+ await sleep(500);+ }+}++function releaseLock(lock) {+ clearInterval(lock.heartbeat);+ try {+ fs.rmSync(lock.tokenPath, { force: true });+ } catch {}+ try {+ fs.rmdirSync(LOCK_DIR);+ } catch {}+}++function ownsLock(lock) {+ return fs.existsSync(lock.tokenPath);+}+export async function getCachedBundle({ onBundle } = {}) {const want = currentHash();- if (fs.existsSync(HASH_FILE) && fs.existsSync(path.join(CACHE_DIR, "index.html"))) {- if (fs.readFileSync(HASH_FILE, "utf-8").trim() === want) return CACHE_DIR;- }+ if (cacheIsValid(want)) return CACHE_DIR;++ fs.mkdirSync(CACHE_ROOT, { recursive: true });+ const lock = await acquireLock();+ try {+ if (cacheIsValid(want)) return CACHE_DIR;- onBundle?.();- fs.mkdirSync(CACHE_DIR, { recursive: true });- const location = await bundle({- entryPoint: ENTRY_POINT,- outDir: CACHE_DIR,- webpackOverride,- });- fs.writeFileSync(HASH_FILE, want);- return location;+ onBundle?.();+ // Bundle into a scratch dir and swap it in whole, so a crash mid-bundle+ // never leaves CACHE_DIR half-written.+ const staging = `${CACHE_DIR}.tmp-${lock.token}`;+ fs.rmSync(staging, { recursive: true, force: true });+ try {+ await bundle({+ entryPoint: ENTRY_POINT,+ outDir: staging,+ webpackOverride,+ });+ if (!ownsLock(lock)) {+ throw new Error("Bundle cache lock ownership lost");+ }+ fs.writeFileSync(path.join(staging, ".hash"), want);+ fs.rmSync(CACHE_DIR, { recursive: true, force: true });+ fs.renameSync(staging, CACHE_DIR);+ } finally {+ fs.rmSync(staging, { recursive: true, force: true });+ }+ return CACHE_DIR;+ } finally {+ releaseLock(lock);+ }}diff --git a/remotion/bundle-cache.test.mjs b/remotion/bundle-cache.test.mjsnew file mode 100644index 0000000..a81ef2e--- /dev/null+++ b/remotion/bundle-cache.test.mjs@@ -0,0 +1,70 @@+import fs from "fs";+import os from "os";+import path from "path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { bundle } from "@remotion/bundler";++vi.mock("@remotion/bundler", () => ({ bundle: vi.fn() }));++const savedCacheDir = process.env.PODCLI_CACHE_DIR;+const temporaryDirectories = [];++function deferred() {+ let resolve;+ const promise = new Promise((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}++afterEach(() => {+ vi.mocked(bundle).mockReset();+ vi.resetModules();+ if (savedCacheDir === undefined) delete process.env.PODCLI_CACHE_DIR;+ else process.env.PODCLI_CACHE_DIR = savedCacheDir;+ for (const directory of temporaryDirectories.splice(0)) {+ fs.rmSync(directory, { recursive: true, force: true });+ }+});++describe("bundle cache lock", () => {+ it("does not let a displaced owner release its successor's lock", async () => {+ const cacheRoot = fs.mkdtempSync(path.join(os.tmpdir(), "podcli-bundle-cache-"));+ temporaryDirectories.push(cacheRoot);+ process.env.PODCLI_CACHE_DIR = cacheRoot;++ const pendingBundles = [];+ vi.mocked(bundle).mockImplementation(async ({ outDir }) => {+ const completion = deferred();+ pendingBundles.push(completion);+ await completion.promise;+ fs.mkdirSync(outDir, { recursive: true });+ fs.writeFileSync(path.join(outDir, "index.html"), "");+ return outDir;+ });++ const { CACHE_DIR, getCachedBundle } = await import("./bundle-cache.mjs");+ const lockDir = `${CACHE_DIR}.lock`;+ const first = getCachedBundle();+ await vi.waitFor(() => expect(pendingBundles).toHaveLength(1));++ const staleTime = new Date(Date.now() - 10 * 60 * 1000);+ for (const entry of fs.readdirSync(lockDir)) {+ fs.utimesSync(path.join(lockDir, entry), staleTime, staleTime);+ }+ fs.utimesSync(lockDir, staleTime, staleTime);++ const second = getCachedBundle();+ await vi.waitFor(() => expect(pendingBundles).toHaveLength(2));+ const replacementTokens = fs.readdirSync(lockDir);+ expect(replacementTokens).toHaveLength(1);++ pendingBundles[0].resolve();+ await expect(first).rejects.toThrow("Bundle cache lock ownership lost");+ expect(fs.readdirSync(lockDir)).toEqual(replacementTokens);++ pendingBundles[1].resolve();+ await second;+ expect(fs.existsSync(lockDir)).toBe(false);+ });+});diff --git a/remotion/package-lock.json b/remotion/package-lock.jsonnew file mode 100644index 0000000..3d660be--- /dev/null+++ b/remotion/package-lock.json@@ -0,0 +1,2676 @@+{+ "name": "podcli-remotion-bundle",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "podcli-remotion-bundle",+ "dependencies": {+ "@fontsource/dm-sans": "5.2.8",+ "@remotion/bundler": "4.0.488",+ "@remotion/renderer": "4.0.488",+ "react": "19.2.7",+ "react-dom": "19.2.7",+ "remotion": "4.0.488"+ }+ },+ "node_modules/@emnapi/core": {+ "version": "1.11.2",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz",+ "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.2",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.2",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz",+ "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/wasi-threads": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",+ "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@fontsource/dm-sans": {+ "version": "5.2.8",+ "resolved": "https://registry.npmjs.org/@fontsource/dm-sans/-/dm-sans-5.2.8.tgz",+ "integrity": "sha512-tlovG42m9ESG28WiHpLq3F5umAlm64rv0RkqTbYowRn70e9OlRr5a3yTJhrhrY+k5lftR/OFJjPzOLQzk8EfCA==",+ "license": "OFL-1.1",+ "funding": {+ "url": "https://github.com/sponsors/ayuhito"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/source-map": {+ "version": "0.3.11",+ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",+ "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.25"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@mediabunny/aac-encoder": {+ "version": "1.50.8",+ "resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.50.8.tgz",+ "integrity": "sha512-A5Se/LZd6RmYq/h36lBMSEsHvsyW8d0toR7FrAwpsFYbK+DVQYf90KiBT1Aw/mzLXx8/ypIOORJnd1sVZqOvJQ==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },+ "node_modules/@mediabunny/flac-encoder": {+ "version": "1.50.8",+ "resolved": "https://registry.npmjs.org/@mediabunny/flac-encoder/-/flac-encoder-1.50.8.tgz",+ "integrity": "sha512-4cfN03SbEoQaG+eBeYFUAb1R1ALaAHzf43dXFzQTr/oO5ueqzTgBoG3coKrIvBaAMU7Vv36mrBKLX8bvTppdAQ==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },+ "node_modules/@mediabunny/mp3-encoder": {+ "version": "1.50.8",+ "resolved": "https://registry.npmjs.org/@mediabunny/mp3-encoder/-/mp3-encoder-1.50.8.tgz",+ "integrity": "sha512-eBT/H30tTu8AmZXqZ5RTpJ9VmwVlwednajuOrrWp0GS6cbGXsGMQ60Qvr3ZMIE0QDiadlEzb8/ozR+doP+MC1g==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },+ "node_modules/@module-federation/error-codes": {+ "version": "0.22.0",+ "resolved": "https://registry.npmjs.org/@module-federation/error-codes/-/error-codes-0.22.0.tgz",+ "integrity": "sha512-xF9SjnEy7vTdx+xekjPCV5cIHOGCkdn3pIxo9vU7gEZMIw0SvAEdsy6Uh17xaCpm8V0FWvR0SZoK9Ik6jGOaug==",+ "license": "MIT"+ },+ "node_modules/@module-federation/runtime": {+ "version": "0.22.0",+ "resolved": "https://registry.npmjs.org/@module-federation/runtime/-/runtime-0.22.0.tgz",+ "integrity": "sha512-38g5iPju2tPC3KHMPxRKmy4k4onNp6ypFPS1eKGsNLUkXgHsPMBFqAjDw96iEcjri91BrahG4XcdyKi97xZzlA==",+ "license": "MIT",+ "dependencies": {+ "@module-federation/error-codes": "0.22.0",+ "@module-federation/runtime-core": "0.22.0",+ "@module-federation/sdk": "0.22.0"+ }+ },+ "node_modules/@module-federation/runtime-core": {+ "version": "0.22.0",+ "resolved": "https://registry.npmjs.org/@module-federation/runtime-core/-/runtime-core-0.22.0.tgz",+ "integrity": "sha512-GR1TcD6/s7zqItfhC87zAp30PqzvceoeDGYTgF3Vx2TXvsfDrhP6Qw9T4vudDQL3uJRne6t7CzdT29YyVxlgIA==",+ "license": "MIT",+ "dependencies": {+ "@module-federation/error-codes": "0.22.0",+ "@module-federation/sdk": "0.22.0"+ }+ },+ "node_modules/@module-federation/runtime-tools": {+ "version": "0.22.0",+ "resolved": "https://registry.npmjs.org/@module-federation/runtime-tools/-/runtime-tools-0.22.0.tgz",+ "integrity": "sha512-4ScUJ/aUfEernb+4PbLdhM/c60VHl698Gn1gY21m9vyC1Ucn69fPCA1y2EwcCB7IItseRMoNhdcWQnzt/OPCNA==",+ "license": "MIT",+ "dependencies": {+ "@module-federation/runtime": "0.22.0",+ "@module-federation/webpack-bundler-runtime": "0.22.0"+ }+ },+ "node_modules/@module-federation/sdk": {+ "version": "0.22.0",+ "resolved": "https://registry.npmjs.org/@module-federation/sdk/-/sdk-0.22.0.tgz",+ "integrity": "sha512-x4aFNBKn2KVQRuNVC5A7SnrSCSqyfIWmm1DvubjbO9iKFe7ith5niw8dqSFBekYBg2Fwy+eMg4sEFNVvCAdo6g==",+ "license": "MIT"+ },+ "node_modules/@module-federation/webpack-bundler-runtime": {+ "version": "0.22.0",+ "resolved": "https://registry.npmjs.org/@module-federation/webpack-bundler-runtime/-/webpack-bundler-runtime-0.22.0.tgz",+ "integrity": "sha512-aM8gCqXu+/4wBmJtVeMeeMN5guw3chf+2i6HajKtQv7SJfxV/f4IyNQJUeUQu9HfiAZHjqtMV5Lvq/Lvh8LdyA==",+ "license": "MIT",+ "dependencies": {+ "@module-federation/runtime": "0.22.0",+ "@module-federation/sdk": "0.22.0"+ }+ },+ "node_modules/@napi-rs/wasm-runtime": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.0.7.tgz",+ "integrity": "sha512-SeDnOO0Tk7Okiq6DbXmmBODgOAb9dp9gjlphokTUxmt8U3liIP1ZsozBahH69j/RJv+Rfs6IwUKHTgQYJ/HBAw==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.5.0",+ "@emnapi/runtime": "^1.5.0",+ "@tybys/wasm-util": "^0.10.1"+ }+ },+ "node_modules/@remotion/bundler": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/bundler/-/bundler-4.0.488.tgz",+ "integrity": "sha512-HBBH+IRRSuGjgc23e4uujOJffKvPcMhDiMrl9X3TJJXCO/qc9CqUQzW4yH4m04yecUBEZjogmrXLBoSVNYhZcw==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@remotion/media-parser": "4.0.488",+ "@remotion/studio": "4.0.488",+ "@remotion/studio-shared": "4.0.488",+ "@remotion/timeline-utils": "4.0.488",+ "@rspack/core": "1.7.11",+ "@rspack/plugin-react-refresh": "1.6.1",+ "css-loader": "7.1.4",+ "esbuild": "0.28.1",+ "react-refresh": "0.18.0",+ "remotion": "4.0.488",+ "style-loader": "4.0.0",+ "webpack": "5.105.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/canvas-capture": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/canvas-capture/-/canvas-capture-4.0.488.tgz",+ "integrity": "sha512-K5unf3W3yRlzoERZ1Kd+3k6NZJZdKupSEb1O0oPf5VEkct9PI5DpuK1b/AGPULwSop14GHb7GoYlRFse9rAiDA==",+ "license": "Remotion License",+ "dependencies": {+ "mediabunny": "1.50.8",+ "remotion": "4.0.488"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/compositor-darwin-arm64": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-arm64/-/compositor-darwin-arm64-4.0.488.tgz",+ "integrity": "sha512-FP4FY4zPEMQ/EQYBfs20TYfs2kyHlwpypaR+BRk2zYV29r3klNi+vzrlxk0P480g3QiX0sxKZ8AFDeBZdbP6UA==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@remotion/compositor-darwin-x64": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-x64/-/compositor-darwin-x64-4.0.488.tgz",+ "integrity": "sha512-5GBn7Oqx2eAMJfXikrRAGcdjtJwT2/zHpguLuoNzbepuc7AAb1Sj7iqzj+kMLQU7Dc4/iiVdvN7SOVc4adFbgA==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@remotion/compositor-linux-arm64-gnu": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-gnu/-/compositor-linux-arm64-gnu-4.0.488.tgz",+ "integrity": "sha512-kHfWTF3W/N6q1ZTCXiFhJGcDZB4GB2ZnglbK90k/b3os0IyJvz8n44qFNz0PS3HKCerG9vO8aYLTRNg41g56Og==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-linux-arm64-musl": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-musl/-/compositor-linux-arm64-musl-4.0.488.tgz",+ "integrity": "sha512-ySrF9LfJDjc+yqenfWMGvPVoINJe7grxlT0i9DjcPX6XS+yfDSQQSFnDfNB0jdHiuD8NJjjaJ0AGhOozKIQLlg==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-linux-x64-gnu": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-gnu/-/compositor-linux-x64-gnu-4.0.488.tgz",+ "integrity": "sha512-xXzFkWAjWVJNl9/lYuEgqVYJQd+yNaxM03gLaG2CYEK3yq03+PHwdDrs9W2gTHs1l8P1XkMuiOGXmtlAO6W9Zg==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-linux-x64-musl": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-musl/-/compositor-linux-x64-musl-4.0.488.tgz",+ "integrity": "sha512-bu2JPr0UTufzYpMzt8jBmC93RxKI9iqOVSzISW7bUDDZzuUMdcUJNDeauWuI9b6B17bn3j3VoDbOrZ/kKeb4/w==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-win32-x64-msvc": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-win32-x64-msvc/-/compositor-win32-x64-msvc-4.0.488.tgz",+ "integrity": "sha512-iljgUki6NBoTIfxRyOEhMhyVBbo0Yot2sb6El8qeUBDrNc3Ctl3ixBT2lZZJmdq3gaY46gKH9lYENvE2kGQALA==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@remotion/licensing": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.488.tgz",+ "integrity": "sha512-5jVmxoOzpeZMnLX7qLQUteOA0vbj+uPYHH8G3nuD87xnPPWDGMy/t8bA8GuImfLn55aM6jaNLP4ngi3IorlvgA==",+ "license": "MIT"+ },+ "node_modules/@remotion/media-parser": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/media-parser/-/media-parser-4.0.488.tgz",+ "integrity": "sha512-g4Q2S/Iso87h/ZMWniv3QyZEV45iVg6wwlPSd2ukXAVCh3Gz5e333/y4exNT/MZ2l45WPaNN9CA4EV3qsLu8bw==",+ "license": "Remotion License https://remotion.dev/license"+ },+ "node_modules/@remotion/media-utils": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.488.tgz",+ "integrity": "sha512-Q5Q02PtGmGLIb2pjUiAQt/2dZDHezpjF57hNmV/XMzM7RBw+RiaPJMMRtuJ5hSgOWSJouGMUvtNnlKO/H0L6CA==",+ "license": "MIT",+ "dependencies": {+ "mediabunny": "1.50.8",+ "remotion": "4.0.488"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/player": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.488.tgz",+ "integrity": "sha512-bP9y6PFHtP79ikR2zxFiMwR11Cc5BoN9+PEP1YEdMXhkf4o+zDj6PzNw/Va2SjWhozrOTgVshgs1QZfQYleEkg==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "remotion": "4.0.488"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/renderer": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/renderer/-/renderer-4.0.488.tgz",+ "integrity": "sha512-gChcGkdrp4/0hmJDUU75bmvOk6RSO+xbzpQM82DvGbBEKHd/PmfEObsPXW9biMvJ2PG9IUAbfNhCBLJZMOTL6A==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@remotion/licensing": "4.0.488",+ "@remotion/streaming": "4.0.488",+ "execa": "5.1.1",+ "remotion": "4.0.488",+ "source-map": "0.8.0-beta.0",+ "ws": "8.21.0"+ },+ "optionalDependencies": {+ "@remotion/compositor-darwin-arm64": "4.0.488",+ "@remotion/compositor-darwin-x64": "4.0.488",+ "@remotion/compositor-linux-arm64-gnu": "4.0.488",+ "@remotion/compositor-linux-arm64-musl": "4.0.488",+ "@remotion/compositor-linux-x64-gnu": "4.0.488",+ "@remotion/compositor-linux-x64-musl": "4.0.488",+ "@remotion/compositor-win32-x64-msvc": "4.0.488"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/streaming": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/streaming/-/streaming-4.0.488.tgz",+ "integrity": "sha512-/l+drcbhtg6ot4y6ApPolkBjsO0cZx20KtFBnCrzxufnNHRKOp7RzeOHxLXNVLMP/Bz2cf31sQYXbalXk16sjQ==",+ "license": "MIT"+ },+ "node_modules/@remotion/studio": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/studio/-/studio-4.0.488.tgz",+ "integrity": "sha512-LVuW1usvzqz3GRVf0jL9jYT0XzYglS/TGuyW5ee5o3hmz47ksiwCUYYt6zv9x0DzlyZtK6dzfYzbvPVwSIQkiQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "0.3.31",+ "@remotion/canvas-capture": "4.0.488",+ "@remotion/media-utils": "4.0.488",+ "@remotion/player": "4.0.488",+ "@remotion/renderer": "4.0.488",+ "@remotion/studio-shared": "4.0.488",+ "@remotion/timeline-utils": "4.0.488",+ "@remotion/web-renderer": "4.0.488",+ "@remotion/zod-types": "4.0.488",+ "mediabunny": "1.50.8",+ "memfs": "3.4.3",+ "open": "8.4.2",+ "remotion": "4.0.488",+ "semver": "7.5.3",+ "zod": "4.3.6"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/studio-shared": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/studio-shared/-/studio-shared-4.0.488.tgz",+ "integrity": "sha512-QPLJEteenroRRPJ3z9gxffycGJanYNC/XvGJbpSlcELYMyZBkE/+LYq6bNV2Xso5FoGO50GUd9lt/fCKJR3F0A==",+ "license": "MIT",+ "dependencies": {+ "remotion": "4.0.488"+ }+ },+ "node_modules/@remotion/timeline-utils": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/timeline-utils/-/timeline-utils-4.0.488.tgz",+ "integrity": "sha512-TwC4bPkJHm9hwtzI2pVjERKCmcsw82FoGSecc7c7Bwo9az+1l0KenTg1HznMVhqJRtMTTyDSZvkiD7Lat1TFdg==",+ "license": "MIT",+ "dependencies": {+ "mediabunny": "1.50.8"+ }+ },+ "node_modules/@remotion/web-renderer": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/web-renderer/-/web-renderer-4.0.488.tgz",+ "integrity": "sha512-9hzmwPGRUvlXs0pjdlI4kIS3nogVOa6Wheoob+S7PxaFLK2wobxbNtTAKNidoLJXfv/chCo65v1ThPJFsyb5qw==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@mediabunny/aac-encoder": "1.50.8",+ "@mediabunny/flac-encoder": "1.50.8",+ "@mediabunny/mp3-encoder": "1.50.8",+ "@remotion/licensing": "4.0.488",+ "mediabunny": "1.50.8",+ "remotion": "4.0.488"+ },+ "peerDependencies": {+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"+ }+ },+ "node_modules/@remotion/zod-types": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/@remotion/zod-types/-/zod-types-4.0.488.tgz",+ "integrity": "sha512-2XdHInhWUX5DhaMNxVaOsv/T6po4siPOJ8EcU0AA8nBbwIgTpFSE/R6XwMRQGwEtCknY3EOJBORhVfWh0tXOCQ==",+ "license": "MIT",+ "dependencies": {+ "remotion": "4.0.488"+ }+ },+ "node_modules/@rspack/binding": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-1.7.11.tgz",+ "integrity": "sha512-2MGdy2s2HimsDT444Bp5XnALzNRxuBNc7y0JzyuqKbHBywd4x2NeXyhWXXoxufaCFu5PBc9Qq9jyfjW2Aeh06Q==",+ "license": "MIT",+ "optionalDependencies": {+ "@rspack/binding-darwin-arm64": "1.7.11",+ "@rspack/binding-darwin-x64": "1.7.11",+ "@rspack/binding-linux-arm64-gnu": "1.7.11",+ "@rspack/binding-linux-arm64-musl": "1.7.11",+ "@rspack/binding-linux-x64-gnu": "1.7.11",+ "@rspack/binding-linux-x64-musl": "1.7.11",+ "@rspack/binding-wasm32-wasi": "1.7.11",+ "@rspack/binding-win32-arm64-msvc": "1.7.11",+ "@rspack/binding-win32-ia32-msvc": "1.7.11",+ "@rspack/binding-win32-x64-msvc": "1.7.11"+ }+ },+ "node_modules/@rspack/binding-darwin-arm64": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-1.7.11.tgz",+ "integrity": "sha512-oduECiZVqbO5zlVw+q7Vy65sJFth99fWPTyucwvLJJtJkPL5n17Uiql2cYP6Ijn0pkqtf1SXgK8WjiKLG5bIig==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rspack/binding-darwin-x64": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-1.7.11.tgz",+ "integrity": "sha512-a1+TtTE9ap6RalgFi7FGIgkJP6O4Vy6ctv+9WGJy53E4kuqHR0RygzaiVxCI/GMc/vBT9vY23hyrpWb3d1vtXA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rspack/binding-linux-arm64-gnu": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.7.11.tgz",+ "integrity": "sha512-P0QrGRPbTWu6RKWfN0bDtbnEps3rXH0MWIMreZABoUrVmNQKtXR6e73J3ub6a+di5s2+K0M2LJ9Bh2/H4UsDUA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-arm64-musl": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.7.11.tgz",+ "integrity": "sha512-6ky7R43VMjWwmx3Yx7Jl7faLBBMAgMDt+/bN35RgwjiPgsIByz65EwytUVuW9rikB43BGHvA/eqlnjLrUzNBqw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-x64-gnu": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.7.11.tgz",+ "integrity": "sha512-cuOJMfCOvb2Wgsry5enXJ3iT1FGUjdPqtGUBVupQlEG4ntSYsQ2PtF4wIDVasR3wdxC5nQbipOrDiN/u6fYsdQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-x64-musl": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-1.7.11.tgz",+ "integrity": "sha512-CoK37hva4AmHGh3VCsQXmGr40L36m1/AdnN5LEjUX6kx5rEH7/1nEBN6Ii72pejqDVvk9anEROmPDiPw10tpFg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-wasm32-wasi": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-1.7.11.tgz",+ "integrity": "sha512-OtrmnPUVJMxjNa3eDMfHyPdtlLRmmp/aIm0fQHlAOATbZvlGm12q7rhPW5BXTu1yh+1rQ1/uqvz+SzKEZXuJaQ==",+ "cpu": [+ "wasm32"+ ],+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@napi-rs/wasm-runtime": "1.0.7"+ }+ },+ "node_modules/@rspack/binding-win32-arm64-msvc": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.7.11.tgz",+ "integrity": "sha512-lObFW6e5lCWNgTBNwT//yiEDbsxm9QG4BYUojqeXxothuzJ/L6ibXz6+gLMvbOvLGV3nKgkXmx8GvT9WDKR0mA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rspack/binding-win32-ia32-msvc": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.7.11.tgz",+ "integrity": "sha512-0pYGnZd8PPqNR68zQ8skamqNAXEA1sUfXuAdYcknIIRq2wsbiwFzIc0Pov1cIfHYab37G7sSIPBiOUdOWF5Ivw==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rspack/binding-win32-x64-msvc": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.7.11.tgz",+ "integrity": "sha512-EeQXayoQk/uBkI3pdoXfQBXNIUrADq56L3s/DFyM2pJeUDrWmhfIw2UFIGkYPTMSCo8F2JcdcGM32FGJrSnU0Q==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rspack/core": {+ "version": "1.7.11",+ "resolved": "https://registry.npmjs.org/@rspack/core/-/core-1.7.11.tgz",+ "integrity": "sha512-rsD9b+Khmot5DwCMiB3cqTQo53ioPG3M/A7BySu8+0+RS7GCxKm+Z+mtsjtG/vsu4Tn2tcqCdZtA3pgLoJB+ew==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@module-federation/runtime-tools": "0.22.0",+ "@rspack/binding": "1.7.11",+ "@rspack/lite-tapable": "1.1.0"+ },+ "engines": {+ "node": ">=18.12.0"+ },+ "peerDependencies": {+ "@swc/helpers": ">=0.5.1"+ },+ "peerDependenciesMeta": {+ "@swc/helpers": {+ "optional": true+ }+ }+ },+ "node_modules/@rspack/lite-tapable": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@rspack/lite-tapable/-/lite-tapable-1.1.0.tgz",+ "integrity": "sha512-E2B0JhYFmVAwdDiG14+DW0Di4Ze4Jg10Pc4/lILUrd5DRCaklduz2OvJ5HYQ6G+hd+WTzqQb3QnDNfK4yvAFYw==",+ "license": "MIT"+ },+ "node_modules/@rspack/plugin-react-refresh": {+ "version": "1.6.1",+ "resolved": "https://registry.npmjs.org/@rspack/plugin-react-refresh/-/plugin-react-refresh-1.6.1.tgz",+ "integrity": "sha512-eqqW5645VG3CzGzFgNg5HqNdHVXY+567PGjtDhhrM8t67caxmsSzRmT5qfoEIfBcGgFkH9vEg7kzXwmCYQdQDw==",+ "license": "MIT",+ "dependencies": {+ "error-stack-parser": "^2.1.4",+ "html-entities": "^2.6.0"+ },+ "peerDependencies": {+ "react-refresh": ">=0.10.0 <1.0.0",+ "webpack-hot-middleware": "2.x"+ },+ "peerDependenciesMeta": {+ "webpack-hot-middleware": {+ "optional": true+ }+ }+ },+ "node_modules/@tybys/wasm-util": {+ "version": "0.10.3",+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",+ "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@types/dom-mediacapture-transform": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",+ "license": "MIT",+ "dependencies": {+ "@types/dom-webcodecs": "*"+ }+ },+ "node_modules/@types/dom-webcodecs": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",+ "license": "MIT"+ },+ "node_modules/@types/eslint": {+ "version": "9.6.1",+ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz",+ "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "*",+ "@types/json-schema": "*"+ }+ },+ "node_modules/@types/eslint-scope": {+ "version": "3.7.7",+ "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz",+ "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==",+ "license": "MIT",+ "dependencies": {+ "@types/eslint": "*",+ "@types/estree": "*"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "license": "MIT"+ },+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "26.1.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",+ "integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~8.3.0"+ }+ },+ "node_modules/@webassemblyjs/ast": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz",+ "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/helper-numbers": "1.13.2",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2"+ }+ },+ "node_modules/@webassemblyjs/floating-point-hex-parser": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz",+ "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-api-error": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz",+ "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-buffer": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz",+ "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-numbers": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz",+ "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/floating-point-hex-parser": "1.13.2",+ "@webassemblyjs/helper-api-error": "1.13.2",+ "@xtuc/long": "4.2.2"+ }+ },+ "node_modules/@webassemblyjs/helper-wasm-bytecode": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz",+ "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-wasm-section": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz",+ "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-buffer": "1.14.1",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/wasm-gen": "1.14.1"+ }+ },+ "node_modules/@webassemblyjs/ieee754": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz",+ "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==",+ "license": "MIT",+ "dependencies": {+ "@xtuc/ieee754": "^1.2.0"+ }+ },+ "node_modules/@webassemblyjs/leb128": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz",+ "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@xtuc/long": "4.2.2"+ }+ },+ "node_modules/@webassemblyjs/utf8": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz",+ "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/wasm-edit": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz",+ "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-buffer": "1.14.1",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/helper-wasm-section": "1.14.1",+ "@webassemblyjs/wasm-gen": "1.14.1",+ "@webassemblyjs/wasm-opt": "1.14.1",+ "@webassemblyjs/wasm-parser": "1.14.1",+ "@webassemblyjs/wast-printer": "1.14.1"+ }+ },+ "node_modules/@webassemblyjs/wasm-gen": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz",+ "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/ieee754": "1.13.2",+ "@webassemblyjs/leb128": "1.13.2",+ "@webassemblyjs/utf8": "1.13.2"+ }+ },+ "node_modules/@webassemblyjs/wasm-opt": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz",+ "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-buffer": "1.14.1",+ "@webassemblyjs/wasm-gen": "1.14.1",+ "@webassemblyjs/wasm-parser": "1.14.1"+ }+ },+ "node_modules/@webassemblyjs/wasm-parser": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz",+ "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-api-error": "1.13.2",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/ieee754": "1.13.2",+ "@webassemblyjs/leb128": "1.13.2",+ "@webassemblyjs/utf8": "1.13.2"+ }+ },+ "node_modules/@webassemblyjs/wast-printer": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz",+ "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@xtuc/long": "4.2.2"+ }+ },+ "node_modules/@xtuc/ieee754": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",+ "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@xtuc/long": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",+ "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==",+ "license": "Apache-2.0"+ },+ "node_modules/acorn": {+ "version": "8.17.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",+ "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",+ "license": "MIT",+ "peer": true,+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-import-phases": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz",+ "integrity": "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10.13.0"+ },+ "peerDependencies": {+ "acorn": "^8.14.0"+ }+ },+ "node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",+ "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/ajv-keywords": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz",+ "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3"+ },+ "peerDependencies": {+ "ajv": "^8.8.2"+ }+ },+ "node_modules/baseline-browser-mapping": {+ "version": "2.10.43",+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.43.tgz",+ "integrity": "sha512-AjYpR78kDWAY3Efj+cDTFH9t9SCoL7OoTp1BOb0mQV7S+6CiLwnWM3FyxhJtdPufDFKzmCSFoUncKjWgJEZTCQ==",+ "license": "Apache-2.0",+ "bin": {+ "baseline-browser-mapping": "dist/cli.cjs"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/browserslist": {+ "version": "4.28.6",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.6.tgz",+ "integrity": "sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "baseline-browser-mapping": "^2.10.42",+ "caniuse-lite": "^1.0.30001803",+ "electron-to-chromium": "^1.5.389",+ "node-releases": "^2.0.51",+ "update-browserslist-db": "^1.2.3"+ },+ "bin": {+ "browserslist": "cli.js"+ },+ "engines": {+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"+ }+ },+ "node_modules/buffer-from": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",+ "license": "MIT"+ },+ "node_modules/caniuse-lite": {+ "version": "1.0.30001805",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001805.tgz",+ "integrity": "sha512-52noaS3DubycKSXaU30TwPGIp+POyQSUVa5jBEq3vkRkY0kjyb3LQgvhU6WGyCcyXqVLWO0Cw0Q6BSdD0kUfVA==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "CC-BY-4.0"+ },+ "node_modules/chrome-trace-event": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz",+ "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6.0"+ }+ },+ "node_modules/commander": {+ "version": "2.20.3",+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",+ "license": "MIT"+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/css-loader": {+ "version": "7.1.4",+ "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-7.1.4.tgz",+ "integrity": "sha512-vv3J9tlOl04WjiMvHQI/9tmIrCxVrj6PFbHemBB1iihpeRbi/I4h033eoFIhwxBBqLhI0KYFS7yvynBFhIZfTw==",+ "license": "MIT",+ "dependencies": {+ "icss-utils": "^5.1.0",+ "postcss": "^8.4.40",+ "postcss-modules-extract-imports": "^3.1.0",+ "postcss-modules-local-by-default": "^4.0.5",+ "postcss-modules-scope": "^3.2.0",+ "postcss-modules-values": "^4.0.0",+ "postcss-value-parser": "^4.2.0",+ "semver": "^7.6.3"+ },+ "engines": {+ "node": ">= 18.12.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0",+ "webpack": "^5.27.0"+ },+ "peerDependenciesMeta": {+ "@rspack/core": {+ "optional": true+ },+ "webpack": {+ "optional": true+ }+ }+ },+ "node_modules/css-loader/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/cssesc": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",+ "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",+ "license": "MIT",+ "bin": {+ "cssesc": "bin/cssesc"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/define-lazy-prop": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",+ "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/electron-to-chromium": {+ "version": "1.5.389",+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.389.tgz",+ "integrity": "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg==",+ "license": "ISC"+ },+ "node_modules/enhanced-resolve": {+ "version": "5.24.2",+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.2.tgz",+ "integrity": "sha512-rpsZEGT1jFuve6QlpyRp9ckQ+kN61hvF9BzCPyMdaKTm8UJce96KBn3sorXOFXlzjPrs3Vc4T1NsSroZ3PxlFw==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "tapable": "^2.3.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/error-stack-parser": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/error-stack-parser/-/error-stack-parser-2.1.4.tgz",+ "integrity": "sha512-Sk5V6wVazPhq5MhpO+AUxJn5x7XSXGl1R93Vn7i+zS15KDVxQijejNCrz8340/2bgLBjR9GtEG8ZVKONDjcqGQ==",+ "license": "MIT",+ "dependencies": {+ "stackframe": "^1.3.4"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.1.tgz",+ "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==",+ "license": "MIT"+ },+ "node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/eslint-scope": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",+ "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "esrecurse": "^4.3.0",+ "estraverse": "^4.1.1"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esrecurse/node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",+ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/events": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.x"+ }+ },+ "node_modules/execa": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.3",+ "get-stream": "^6.0.0",+ "human-signals": "^2.1.0",+ "is-stream": "^2.0.0",+ "merge-stream": "^2.0.0",+ "npm-run-path": "^4.0.1",+ "onetime": "^5.1.2",+ "signal-exit": "^3.0.3",+ "strip-final-newline": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/execa?sponsor=1"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz",+ "integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/fs-monkey": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.3.tgz",+ "integrity": "sha512-cybjIfiiE+pTWicSCLFHSrXZ6EilF30oh91FDP9S2B051prEa7QWfrVTQm10/dDpswBDXZugPa1Ogu8Yh+HV0Q==",+ "license": "Unlicense"+ },+ "node_modules/get-stream": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/glob-to-regexp": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",+ "license": "BSD-2-Clause"+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "license": "ISC"+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/html-entities": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz",+ "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/mdevils"+ },+ {+ "type": "patreon",+ "url": "https://patreon.com/mdevils"+ }+ ],+ "license": "MIT"+ },+ "node_modules/human-signals": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=10.17.0"+ }+ },+ "node_modules/icss-utils": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz",+ "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==",+ "license": "ISC",+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/is-docker": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",+ "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",+ "license": "MIT",+ "bin": {+ "is-docker": "cli.js"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-wsl": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",+ "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",+ "license": "MIT",+ "dependencies": {+ "is-docker": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jest-worker": {+ "version": "27.5.1",+ "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",+ "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "merge-stream": "^2.0.0",+ "supports-color": "^8.0.0"+ },+ "engines": {+ "node": ">= 10.13.0"+ }+ },+ "node_modules/json-parse-even-better-errors": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",+ "license": "MIT"+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/loader-runner": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.2.tgz",+ "integrity": "sha512-DFEqQ3ihfS9blba08cLfYf1NRAIEm+dDjic073DRDc3/JspI/8wYmtDsHwd3+4hwvdxSK7PGaElfTmm0awWJ4w==",+ "license": "MIT",+ "engines": {+ "node": ">=6.11.5"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/lodash.sortby": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz",+ "integrity": "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==",+ "license": "MIT"+ },+ "node_modules/lru-cache": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",+ "license": "ISC",+ "dependencies": {+ "yallist": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/mediabunny": {+ "version": "1.50.8",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.50.8.tgz",+ "integrity": "sha512-LgykLyQzhdpo0V2yw3UXmOpj+b4JAGdpHBwsPE6kjSt8Za0d1VllD+FV7EGHBcdV4+oHUAo+yrqbVAWxNSDCPQ==",+ "license": "MPL-2.0",+ "peer": true,+ "workspaces": [+ ".",+ "packages/*"+ ],+ "dependencies": {+ "@types/dom-mediacapture-transform": "^0.1.11",+ "@types/dom-webcodecs": "0.1.13"+ },+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ }+ },+ "node_modules/memfs": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/memfs/-/memfs-3.4.3.tgz",+ "integrity": "sha512-eivjfi7Ahr6eQTn44nvTnR60e4a1Fs1Via2kCR5lHo/kyNoiMWaXCNJ/GpSd0ilXas2JSOl9B5FTIhflXu0hlg==",+ "license": "Unlicense",+ "dependencies": {+ "fs-monkey": "1.0.3"+ },+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/merge-stream": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",+ "license": "MIT"+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mimic-fn": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.16",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",+ "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/neo-async": {+ "version": "2.6.2",+ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",+ "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",+ "license": "MIT"+ },+ "node_modules/node-releases": {+ "version": "2.0.51",+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz",+ "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/npm-run-path": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/onetime": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",+ "license": "MIT",+ "dependencies": {+ "mimic-fn": "^2.1.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/open": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz",+ "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==",+ "license": "MIT",+ "dependencies": {+ "define-lazy-prop": "^2.0.0",+ "is-docker": "^2.1.1",+ "is-wsl": "^2.2.0"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/postcss": {+ "version": "8.5.19",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",+ "integrity": "sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "nanoid": "^3.3.12",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/postcss-modules-extract-imports": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.1.0.tgz",+ "integrity": "sha512-k3kNe0aNFQDAZGbin48pL2VNidTF0w4/eASDsxlyspobzU3wZQLOGj7L9gfRe0Jo9/4uud09DsjFNH7winGv8Q==",+ "license": "ISC",+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-modules-local-by-default": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.2.0.tgz",+ "integrity": "sha512-5kcJm/zk+GJDSfw+V/42fJ5fhjL5YbFDl8nVdXkJPLLW+Vf9mTD5Xe0wqIaDnLuL2U6cDNpTr+UQ+v2HWIBhzw==",+ "license": "MIT",+ "dependencies": {+ "icss-utils": "^5.0.0",+ "postcss-selector-parser": "^7.0.0",+ "postcss-value-parser": "^4.1.0"+ },+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-modules-scope": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.2.1.tgz",+ "integrity": "sha512-m9jZstCVaqGjTAuny8MdgE88scJnCiQSlSrOWcTQgM2t32UBe+MUmFSO5t7VMSfAf/FJKImAxBav8ooCHJXCJA==",+ "license": "ISC",+ "dependencies": {+ "postcss-selector-parser": "^7.0.0"+ },+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-modules-values": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz",+ "integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==",+ "license": "ISC",+ "dependencies": {+ "icss-utils": "^5.0.0"+ },+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-selector-parser": {+ "version": "7.1.4",+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.4.tgz",+ "integrity": "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg==",+ "license": "MIT",+ "dependencies": {+ "cssesc": "^3.0.0",+ "util-deprecate": "^1.0.2"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/postcss-value-parser": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",+ "license": "MIT"+ },+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/react": {+ "version": "19.2.7",+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",+ "integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-dom": {+ "version": "19.2.7",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",+ "integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "scheduler": "^0.27.0"+ },+ "peerDependencies": {+ "react": "^19.2.7"+ }+ },+ "node_modules/react-refresh": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",+ "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/remotion": {+ "version": "4.0.488",+ "resolved": "https://registry.npmjs.org/remotion/-/remotion-4.0.488.tgz",+ "integrity": "sha512-V+2GQChZQkrBWrT2+bqpvu9Q/8mAri08vdZEdWsl5hy5j8/3z2DAr+Fw81K4RHmLKgKbZY21AJv7hUD+DKOdhA==",+ "license": "SEE LICENSE IN LICENSE.md",+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/scheduler": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",+ "license": "MIT"+ },+ "node_modules/schema-utils": {+ "version": "4.3.3",+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz",+ "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==",+ "license": "MIT",+ "dependencies": {+ "@types/json-schema": "^7.0.9",+ "ajv": "^8.9.0",+ "ajv-formats": "^2.1.1",+ "ajv-keywords": "^5.1.0"+ },+ "engines": {+ "node": ">= 10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/semver": {+ "version": "7.5.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz",+ "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==",+ "license": "ISC",+ "dependencies": {+ "lru-cache": "^6.0.0"+ },+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/signal-exit": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "license": "ISC"+ },+ "node_modules/source-map": {+ "version": "0.8.0-beta.0",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0-beta.0.tgz",+ "integrity": "sha512-2ymg6oRBpebeZi9UUNsgQ89bhx01TcTkmNTGnNO88imTmbSgy4nfujrgVEFKWpMTEGA11EDkTt7mqObTPdigIA==",+ "deprecated": "The work that was done in this beta branch won't be included in future versions",+ "license": "BSD-3-Clause",+ "dependencies": {+ "whatwg-url": "^7.0.0"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/source-map-support": {+ "version": "0.5.21",+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",+ "license": "MIT",+ "dependencies": {+ "buffer-from": "^1.0.0",+ "source-map": "^0.6.0"+ }+ },+ "node_modules/source-map-support/node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stackframe": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/stackframe/-/stackframe-1.3.4.tgz",+ "integrity": "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw==",+ "license": "MIT"+ },+ "node_modules/strip-final-newline": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/style-loader": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-4.0.0.tgz",+ "integrity": "sha512-1V4WqhhZZgjVAVJyt7TdDPZoPBPNHbekX4fWnCJL1yQukhCeZhJySUL+gL9y6sNdN95uEOS83Y55SqHcP7MzLA==",+ "license": "MIT",+ "engines": {+ "node": ">= 18.12.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "webpack": "^5.27.0"+ }+ },+ "node_modules/supports-color": {+ "version": "8.1.1",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"+ }+ },+ "node_modules/tapable": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz",+ "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/terser": {+ "version": "5.49.0",+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.49.0.tgz",+ "integrity": "sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "@jridgewell/source-map": "^0.3.3",+ "acorn": "^8.15.0",+ "commander": "^2.20.0",+ "source-map-support": "~0.5.20"+ },+ "bin": {+ "terser": "bin/terser"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/terser-webpack-plugin": {+ "version": "5.6.1",+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.6.1.tgz",+ "integrity": "sha512-201R5j+sJpK8nFWwKVyNfZot8FaJbLZDq5evriVzbV1wDtSXDjRUDRfJzHpAaxFDMEhsZL1QkeqM61wgsS3KaQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "^0.3.25",+ "jest-worker": "^27.4.5",+ "schema-utils": "^4.3.0",+ "terser": "^5.31.1"+ },+ "engines": {+ "node": ">= 10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "webpack": "^5.1.0"+ },+ "peerDependenciesMeta": {+ "@minify-html/node": {+ "optional": true+ },+ "@swc/core": {+ "optional": true+ },+ "@swc/css": {+ "optional": true+ },+ "@swc/html": {+ "optional": true+ },+ "clean-css": {+ "optional": true+ },+ "cssnano": {+ "optional": true+ },+ "csso": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "html-minifier-terser": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "postcss": {+ "optional": true+ },+ "uglify-js": {+ "optional": true+ }+ }+ },+ "node_modules/tr46": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz",+ "integrity": "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==",+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.1.0"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD",+ "optional": true+ },+ "node_modules/undici-types": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",+ "license": "MIT"+ },+ "node_modules/update-browserslist-db": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",+ "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "escalade": "^3.2.0",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "update-browserslist-db": "cli.js"+ },+ "peerDependencies": {+ "browserslist": ">= 4.21.0"+ }+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/watchpack": {+ "version": "2.5.2",+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz",+ "integrity": "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.1.2"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz",+ "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==",+ "license": "BSD-2-Clause"+ },+ "node_modules/webpack": {+ "version": "5.105.0",+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz",+ "integrity": "sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/eslint-scope": "^3.7.7",+ "@types/estree": "^1.0.8",+ "@types/json-schema": "^7.0.15",+ "@webassemblyjs/ast": "^1.14.1",+ "@webassemblyjs/wasm-edit": "^1.14.1",+ "@webassemblyjs/wasm-parser": "^1.14.1",+ "acorn": "^8.15.0",+ "acorn-import-phases": "^1.0.3",+ "browserslist": "^4.28.1",+ "chrome-trace-event": "^1.0.2",+ "enhanced-resolve": "^5.19.0",+ "es-module-lexer": "^2.0.0",+ "eslint-scope": "5.1.1",+ "events": "^3.2.0",+ "glob-to-regexp": "^0.4.1",+ "graceful-fs": "^4.2.11",+ "json-parse-even-better-errors": "^2.3.1",+ "loader-runner": "^4.3.1",+ "mime-types": "^2.1.27",+ "neo-async": "^2.6.2",+ "schema-utils": "^4.3.3",+ "tapable": "^2.3.0",+ "terser-webpack-plugin": "^5.3.16",+ "watchpack": "^2.5.1",+ "webpack-sources": "^3.3.3"+ },+ "bin": {+ "webpack": "bin/webpack.js"+ },+ "engines": {+ "node": ">=10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependenciesMeta": {+ "webpack-cli": {+ "optional": true+ }+ }+ },+ "node_modules/webpack-sources": {+ "version": "3.5.1",+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz",+ "integrity": "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==",+ "license": "MIT",+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/whatwg-url": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.1.0.tgz",+ "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==",+ "license": "MIT",+ "dependencies": {+ "lodash.sortby": "^4.7.0",+ "tr46": "^1.0.1",+ "webidl-conversions": "^4.0.2"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/yallist": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",+ "license": "ISC"+ },+ "node_modules/zod": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/remotion/package.json b/remotion/package.jsonnew file mode 100644index 0000000..c1aade3--- /dev/null+++ b/remotion/package.json@@ -0,0 +1,13 @@+{+ "name": "podcli-remotion-bundle",+ "private": true,+ "type": "module",+ "dependencies": {+ "@fontsource/dm-sans": "5.2.8",+ "@remotion/bundler": "4.0.488",+ "@remotion/renderer": "4.0.488",+ "react": "19.2.7",+ "react-dom": "19.2.7",+ "remotion": "4.0.488"+ }+}diff --git a/remotion/render.mjs b/remotion/render.mjsindex b93adbc..ecbc9c8 100644--- a/remotion/render.mjs+++ b/remotion/render.mjs@@ -100,10 +100,18 @@ async function main() {await new Promise((resolve) => assetServer.listen(0, "127.0.0.1", resolve));const assetPort = assetServer.address().port;- // Ensure the asset server is closed on any exit path+ // Ensure the asset server is closed and the overlay temp file removed on any exit path+ let captionOverlay;const closeAssetServer = () => { try { assetServer.close(); } catch {} };- process.on("SIGINT", () => { closeAssetServer(); process.exit(1); });- process.on("SIGTERM", () => { closeAssetServer(); process.exit(1); });+ const cleanupOnSignal = () => {+ closeAssetServer();+ if (captionOverlay && !opts["keep-overlay"]) {+ try { fs.unlinkSync(captionOverlay); } catch {}+ }+ process.exit(1);+ };+ process.on("SIGINT", cleanupOnSignal);+ process.on("SIGTERM", cleanupOnSignal);const videoSrc = `http://127.0.0.1:${assetPort}/clip.mp4`;const logoSrc = opts.logo ? `http://127.0.0.1:${assetPort}/logo.png` : undefined;@@ -159,7 +167,6 @@ async function main() {const cpus = os.cpus().length;const concurrency = Math.max(2, Math.min(cpus, 8));- let captionOverlay;if (opts["keep-overlay"]) {const outBase = opts.output.replace(/\.[^.]+$/, "");captionOverlay = `${outBase}_captions.mov`;diff --git a/remotion/src/Root.tsx b/remotion/src/Root.tsxindex 5a92408..b5ceac3 100644--- a/remotion/src/Root.tsx+++ b/remotion/src/Root.tsx@@ -1,12 +1,30 @@import "@fontsource/dm-sans/400.css";import "@fontsource/dm-sans/700.css";import React from "react";-import { Composition, getInputProps } from "remotion";+import { Composition, continueRender, delayRender, getInputProps } from "remotion";import { CaptionedClip } from "./CaptionedClip";import { Bookend } from "./Bookend";import { STYLES } from "./types";import type { Word } from "./types";+// @fontsource only injects @font-face CSS and the browser fetches lazily, so+// early frames can rasterize with fallback glyphs. Force the load and block+// rendering on it. fonts.load() is used because fonts.ready resolves+// immediately while no rendered text references the family yet.+const fontsReady = delayRender("Waiting for DM Sans");+Promise.all([+ document.fonts.load("400 16px 'DM Sans'"),+ document.fonts.load("700 16px 'DM Sans'"),+])+ .then(() => document.fonts.ready)+ .then(() => continueRender(fontsReady))+ .catch((err) => {+ // An unfetchable or unparseable woff2 must degrade to the fallback font. An+ // uncleared delayRender fails every frame instead, killing the whole render.+ console.warn("DM Sans failed to load, falling back:", err);+ continueRender(fontsReady);+ });+const inputProps = getInputProps() as {videoSrc?: string;words?: Word[];diff --git a/remotion/src/chunks.test.ts b/remotion/src/chunks.test.tsnew file mode 100644index 0000000..fde0cfd--- /dev/null+++ b/remotion/src/chunks.test.ts@@ -0,0 +1,72 @@+import { describe, it, expect } from "vitest";+import { buildChunks, activeChunkAt } from "./chunks";+import type { Word } from "./types";++function words(...spec: [string, number, number][]): Word[] {+ return spec.map(([word, start, end]) => ({ word, start, end }));+}++describe("buildChunks", () => {+ it("holds a chunk through a short pause so captions don't flicker", () => {+ const chunks = buildChunks(+ words(["one", 0, 0.4], ["two.", 0.4, 0.8], ["three", 1.0, 1.4]),+ { perChunk: 4 }+ );++ expect(chunks).toHaveLength(2);+ expect(chunks[0].end).toBe(0.8);+ expect(chunks[0].displayEnd).toBe(chunks[1].start);+ expect(activeChunkAt(chunks, 0.9)).toBe(chunks[0]);+ });++ it("caps the hold at 0.4s across a long silence", () => {+ const chunks = buildChunks(+ words(["one", 0, 0.4], ["two", 0.4, 0.8], ["three", 15.0, 15.4]),+ { perChunk: 4 }+ );++ expect(chunks).toHaveLength(2);+ expect(chunks[0].displayEnd).toBeCloseTo(1.2, 6);+ expect(activeChunkAt(chunks, 5)).toBeUndefined();+ });++ it("never displays past the next chunk's start", () => {+ const chunks = buildChunks(+ words(["one", 0, 0.9], ["two.", 0.9, 1.5], ["three", 1.5, 2.0]),+ { perChunk: 4 }+ );++ expect(chunks[0].displayEnd).toBe(chunks[1].start);+ });++ it("gives the last chunk a hold, clamped to the composition duration", () => {+ const spec: [string, number, number][] = [["one", 0, 0.4], ["two", 0.4, 0.8]];++ expect(buildChunks(words(...spec), { perChunk: 4 }).at(-1)!.displayEnd).toBeCloseTo(2.0, 6);+ expect(+ buildChunks(words(...spec), { perChunk: 4, clipEnd: 1.0 }).at(-1)!.displayEnd+ ).toBeCloseTo(1.0, 6);+ expect(+ buildChunks(words(...spec), { perChunk: 4, clipEnd: 10 }).at(-1)!.displayEnd+ ).toBeCloseTo(2.0, 6);+ });++ it("breaks on terminal punctuation, speaker change and long gaps", () => {+ const chunks = buildChunks(+ [+ { word: "hi.", start: 0, end: 0.3, speaker: "A" },+ { word: "so", start: 0.3, end: 0.6, speaker: "A" },+ { word: "yes", start: 0.6, end: 0.9, speaker: "B" },+ { word: "later", start: 3.0, end: 3.4, speaker: "B" },+ ],+ { perChunk: 8 }+ );++ expect(chunks.map((c) => c.words.map((w) => w.word).join(" "))).toEqual([+ "hi.",+ "so",+ "yes",+ "later",+ ]);+ });+});diff --git a/remotion/src/chunks.ts b/remotion/src/chunks.tsnew file mode 100644index 0000000..949a815--- /dev/null+++ b/remotion/src/chunks.ts@@ -0,0 +1,100 @@+import type { Word } from "./types";++export interface Chunk {+ words: Word[];+ start: number;+ end: number;+ displayEnd: number;+}++export interface ChunkOptions {+ perChunk: number;+ maxChars?: number;+ absorbTail?: number;+ splitTail?: boolean;+ /** Composition duration in seconds; caps the hold on the last chunk. */+ clipEnd?: number;+}++const BREAK_GAP_SECONDS = 0.8;+// Mirrors CAPTION_GAP_FILL_MAX in backend/services/caption_renderer.py: both+// renderers must burn the same caption timings.+const GAP_FILL_MAX_SECONDS = 0.4;+const LAST_CHUNK_HOLD_SECONDS = 1.2;+const TERMINAL_PUNCTUATION = /[.!?…]["')\]]?$/;++function breaksAfter(prev: Word, next: Word): boolean {+ return (+ TERMINAL_PUNCTUATION.test(prev.word.trim()) ||+ (prev.speaker != null && next.speaker != null && prev.speaker !== next.speaker) ||+ next.start - prev.end > BREAK_GAP_SECONDS+ );+}++function hasBreakBetween(words: Word[], from: number, to: number): boolean {+ for (let i = from; i < to; i++) {+ if (breaksAfter(words[i], words[i + 1])) return true;+ }+ return false;+}++export function buildChunks(words: Word[], opts: ChunkOptions): Chunk[] {+ const chunks: Chunk[] = [];+ let i = 0;++ while (i < words.length) {+ let end = i + 1;+ let charCount = words[i].word.trim().length;++ while (end < words.length && end - i < opts.perChunk) {+ if (breaksAfter(words[end - 1], words[end])) break;+ if (opts.maxChars != null) {+ const nextChars = charCount + 1 + words[end].word.trim().length;+ if (nextChars > opts.maxChars) break;+ charCount = nextChars;+ }+ end += 1;+ }++ if (+ opts.absorbTail != null &&+ end < words.length &&+ words.length - end <= opts.absorbTail &&+ !hasBreakBetween(words, end - 1, words.length - 1)+ ) {+ end = words.length;+ }+ if (opts.splitTail && words.length - end === 1 && end - i > 2) {+ end -= 1;+ }++ const slice = words.slice(i, end);+ const speechEnd = slice[slice.length - 1].end;+ chunks.push({+ words: slice,+ start: slice[0].start,+ end: speechEnd,+ displayEnd: speechEnd,+ });+ i = end;+ }++ // Captions vanishing during inter-chunk pauses reads as flicker, so a chunk+ // holds until the next one starts. The hold is capped, or a chunk break on a+ // long silence (a musical sting, dead air) freezes the last sentence on screen+ // for the whole pause.+ for (let k = 0; k < chunks.length; k++) {+ const next = chunks[k + 1];+ const hold = next+ ? Math.min(next.start, chunks[k].end + GAP_FILL_MAX_SECONDS)+ : chunks[k].end + LAST_CHUNK_HOLD_SECONDS;+ const capped = opts.clipEnd != null ? Math.min(hold, opts.clipEnd) : hold;+ chunks[k].displayEnd = Math.max(chunks[k].end, capped);+ }++ return chunks;+}++export function activeChunkAt(chunks: Chunk[], time: number): Chunk | undefined {+ return chunks.find((c) => time >= c.start && time < c.displayEnd);+}diff --git a/remotion/src/components/BrandedCaptions.tsx b/remotion/src/components/BrandedCaptions.tsxindex 75786df..789e310 100644--- a/remotion/src/components/BrandedCaptions.tsx+++ b/remotion/src/components/BrandedCaptions.tsx@@ -8,6 +8,7 @@ import {} from "remotion";import type { Word, CaptionStyle } from "../types";import { captionScale } from "../types";+import { buildChunks, activeChunkAt } from "../chunks";interface Props {words: Word[];@@ -16,62 +17,12 @@ interface Props {faceY?: number | null; // normalized 0-1 (0=top, 1=bottom)}-interface Chunk {- words: Word[];- start: number;- end: number;-}-const MAX_CHARS_PER_CHUNK = 18;-function buildChunks(words: Word[], perChunk: number): Chunk[] {- const chunks: Chunk[] = [];- let i = 0;-- while (i < words.length) {- let end = i;- let charCount = 0;-- while (end < words.length && end - i < perChunk) {- const nextWord = words[end].word.trim();- const nextChars = charCount === 0 ? nextWord.length : charCount + 1 + nextWord.length;-- if (end > i && nextChars > MAX_CHARS_PER_CHUNK) {- break;- }-- charCount = nextChars;- end += 1;- }-- if (end === i) {- end = i + 1;- }-- const remaining = words.length - end;- if (remaining === 1 && end - i > 2) {- end -= 1;- }-- const slice = words.slice(i, end);- chunks.push({- words: slice,- start: slice[0].start,- end: slice[slice.length - 1].end,- });- i = end;- }-- return chunks;-}-function splitIntoLines(words: Word[]): [Word[], Word[]] {if (words.length <= 2) {return [words, []];}- if (words.length === 3) {- return [words.slice(0, 2), words.slice(2)];- }return [words.slice(0, 2), words.slice(2)];}@@ -137,7 +88,8 @@ const CaptionLine: React.FC<{color: style.color,textShadow: "0 0 40px rgba(0, 0, 0, 0.15), 0 0 80px rgba(0, 0, 0, 0.1), 0 0 150px rgba(0, 0, 0, 0.08)",lineHeight: 1.25,- whiteSpace: "nowrap",+ maxWidth: "100%",+ overflowWrap: "anywhere",}}>{words.map((word, i) => {@@ -167,15 +119,18 @@ export const BrandedCaptions: React.FC<Props> = ({faceY,}) => {const frame = useCurrentFrame();- const { fps, height } = useVideoConfig();+ const { fps, height, durationInFrames } = useVideoConfig();const s = captionScale(height);const currentTime = frame / fps;const scaledStyle = { ...style, fontSize: style.fontSize * s };- const chunks = buildChunks(words, style.wordsPerChunk);- const activeChunk = chunks.find(- (c) => currentTime >= c.start && currentTime < c.end- );+ const chunks = buildChunks(words, {+ perChunk: style.wordsPerChunk,+ maxChars: MAX_CHARS_PER_CHUNK,+ splitTail: true,+ clipEnd: durationInFrames / fps,+ });+ const activeChunk = activeChunkAt(chunks, currentTime);// Dynamic margin: if face is in the lower portion, push captions further down// faceY is normalized 0-1 (0=top, 1=bottom)diff --git a/remotion/src/components/HormoziCaptions.tsx b/remotion/src/components/HormoziCaptions.tsxindex 7cb531c..a709056 100644--- a/remotion/src/components/HormoziCaptions.tsx+++ b/remotion/src/components/HormoziCaptions.tsx@@ -7,45 +7,25 @@ import {} from "remotion";import type { Word, CaptionStyle } from "../types";import { captionScale } from "../types";+import { buildChunks, activeChunkAt } from "../chunks";interface Props {words: Word[];style: CaptionStyle;}-interface Chunk {- words: Word[];- start: number;- end: number;-}--function buildChunks(words: Word[], perChunk: number): Chunk[] {- const chunks: Chunk[] = [];- let i = 0;- while (i < words.length) {- let end = Math.min(i + perChunk, words.length);- if (words.length - end === 1) end = words.length;- const slice = words.slice(i, end);- chunks.push({- words: slice,- start: slice[0].start,- end: slice[slice.length - 1].end,- });- i = end;- }- return chunks;-}-export const HormoziCaptions: React.FC<Props> = ({ words, style }) => {const frame = useCurrentFrame();- const { fps, height } = useVideoConfig();+ const { fps, height, durationInFrames } = useVideoConfig();const s = captionScale(height);const currentTime = frame / fps;- const chunks = buildChunks(words, style.wordsPerChunk);- const activeChunk = chunks.find(- (c) => currentTime >= c.start && currentTime < c.end- );+ const chunks = buildChunks(words, {+ perChunk: style.wordsPerChunk,+ absorbTail: 1,+ clipEnd: durationInFrames / fps,+ });+ const activeChunk = activeChunkAt(chunks, currentTime);if (!activeChunk) return null;@@ -82,6 +62,9 @@ export const HormoziCaptions: React.FC<Props> = ({ words, style }) => {backgroundColor: "rgba(0, 0, 0, 0.8)",borderRadius: 16 * s,padding: `${14 * s}px ${32 * s}px`,+ maxWidth: `calc(100% - ${120 * s}px)`,+ boxSizing: "border-box",+ overflowWrap: "anywhere",textAlign: "center",fontFamily: style.fontFamily,fontSize: style.fontSize * s,diff --git a/remotion/src/components/KaraokeCaptions.tsx b/remotion/src/components/KaraokeCaptions.tsxindex 30a2f35..20bee27 100644--- a/remotion/src/components/KaraokeCaptions.tsx+++ b/remotion/src/components/KaraokeCaptions.tsx@@ -2,35 +2,13 @@ import React from "react";import { useCurrentFrame, useVideoConfig } from "remotion";import type { Word, CaptionStyle } from "../types";import { captionScale } from "../types";+import { buildChunks, activeChunkAt } from "../chunks";interface Props {words: Word[];style: CaptionStyle;}-interface Chunk {- words: Word[];- start: number;- end: number;-}--function buildChunks(words: Word[], perChunk: number): Chunk[] {- const chunks: Chunk[] = [];- let i = 0;- while (i < words.length) {- let end = Math.min(i + perChunk, words.length);- if (words.length - end === 1) end = words.length;- const slice = words.slice(i, end);- chunks.push({- words: slice,- start: slice[0].start,- end: slice[slice.length - 1].end,- });- i = end;- }- return chunks;-}-function splitIntoLines(words: Word[]): [Word[], Word[]] {if (words.length <= 3) return [words, []];const mid = Math.ceil(words.length / 2);@@ -88,14 +66,16 @@ const KaraokeLine: React.FC<{export const KaraokeCaptions: React.FC<Props> = ({ words, style }) => {const frame = useCurrentFrame();- const { fps, height } = useVideoConfig();+ const { fps, height, durationInFrames } = useVideoConfig();const s = captionScale(height);const currentTime = frame / fps;- const chunks = buildChunks(words, style.wordsPerChunk);- const activeChunk = chunks.find(- (c) => currentTime >= c.start && currentTime < c.end- );+ const chunks = buildChunks(words, {+ perChunk: style.wordsPerChunk,+ absorbTail: 1,+ clipEnd: durationInFrames / fps,+ });+ const activeChunk = activeChunkAt(chunks, currentTime);if (!activeChunk) return null;diff --git a/remotion/src/components/SubtleCaptions.tsx b/remotion/src/components/SubtleCaptions.tsxindex 5c538a6..3f985dd 100644--- a/remotion/src/components/SubtleCaptions.tsx+++ b/remotion/src/components/SubtleCaptions.tsx@@ -2,35 +2,13 @@ import React from "react";import { useCurrentFrame, useVideoConfig, interpolate } from "remotion";import type { Word, CaptionStyle } from "../types";import { captionScale } from "../types";+import { buildChunks, activeChunkAt } from "../chunks";interface Props {words: Word[];style: CaptionStyle;}-interface Chunk {- words: Word[];- start: number;- end: number;-}--function buildChunks(words: Word[], perChunk: number): Chunk[] {- const chunks: Chunk[] = [];- let i = 0;- while (i < words.length) {- let end = Math.min(i + perChunk, words.length);- if (words.length - end <= 2) end = words.length;- const slice = words.slice(i, end);- chunks.push({- words: slice,- start: slice[0].start,- end: slice[slice.length - 1].end,- });- i = end;- }- return chunks;-}-function splitIntoLines(words: Word[]): [Word[], Word[]] {if (words.length <= 4) return [words, []];const mid = Math.ceil(words.length / 2);@@ -39,14 +17,16 @@ function splitIntoLines(words: Word[]): [Word[], Word[]] {export const SubtleCaptions: React.FC<Props> = ({ words, style }) => {const frame = useCurrentFrame();- const { fps, height } = useVideoConfig();+ const { fps, height, durationInFrames } = useVideoConfig();const s = captionScale(height);const currentTime = frame / fps;- const chunks = buildChunks(words, style.wordsPerChunk);- const activeChunk = chunks.find(- (c) => currentTime >= c.start && currentTime < c.end- );+ const chunks = buildChunks(words, {+ perChunk: style.wordsPerChunk,+ absorbTail: 2,+ clipEnd: durationInFrames / fps,+ });+ const activeChunk = activeChunkAt(chunks, currentTime);if (!activeChunk) return null;diff --git a/remotion/src/types.ts b/remotion/src/types.tsindex ed17909..b7a2cbb 100644--- a/remotion/src/types.ts+++ b/remotion/src/types.ts@@ -14,7 +14,6 @@ export interface CaptionStyle {activeColor: string;uppercase: boolean;wordsPerChunk: number;- position: "bottom" | "center" | "lower-third";marginBottom: number;}@@ -46,7 +45,6 @@ export const STYLES: Record<string, CaptionStyle> = {activeColor: "#FFFF00",uppercase: true,wordsPerChunk: 3,- position: "bottom",marginBottom: 400,},karaoke: {@@ -57,7 +55,6 @@ export const STYLES: Record<string, CaptionStyle> = {activeColor: "#FFFFFF",uppercase: false,wordsPerChunk: 5,- position: "bottom",marginBottom: 400,},subtle: {@@ -68,7 +65,6 @@ export const STYLES: Record<string, CaptionStyle> = {activeColor: "#FFFFFF",uppercase: false,wordsPerChunk: 6,- position: "bottom",marginBottom: 200,},branded: {@@ -79,7 +75,6 @@ export const STYLES: Record<string, CaptionStyle> = {activeColor: "#FFFFFF",uppercase: false,wordsPerChunk: 3,- position: "lower-third",marginBottom: 420,},};diff --git a/scripts/build-remotion.sh b/scripts/build-remotion.shindex aef6c3a..55c5da2 100644--- a/scripts/build-remotion.sh+++ b/scripts/build-remotion.sh@@ -17,23 +17,9 @@ rm -rf "$out"mkdir -p "$out"cp -R "$here/remotion" "$out/remotion"cp "$here/tsconfig.json" "$out/tsconfig.json" 2>/dev/null || true--cat > "$out/package.json" <<'JSON'-{- "name": "podcli-remotion-bundle",- "private": true,- "type": "module",- "dependencies": {- "@remotion/bundler": "^4.0.441",- "@remotion/renderer": "^4.0.441",- "remotion": "^4.0.441",- "react": "^18.3.1",- "react-dom": "^18.3.1",- "@fontsource/dm-sans": "^5.2.8"- }-}-JSON+mv "$out/remotion/package.json" "$out/package.json"+mv "$out/remotion/package-lock.json" "$out/package-lock.json"cd "$out"-npm install --omit=dev --no-audit --no-fund --no-package-lock+npm ci --omit=dev --no-audit --no-fundecho "remotion bundle -> $out"diff --git a/scripts/check-docs-drift.mjs b/scripts/check-docs-drift.mjsindex 29fdab2..96b5090 100644--- a/scripts/check-docs-drift.mjs+++ b/scripts/check-docs-drift.mjs@@ -28,6 +28,28 @@ for (const claim of toolClaims) {}}+const claudeMd = read("CLAUDE.md");+const toolSection = claudeMd.split(/^## MCP tools/m)[1]?.split(/^## /m)[0] ?? "";+const documentedTools = [...toolSection.matchAll(/^\| `([a-z0-9_]+)` \|/gm)].map((m) => m[1]).sort();+if (Array.isArray(manifest.mcpToolNames)) {+ const registered = [...manifest.mcpToolNames].sort();+ const missing = registered.filter((t) => !documentedTools.includes(t));+ const stale = documentedTools.filter((t) => !registered.includes(t));+ if (missing.length) errors.push(`CLAUDE.md MCP tool table is missing: ${missing.join(", ")}`);+ if (stale.length) errors.push(`CLAUDE.md MCP tool table lists unregistered tools: ${stale.join(", ")}`);+ if (documentedTools.length !== registered.length) {+ errors.push(`CLAUDE.md documents ${documentedTools.length} MCP tools but src registers ${registered.length}.`);+ }+ const claudeClaims = [...new Set([...claudeMd.matchAll(/All (\d+) tools/g)].map((m) => Number(m[1])))];+ for (const claim of claudeClaims) {+ if (claim !== registered.length) {+ errors.push(`CLAUDE.md claims "${claim} tools" but src registers ${registered.length}.`);+ }+ }+} else {+ errors.push("docs-manifest.json has no mcpToolNames. Re-run: node scripts/gen-docs-manifest.mjs");+}+if (manifest.packageVersion && manifest.version && !manifest.version.endsWith(manifest.packageVersion)) {warnings.push(`package.json version ${manifest.packageVersion} lags the latest tag ${manifest.version}.`);}diff --git a/scripts/e2e_render.py b/scripts/e2e_render.pynew file mode 100644index 0000000..afef846--- /dev/null+++ b/scripts/e2e_render.py@@ -0,0 +1,233 @@+"""End-to-end render check: synthetic video in, real clip out.++CI only ever ran unit tests, so a change that broke the render pipeline (a+Remotion runtime mismatch, a bad ffmpeg flag, a caption regression) could pass+every check and still ship. This drives the pipeline the product actually runs+and asserts the artifact is real.++Captions are proven by rendering the same clip twice, with and without words,+and diffing the pixels: probing the container cannot tell a captioned clip from+an uncaptioned one.+"""++import json+import os+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "backend"))++ARTIFACT_DIR = ROOT / "e2e-artifacts"++CLIP_START = 2.0+CLIP_END = 8.0+EXPECTED_DURATION = CLIP_END - CLIP_START+DURATION_TOLERANCE = 1.5 # outro/intro-free clip, but encoders round frame counts++WORDS = [+ {"word": "the", "start": 2.1, "end": 2.35},+ {"word": "secret", "start": 2.35, "end": 2.8},+ {"word": "to", "start": 2.8, "end": 2.95},+ {"word": "growth", "start": 2.95, "end": 3.5},+ {"word": "is", "start": 4.2, "end": 4.4},+ {"word": "boring", "start": 4.4, "end": 4.9},+ {"word": "work", "start": 4.9, "end": 5.4},+ {"word": "done", "start": 5.6, "end": 6.0},+ {"word": "every", "start": 6.0, "end": 6.4},+ {"word": "single", "start": 6.4, "end": 6.9},+ {"word": "day", "start": 6.9, "end": 7.4},+]++# Clip-relative seconds, each one mid-word so some chunk is always on screen.+SAMPLE_TIMES = [0.6, 2.6, 5.0]++# All four styles anchor captions to the bottom of the frame (margins 200-420px+# on a 1920-tall canvas), and nothing is ever drawn in the top half.+CAPTION_BAND = (0.55, 1.0)+CONTROL_BAND = (0.0, 0.45)++PIXEL_DELTA = 40 # a caption stroke moves a pixel far further than a re-encode does+MIN_CAPTION_COVERAGE = 0.004+MIN_SIGNAL_RATIO = 5.0+++class CheckFailed(Exception):+ pass+++def ffprobe(path: str) -> dict:+ out = subprocess.run(+ ["ffprobe", "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path],+ capture_output=True,+ text=True,+ check=True,+ )+ return json.loads(out.stdout)+++def make_source(path: str) -> None:+ subprocess.run(+ [+ "ffmpeg", "-y", "-v", "error",+ "-f", "lavfi", "-i", "testsrc=size=1280x720:rate=30:duration=12",+ "-f", "lavfi", "-i", "sine=frequency=440:duration=12",+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-shortest", path,+ ],+ check=True,+ capture_output=True,+ )+++def extract_frame(video: str, second: float, path: str) -> None:+ subprocess.run(+ [+ "ffmpeg", "-y", "-v", "error",+ "-ss", str(second), "-i", video, "-frames:v", "1", path,+ ],+ check=True,+ capture_output=True,+ )+++def band(frame, bounds: tuple[float, float]):+ top, bottom = bounds+ height = frame.shape[0]+ return frame[int(height * top):int(height * bottom)]+++def changed_fractions(captioned: str, plain: str) -> tuple[float, float]:+ import numpy as np+ from PIL import Image++ a = np.asarray(Image.open(captioned).convert("L"), dtype=np.int16)+ b = np.asarray(Image.open(plain).convert("L"), dtype=np.int16)+ if a.shape != b.shape:+ raise CheckFailed(f"frames differ in size: {a.shape} vs {b.shape}")++ delta = np.abs(a - b)+ return (+ float((band(delta, CAPTION_BAND) > PIXEL_DELTA).mean()),+ float((band(delta, CONTROL_BAND) > PIXEL_DELTA).mean()),+ )+++def check(name: str, condition: bool, detail: str = "") -> None:+ if condition:+ print(f" ok {name}")+ return+ raise CheckFailed(f"{name}{': ' + detail if detail else ''}")+++def keep_artifacts(style: str, work: str) -> None:+ dest = ARTIFACT_DIR / style+ dest.mkdir(parents=True, exist_ok=True)+ for found in Path(work).rglob("*"):+ if found.suffix in (".mp4", ".png") and found.is_file():+ flattened = "-".join(found.relative_to(work).parts)+ shutil.copy2(found, dest / flattened)+ print(f" saved failure artifacts to {dest}")+++def render(style: str, source: str, out_dir: str, words: list) -> str:+ from services.clip_generator import generate_clip++ os.makedirs(out_dir, exist_ok=True)+ result = generate_clip(+ video_path=source,+ start_second=CLIP_START,+ end_second=CLIP_END,+ caption_style=style,+ crop_strategy="speaker",+ format="vertical",+ transcript_words=words,+ title=f"e2e {style}",+ output_dir=out_dir,+ clean_fillers=False,+ )+ path = result.get("output_path") or result.get("path")+ check("pipeline reported success", bool(path), json.dumps(result)[:300])+ check("output file exists", os.path.exists(path), str(path))+ return path+++def run(style: str, work: str) -> None:+ source = os.path.join(work, "source.mp4")++ print(f"[{style}] building synthetic source")+ make_source(source)++ print(f"[{style}] rendering clip {CLIP_START}s to {CLIP_END}s")+ path = render(style, source, os.path.join(work, "captioned"), WORDS)+ check("output is not empty", os.path.getsize(path) > 20_000, f"{os.path.getsize(path)} bytes")++ probe = ffprobe(path)+ streams = {s["codec_type"]: s for s in probe["streams"]}+ check("has a video stream", "video" in streams)+ check("has an audio stream", "audio" in streams)++ duration = float(probe["format"]["duration"])+ check(+ "duration matches the requested clip",+ abs(duration - EXPECTED_DURATION) <= DURATION_TOLERANCE,+ f"expected ~{EXPECTED_DURATION}s, got {duration:.2f}s",+ )++ width = int(streams["video"]["width"])+ height = int(streams["video"]["height"])+ check("is vertical", height > width, f"{width}x{height}")++ print(f"[{style}] re-rendering the same clip with no words, to diff against")+ plain = render(style, source, os.path.join(work, "plain"), [])++ coverage = []+ noise = []+ for i, second in enumerate(SAMPLE_TIMES):+ a = os.path.join(work, "captioned", f"frame-{i}.png")+ b = os.path.join(work, "plain", f"frame-{i}.png")+ extract_frame(path, second, a)+ extract_frame(plain, second, b)+ captioned_frac, control_frac = changed_fractions(a, b)+ coverage.append(captioned_frac)+ noise.append(control_frac)+ print(f" t={second}s caption band {captioned_frac:.3%} control band {control_frac:.3%}")++ check(+ "captions are burned into every sampled frame",+ min(coverage) >= MIN_CAPTION_COVERAGE,+ f"lowest caption-band coverage was {min(coverage):.3%}, needs {MIN_CAPTION_COVERAGE:.3%}",+ )+ check(+ "the caption band changed, not the whole frame",+ min(coverage) >= MIN_SIGNAL_RATIO * max(noise),+ f"caption band {min(coverage):.3%} vs control band {max(noise):.3%}",+ )++ print(f"[{style}] {width}x{height}, {duration:.2f}s, {os.path.getsize(path) // 1024}KB")+++def main() -> int:+ style = sys.argv[1] if len(sys.argv) > 1 else "branded"+ if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):+ print("ffmpeg/ffprobe not on PATH")+ return 1++ work = tempfile.mkdtemp(prefix="podcli-e2e-")+ try:+ run(style, work)+ return 0+ except CheckFailed as failure:+ print(f" FAIL {failure}")+ keep_artifacts(style, work)+ return 1+ finally:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/gen-docs-manifest.mjs b/scripts/gen-docs-manifest.mjsindex 71017b0..2405e0c 100644--- a/scripts/gen-docs-manifest.mjs+++ b/scripts/gen-docs-manifest.mjs@@ -6,14 +6,36 @@ import { fileURLToPath } from "url";const root = join(dirname(fileURLToPath(import.meta.url)), "..");const read = (p) => readFileSync(join(root, p), "utf8");-function countTools(dir) {- let n = 0;+function tsSources(dir, acc = []) {for (const entry of readdirSync(join(root, dir), { withFileTypes: true })) {const rel = join(dir, entry.name);- if (entry.isDirectory()) n += countTools(rel);- else if (entry.name.endsWith(".ts")) n += (read(rel).match(/server\.tool\(/g) || []).length;+ if (entry.isDirectory()) tsSources(rel, acc);+ else if (entry.name.endsWith(".ts")) acc.push(read(rel));}- return n;+ return acc;+}++function collectToolNames(sources) {+ const defs = new Map();+ const names = [];+ let registrations = 0;+ for (const src of sources) {+ for (const m of src.matchAll(/const\s+(\w+)\s*=\s*\{\s*name:\s*"([^"]+)"/g)) {+ defs.set(m[1], m[2]);+ }+ }+ for (const src of sources) {+ for (const m of src.matchAll(/server\.tool\(\s*(?:"([^"]+)"|(\w+)\.name)/g)) {+ registrations += 1;+ if (m[1]) names.push(m[1]);+ else if (defs.has(m[2])) names.push(defs.get(m[2]));+ }+ }+ if (names.length !== registrations) {+ console.error(`resolved ${names.length} tool names for ${registrations} server.tool( registrations`);+ process.exit(1);+ }+ return names.sort();}const mainTsx = read("src/ui/client/main.tsx");@@ -28,10 +50,13 @@ try {version = JSON.parse(read("package.json")).version || "";}+const mcpToolNames = collectToolNames(tsSources("src"));+const manifest = {version,packageVersion: JSON.parse(read("package.json")).version || "",- mcpToolCount: countTools("src"),+ mcpToolCount: mcpToolNames.length,+ mcpToolNames,studioRouteCount: studioRoutes.length,studioRoutes,};diff --git a/src/config/server.test.ts b/src/config/server.test.tsnew file mode 100644index 0000000..dedc9a6--- /dev/null+++ b/src/config/server.test.ts@@ -0,0 +1,23 @@+import { describe, it, expect } from "vitest";+import { resolveWebServerPort } from "./server.js";++describe("resolveWebServerPort", () => {+ it("defaults to 3847", () => {+ expect(resolveWebServerPort({})).toBe(3847);+ });++ it("reads PODCLI_PORT first", () => {+ expect(resolveWebServerPort({ PODCLI_PORT: "4000", PORT: "5000" })).toBe(4000);+ });++ it("falls back to PORT", () => {+ expect(resolveWebServerPort({ PORT: "5000" })).toBe(5000);+ });++ it("rejects garbage and out-of-range values", () => {+ expect(resolveWebServerPort({ PORT: "banana" })).toBe(3847);+ expect(resolveWebServerPort({ PORT: "0" })).toBe(3847);+ expect(resolveWebServerPort({ PORT: "70000" })).toBe(3847);+ expect(resolveWebServerPort({ PORT: "-1" })).toBe(3847);+ });+});diff --git a/src/config/server.ts b/src/config/server.tsnew file mode 100644index 0000000..dc75d0c--- /dev/null+++ b/src/config/server.ts@@ -0,0 +1,8 @@+export function resolveWebServerPort(env: NodeJS.ProcessEnv = process.env): number {+ const raw = env.PODCLI_PORT || env.PORT;+ const parsed = raw ? parseInt(raw, 10) : NaN;+ return Number.isInteger(parsed) && parsed > 0 && parsed <= 65535 ? parsed : 3847;+}++export const webServerPort = resolveWebServerPort();+export const webServerUrl = `http://localhost:${webServerPort}`;diff --git a/src/handlers/batch-clips.handler.ts b/src/handlers/batch-clips.handler.tsindex aad3c6b..8b178f8 100644--- a/src/handlers/batch-clips.handler.ts+++ b/src/handlers/batch-clips.handler.ts@@ -3,6 +3,8 @@ import { PythonExecutor } from "../services/python-executor.js";import { FileManager } from "../services/file-manager.js";import { ClipsHistory } from "../services/clips-history.js";import { paths } from "../config/paths.js";+import { webServerUrl } from "../config/server.js";+import { validateClipRange } from "../utils/clip-validation.js";import { childLogger } from "../utils/logger.js";import type {BatchClipsInput,@@ -34,6 +36,8 @@ export const batchClipsToolDef = {"EASIEST: pass export_selected=true to export all selected clips in one go.\n" +"Alternative: pass clip_numbers=[1, 3, 5] for specific ones.\n" +"Everything (video, timestamps, settings) auto-loads from session state.\n\n" ++ "Pass exactly one of clips, clip_numbers, or export_selected. If several are given, " ++ "an explicit clips array wins, then export_selected, then clip_numbers.\n\n" +"Each clip gets: 9:16 vertical crop, burned-in captions, normalized audio, H.264 MP4.",inputSchema: {type: "object" as const,@@ -149,13 +153,16 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>let clips: BatchClipSpec[];const deselected = state?.deselectedIndices ?? [];+ const batchFormat = input.format || settings.format || "vertical";+ const cleanFillers = input.clean_fillers ?? settings.cleanFillers ?? true;+const buildClipFromSuggestion = (s: SuggestedClip, num: number): BatchClipSpec => ({start_second: s.start_second,end_second: s.end_second,title: s.title || `clip_${num}`,caption_style: s.suggested_caption_style || settings.captionStyle || "hormozi",crop_strategy: settings.cropStrategy || "speaker",- format: input.format || settings.format || "vertical",+ format: batchFormat,allow_ass_fallback: input.allow_ass_fallback === true,keep_caption_overlay: input.keep_caption_overlay === true,logo_path: settings.logoPath || null,@@ -205,19 +212,31 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>clips = clips.map((c) => ({ ...c, keep_caption_overlay: c.keep_caption_overlay ?? true }));}+ for (let i = 0; i < clips.length; i++) {+ const rangeError = validateClipRange(+ clips[i].start_second,+ clips[i].end_second,+ clips[i].format || batchFormat,+ );+ if (rangeError) {+ return JSON.stringify({ error: `Clip ${i + 1}: ${rangeError}` });+ }+ }+// Async path — route through Web UI so caller can poll job_status for// live progress during a multi-minute render. Falls back to sync if the// UI isn't running.if (input.async_mode) {try {- const res = await fetch("http://localhost:3847/api/batch-clips", {+ const res = await fetch(`${webServerUrl}/api/batch-clips`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({video_path: videoPath,clips,+ format: batchFormat,transcript_words: transcriptWords,- clean_fillers: input.clean_fillers !== false,+ clean_fillers: cleanFillers,logo_path: settings.logoPath || null,outro_path: settings.outroPath || null,intro_path: settings.introPath || null,@@ -246,8 +265,9 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>const result = await executor.execute<BatchClipsResult>("batch_clips", {video_path: videoPath,clips,+ format: batchFormat,transcript_words: transcriptWords,- clean_fillers: input.clean_fillers !== false,+ clean_fillers: cleanFillers,allow_ass_fallback: input.allow_ass_fallback === true,keep_caption_overlay: input.keep_caption_overlay === true,output_dir: paths.output,@@ -266,7 +286,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>transcriptWords: transcriptWords,defaultCaptionStyle: settings.captionStyle || "hormozi",defaultCropStrategy: settings.cropStrategy || "speaker",- defaultFormat: input.format || settings.format || "vertical",+ defaultFormat: batchFormat,});await history.persistBatchRecipes(data.results, recorded, {transcriptWords: transcriptWords,@@ -274,7 +294,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>logoPath: settings.logoPath || null,outroPath: settings.outroPath || null,introPath: settings.introPath || null,- cleanFillers: input.clean_fillers !== false,+ cleanFillers,});return JSON.stringify({diff --git a/src/handlers/create-clip.handler.ts b/src/handlers/create-clip.handler.tsindex c046627..15f183e 100644--- a/src/handlers/create-clip.handler.ts+++ b/src/handlers/create-clip.handler.ts@@ -5,6 +5,7 @@ import { paths } from "../config/paths.js";import type { ClipResult, CreateClipInput, SuggestedClip, UIState } from "../models/index.js";import { childLogger } from "../utils/logger.js";import { sliceTranscript } from "../utils/transcript.js";+import { validateClipRange } from "../utils/clip-validation.js";const log = childLogger("create-clip");const executor = new PythonExecutor();@@ -176,6 +177,10 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>error: "start_second and end_second are required (use clip_number to reference a suggestion)",});}+ const rangeError = validateClipRange(startSecond, endSecond, format);+ if (rangeError) {+ return JSON.stringify({ error: rangeError });+ }const result = await executor.execute<ClipResult>("create_clip", {video_path: videoPath,@@ -187,7 +192,7 @@ export async function handleCreateClip(input: CreateClipInput): Promise<string>transcript_words: transcriptWords,title,output_dir: paths.output,- clean_fillers: input.clean_fillers !== false,+ clean_fillers: input.clean_fillers ?? settings.cleanFillers ?? true,allow_ass_fallback: input.allow_ass_fallback === true,keep_caption_overlay: input.keep_caption_overlay === true,logo_path: logoPath,diff --git a/src/handlers/suggest-clips.handler.ts b/src/handlers/suggest-clips.handler.tsindex 3e2d67c..772c34d 100644--- a/src/handlers/suggest-clips.handler.ts+++ b/src/handlers/suggest-clips.handler.ts@@ -6,6 +6,7 @@*/import { randomUUID } from "crypto";+import { validateSuggestionRange } from "../utils/clip-validation.js";export const suggestClipsToolDef = {name: "suggest_clips",@@ -102,6 +103,14 @@ export interface SuggestClipsInput {export async function handleSuggestClips(input: SuggestClipsInput): Promise<string> {const suggestions = input.suggestions;+ for (let i = 0; i < suggestions.length; i++) {+ const s = suggestions[i];+ const rangeError = validateSuggestionRange(s.start_second, s.end_second);+ if (rangeError) {+ throw new Error(`Suggestion ${i + 1} ("${s.title}"): ${rangeError}`);+ }+ }+// Validate and enrich suggestionsconst enriched = suggestions.map((s, i) => {// Compute duration from segments if available, otherwise from start/enddiff --git a/src/handlers/transcribe.handler.ts b/src/handlers/transcribe.handler.tsindex e15f789..8f1f57a 100644--- a/src/handlers/transcribe.handler.ts+++ b/src/handlers/transcribe.handler.ts@@ -1,6 +1,7 @@import { basename } from "path";import { PythonExecutor } from "../services/python-executor.js";import { TranscriptCache } from "../services/transcript-cache.js";+import { webServerUrl } from "../config/server.js";import type { TranscriptResult } from "../models/index.js";const executor = new PythonExecutor();@@ -19,7 +20,8 @@ export const transcribeToolDef = {name: "transcribe_podcast",description:"STEP 1 — Transcribe a podcast video/audio file. This is typically the first tool you call.\n\n" +- "What it does: Uses Whisper AI for word-level timestamps + pyannote for speaker detection (who said what).\n" ++ "What it does: Uses Whisper AI for word-level timestamps. Speaker detection (who said what) is off by " ++ "default; pass enable_diarization=true to add speaker labels where torch/pyannote is available (whisper-py engine).\n" +"Returns: Lightweight metadata only — duration, language, word/segment counts, speaker summary, and " +"packed_ready flag. The actual transcript body is NOT returned here (it would be 500KB+ for a typical " +"episode). Read the content via get_ui_state(include_transcript: true) which returns a compact " +@@ -54,8 +56,9 @@ export const transcribeToolDef = {enable_diarization: {type: "boolean",description:- "Enable speaker detection (who is speaking). Requires pyannote.audio. Default: true",- default: true,+ "Set true for speaker labels (who is speaking). Works where torch/pyannote.audio is available " ++ "(whisper-py engine); slower. Default: false",+ default: false,},num_speakers: {type: "number",@@ -73,7 +76,7 @@ export async function handleTranscribe(input: TranscribeInput): Promise<string>const modelSize = input.model_size ?? "base";const engine = input.engine;const language = input.language;- const enableDiarization = input.enable_diarization !== false; // default true+ const enableDiarization = input.enable_diarization === true;const numSpeakers = input.num_speakers;// Check cache first@@ -150,7 +153,7 @@ export const transcribeStartToolDef = {"Use this instead of transcribe_podcast for long files so you can narrate progress " +"to the user while it runs (a 60-min episode takes 15–25 min).\n\n" +"Flow: call transcribe_start(file_path) → emit status text to user → " +- "call transcribe_status(job_id, wait_seconds: 30) in a loop until done → " ++ "call job_status(job_id, wait_seconds: 30) in a loop until done → " +"then read the packed transcript via get_ui_state(include_transcript: true).\n\n" +"Requires the Web UI to be running (npm run ui). Returns { job_id, cached, status, estimate_minutes }.",inputSchema: {@@ -167,7 +170,7 @@ export const transcribeStartToolDef = {type: "string",enum: ["whisper-py", "whispercpp", "assemblyai"],},- enable_diarization: { type: "boolean", default: true },+ enable_diarization: { type: "boolean", default: false },num_speakers: { type: "number" },},required: ["file_path"],@@ -176,7 +179,7 @@ export const transcribeStartToolDef = {export async function handleTranscribeStart(input: TranscribeInput): Promise<string> {try {- const res = await fetch("http://localhost:3847/api/transcribe", {+ const res = await fetch(`${webServerUrl}/api/transcribe`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -184,7 +187,7 @@ export async function handleTranscribeStart(input: TranscribeInput): Promise<strmodel_size: input.model_size ?? "base",engine: input.engine,language: input.language,- enable_diarization: input.enable_diarization !== false,+ enable_diarization: input.enable_diarization === true,num_speakers: input.num_speakers,}),});@@ -259,7 +262,7 @@ export async function handleJobStatus(input: {try {while (true) {- const res = await fetch(`http://localhost:3847/api/job/${input.job_id}`);+ const res = await fetch(`${webServerUrl}/api/job/${input.job_id}`);if (res.status === 404) {return JSON.stringify({ error: `Job ${input.job_id} not found` });}diff --git a/src/models/index.ts b/src/models/index.tsindex dc538db..64054e3 100644--- a/src/models/index.ts+++ b/src/models/index.ts@@ -123,6 +123,7 @@ export interface UIState {logoPath?: string;outroPath?: string;introPath?: string;+ cleanFillers?: boolean;};phase?: string;lastUpdated?: number;@@ -187,6 +188,9 @@ export interface BatchClipsResult {output_path?: string;start_second?: number;end_second?: number;+ /** Bounds of the clip as submitted; the renderer may trim start_second. */+ source_start_second?: number;+ source_end_second?: number;caption_style?: string;crop_strategy?: string;format?: Format;diff --git a/src/server.ts b/src/server.tsindex f533ff1..6c11eda 100644--- a/src/server.ts+++ b/src/server.ts@@ -29,10 +29,11 @@ import { AssetManager, inferType } from "./services/asset-manager.js";import { ClipsHistory } from "./services/clips-history.js";import { TranscriptCache } from "./services/transcript-cache.js";import { paths } from "./config/paths.js";+import { webServerUrl } from "./config/server.js";import { childLogger } from "./utils/logger.js";import { mcpError } from "./utils/errors.js";import { podcliVersion } from "./version.js";-import type { BatchClipsResult, Format, UIState, WordTimestamp } from "./models/index.js";+import type { Format, SuggestedClip, UIState, WordTimestamp } from "./models/index.js";const log = childLogger("server");@@ -42,9 +43,23 @@ const log = childLogger("server");*/const transcriptCache = new TranscriptCache();+/**+ * Only a studio that isn't listening may be retried inline. A render that+ * started and then failed, timed out, or went missing must surface — retrying it+ * would render the same clips twice.+ */+function studioUnreachable(err: unknown, label: string): boolean {+ const msg = err instanceof Error ? err.message : String(err);+ if (!msg.includes("ECONNREFUSED") && !msg.includes("fetch failed")) return false;+ log.warn(+ `Studio not reachable at ${webServerUrl}. Running ${label} inline without live progress. If the studio listens on another port, set PODCLI_PORT for this MCP server too.`,+ );+ return true;+}+async function uiPing(body: Record<string, unknown>): Promise<void> {try {- await fetch("http://localhost:3847/api/ui-state", {+ await fetch(`${webServerUrl}/api/ui-state`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(body),@@ -77,6 +92,19 @@ function withNextStep(result: string, nextStep: string): string {return `${result}\n\n---\n[Next Step] ${nextStep}`;}+// Fallback transcript views (no packed markdown available) can be 500KB+ for a+// long episode; cap what goes into a tool response.+const TRANSCRIPT_FALLBACK_CAP = 50_000;++function capTranscriptText(text: string): string {+ if (text.length <= TRANSCRIPT_FALLBACK_CAP) return text;+ return (+ text.slice(0, TRANSCRIPT_FALLBACK_CAP) ++ `\n\n[Transcript truncated: showing the first ${TRANSCRIPT_FALLBACK_CAP} of ${text.length} characters. ` ++ "Use parse_transcript or transcribe_podcast to generate the packed view for full coverage.]"+ );+}+/*** Read UI state from the optional Web UI server.* Returns null when the UI isn't running (expected in headless mode).@@ -138,7 +166,7 @@ interface ImportTranscriptResult extends ApiError {async function readUIState(): Promise<ServerUIState | null> {try {- const res = await fetch("http://localhost:3847/api/ui-state");+ const res = await fetch(`${webServerUrl}/api/ui-state`);if (!res.ok) return null;return (await res.json()) as ServerUIState;} catch (err) {@@ -249,8 +277,10 @@ export function createServer(): McpServer {enable_diarization: z.boolean().optional()- .default(true)- .describe("Enable speaker detection (who is speaking). Default: true"),+ .default(false)+ .describe(+ "Set true for speaker labels (who is speaking). Works where torch is available (whisper-py engine); slower. Default: false",+ ),num_speakers: z.number().optional()@@ -321,7 +351,7 @@ export function createServer(): McpServer {.default("base"),language: z.string().optional(),engine: z.enum(["whisper-py", "whispercpp", "assemblyai"]).optional(),- enable_diarization: z.boolean().optional().default(true),+ enable_diarization: z.boolean().optional().default(false),num_speakers: z.number().optional(),},async (input) => {@@ -481,6 +511,12 @@ export function createServer(): McpServer {.describe("Allow ASS caption fallback if Remotion rendering fails (default: false)",),+ clean_fillers: z+ .boolean()+ .optional()+ .describe(+ "Remove filler words (um, uh, hmm) from captions and compress long silences. Defaults to the studio's clean filler words setting (on unless the user turned it off).",+ ),transcript_words: z.array(z.object({@@ -595,7 +631,7 @@ export function createServer(): McpServer {let usedWebServer = false;let finalResult = "";try {- const webRes = await fetch("http://localhost:3847/api/mcp/export", {+ const webRes = await fetch(`${webServerUrl}/api/mcp/export`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -616,6 +652,9 @@ export function createServer(): McpServer {transcript_words: params.transcript_words,logo_path: params.logo_path || null,outro_path: params.outro_path || null,+ ...(params.clean_fillers !== undefined && {+ clean_fillers: params.clean_fillers,+ }),keep_caption_overlay: params.keep_caption_overlay === true,}),});@@ -625,12 +664,16 @@ export function createServer(): McpServer {// Poll the job until completion (1 hour max)const deadline = Date.now() + 3600_000;+ let lostJob = false;while (Date.now() < deadline) {await new Promise((r) => setTimeout(r, 2000));const pollRes = await fetch(- `http://localhost:3847/api/job/${jobId}`,+ `${webServerUrl}/api/job/${jobId}`,);- if (!pollRes.ok) break;+ if (!pollRes.ok) {+ lostJob = true;+ break;+ }const job = (await pollRes.json()) as WebJob;if (job.status === "done") {usedWebServer = true;@@ -642,18 +685,15 @@ export function createServer(): McpServer {}}if (!usedWebServer) {- throw new Error("Clip creation timed out after 1 hour");+ throw new Error(+ lostJob+ ? `Lost track of render job ${jobId}: the web server stopped reporting it (it may have restarted). Check list_outputs for results.`+ : "Clip creation timed out after 1 hour",+ );}}} catch (webErr: unknown) {- const webMsg =- webErr instanceof Error ? webErr.message : String(webErr);- if (- !webMsg.includes("ECONNREFUSED") &&- !webMsg.includes("fetch failed")- ) {- // Unexpected error — still try direct fallback- }+ if (!studioUnreachable(webErr, "create_clip")) throw webErr;}if (!usedWebServer) {@@ -686,7 +726,7 @@ export function createServer(): McpServer {logoPath: (params.logo_path as string) || recipeSettings.logoPath || null,outroPath: (params.outro_path as string) || recipeSettings.outroPath || null,introPath: recipeSettings.introPath || null,- cleanFillers: true,+ cleanFillers: params.clean_fillers ?? recipeSettings.cleanFillers ?? true,keepSegments: keepSegments ?? undefined,});@@ -746,6 +786,12 @@ export function createServer(): McpServer {.describe("Keep ProRes 4444 alpha caption overlays for DaVinci Resolve export (batch-level default; per-clip overrides).",),+ clean_fillers: z+ .boolean()+ .optional()+ .describe(+ "Remove filler words (um, uh, hmm) from captions and compress long silences. Defaults to the studio's clean filler words setting (on unless the user turned it off).",+ ),transcript_words: z.array(z.object({@@ -843,13 +889,17 @@ export function createServer(): McpServer {let usedWebServer = false;let finalResult: string = "";try {- const webRes = await fetch("http://localhost:3847/api/mcp/export", {+ const webRes = await fetch(`${webServerUrl}/api/mcp/export`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({video_path: resolvedVideoPath,clips: resolvedClips,transcript_words: resolvedTranscriptWords,+ ...(params.clean_fillers !== undefined && {+ clean_fillers: params.clean_fillers,+ }),+ keep_caption_overlay: params.keep_caption_overlay === true,}),});if (webRes.ok) {@@ -876,12 +926,16 @@ export function createServer(): McpServer {// Sync path — poll internally until completion (1 hour max)const deadline = Date.now() + 3600_000;+ let lostJob = false;while (Date.now() < deadline) {await new Promise((r) => setTimeout(r, 2000));const pollRes = await fetch(- `http://localhost:3847/api/job/${jobId}`,+ `${webServerUrl}/api/job/${jobId}`,);- if (!pollRes.ok) break;+ if (!pollRes.ok) {+ lostJob = true;+ break;+ }const job = (await pollRes.json()) as WebJob;if (job.status === "done") {usedWebServer = true;@@ -893,49 +947,26 @@ export function createServer(): McpServer {}}if (!usedWebServer) {- throw new Error("Batch clip creation timed out after 1 hour");+ throw new Error(+ lostJob+ ? `Lost track of batch job ${jobId}: the web server stopped reporting it (it may have restarted). Check list_outputs for partial results.`+ : "Batch clip creation timed out after 1 hour",+ );}}} catch (webErr: unknown) {- const webMsg =- webErr instanceof Error ? webErr.message : String(webErr);- if (- !webMsg.includes("ECONNREFUSED") &&- !webMsg.includes("fetch failed")- ) {- // Unexpected error — still try fallback- }+ if (!studioUnreachable(webErr, "batch_create_clips")) throw webErr;}if (!usedWebServer) {await uiPing({ phase: "exporting" });- const batchParams = {+ // handleBatchClips records history + recipes itself.+ finalResult = await handleBatchClips({...params,video_path: resolvedVideoPath || params.video_path,clips: resolvedClips || params.clips,transcript_words: resolvedTranscriptWords || params.transcript_words,- };- finalResult = await handleBatchClips(batchParams);- const parsed = JSON.parse(finalResult) as BatchClipsResult;- const uiState = await readUIState().catch(() => null);- const settings = uiState?.settings ?? {};-- const recorded = await history.recordBatchResults(parsed.results, {- sourceVideo: (batchParams.video_path as string) || "",- transcriptWords: batchParams.transcript_words as WordTimestamp[] | undefined,- });- await history.persistBatchRecipes(parsed.results, recorded, {- transcriptWords: batchParams.transcript_words as WordTimestamp[] | undefined,- clipSpecs: (batchParams.clips || []) as Array<{- start_second: number;- end_second: number;- keep_segments?: Array<{ start: number; end: number }>;- }>,- logoPath: settings.logoPath || null,- outroPath: settings.outroPath || null,- introPath: settings.introPath || null,- cleanFillers: true,});await uiPing({ phase: "done" });@@ -1345,7 +1376,7 @@ export function createServer(): McpServer {},async ({ include_transcript }) => {try {- const res = await fetch("http://localhost:3847/api/ui-state");+ const res = await fetch(`${webServerUrl}/api/ui-state`);if (!res.ok) throw new Error(`HTTP ${res.status}`);const state = (await res.json()) as ServerUIState;@@ -1409,22 +1440,24 @@ export function createServer(): McpServer {} else if (state.transcript) {const segments = state.transcript.segments || [];if (segments.length) {- lines.push("");- lines.push("=== TRANSCRIPT ===");+ const segLines: string[] = [];for (const seg of segments) {const speaker = seg.speaker || "?";const start = Math.floor(seg.start || 0);const end = Math.floor(seg.end || 0);const text = seg.text || "";- lines.push(`[${start}s-${end}s] ${speaker}: ${text}`);+ segLines.push(`[${start}s-${end}s] ${speaker}: ${text}`);}+ lines.push("");+ lines.push("=== TRANSCRIPT ===");+ lines.push(capTranscriptText(segLines.join("\n")));}} else if (state.rawTranscriptText) {lines.push("");lines.push("=== RAW TRANSCRIPT (not yet parsed — use this to analyze and suggest clips) ===",);- lines.push(state.rawTranscriptText);+ lines.push(capTranscriptText(state.rawTranscriptText));}}@@ -1501,111 +1534,64 @@ export function createServer(): McpServer {},async ({ clip_number, clip_id, index, action, updates }) => {try {- // 1. Read current UI state- const res = await fetch("http://localhost:3847/api/ui-state");- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const state = (await res.json()) as ServerUIState;- const suggestions = state.suggestions ?? [];-- if (!suggestions.length) {- return {- content: [- { type: "text" as const, text: "No suggestions in UI state." },- ],- };- }-- // 2. Find target clip (clip_number is 1-based)- let targetIdx = -1;- if (clip_number !== undefined) {- targetIdx = clip_number - 1;- } else if (clip_id) {- targetIdx = suggestions.findIndex((s) => s.clip_id === clip_id);- } else if (index !== undefined) {- targetIdx = index;- }-- if (targetIdx < 0 || targetIdx >= suggestions.length) {+ if (action !== "delete" && Object.keys(updates || {}).length === 0) {return {content: [{type: "text" as const,- text: `Clip not found. Use get_ui_state to see available clips.`,+ text: "No updates provided. Specify at least one field: title, start_second, end_second, reasoning, preview_text, or suggested_caption_style.",},],};}- // --- DELETE ---- if (action === "delete") {- const removed = suggestions[targetIdx];- suggestions.splice(targetIdx, 1);- // Adjust deselectedIndices: remove the deleted index, shift higher ones down- const deselected: number[] = state.deselectedIndices || [];- const adjusted = deselected- .filter((i: number) => i !== targetIdx)- .map((i: number) => (i > targetIdx ? i - 1 : i));-- await fetch("http://localhost:3847/api/ui-state", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ suggestions, deselectedIndices: adjusted }),- });+ // Mutate server-side so concurrent edits aren't lost to a wholesale+ // state replace (clip_number is 1-based).+ const body: Record<string, unknown> = { action, updates };+ if (clip_number !== undefined) body.index = clip_number - 1;+ else if (clip_id) body.clip_id = clip_id;+ else if (index !== undefined) body.index = index;- return {- content: [- {- type: "text" as const,- text: `Deleted clip #${targetIdx + 1}: "${removed.title}". ${suggestions.length} clips remaining.`,- },- ],- };+ const res = await fetch(`${webServerUrl}/api/suggestions/modify`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+ const data = (await res.json()) as ApiError & {+ index: number;+ clip: SuggestedClip;+ total: number;+ };+ if (!res.ok || data.error) {+ if (res.status === 404) {+ return {+ content: [+ {+ type: "text" as const,+ text: "Clip not found. Use get_ui_state to see available clips.",+ },+ ],+ };+ }+ throw new Error(data.error || `HTTP ${res.status}`);}- // --- UPDATE ---- const upd = updates || {};- if (Object.keys(upd).length === 0) {+ if (action === "delete") {return {content: [{type: "text" as const,- text: "No updates provided. Specify at least one field: title, start_second, end_second, reasoning, preview_text, or suggested_caption_style.",+ text: `Deleted clip #${data.index + 1}: "${data.clip.title}". ${data.total} clips remaining.`,},],};}- const clip = suggestions[targetIdx];- if (upd.title !== undefined) clip.title = upd.title;- if (upd.start_second !== undefined)- clip.start_second = upd.start_second;- if (upd.end_second !== undefined) clip.end_second = upd.end_second;- if (upd.reasoning !== undefined) clip.reasoning = upd.reasoning;- if (upd.preview_text !== undefined)- clip.preview_text = upd.preview_text;- if (upd.suggested_caption_style !== undefined)- clip.suggested_caption_style = upd.suggested_caption_style;-- // Recalculate derived fields- clip.duration =- Math.round((clip.end_second - clip.start_second) * 10) / 10;- const fmtTime = (s: number) =>- `${Math.floor(s / 60)}:${Math.floor(s % 60)- .toString()- .padStart(2, "0")}`;- clip.timestamp_display = `${fmtTime(clip.start_second)} → ${fmtTime(clip.end_second)}`;-- suggestions[targetIdx] = clip;- await fetch("http://localhost:3847/api/ui-state", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ suggestions }),- });return {content: [{type: "text" as const,- text: `Updated clip #${targetIdx + 1}: "${clip.title}" (${clip.start_second}s–${clip.end_second}s, ${clip.duration}s)`,+ text: `Updated clip #${data.index + 1}: "${data.clip.title}" (${data.clip.start_second}s–${data.clip.end_second}s, ${data.clip.duration}s)`,},],};@@ -1652,54 +1638,43 @@ export function createServer(): McpServer {},async ({ clip_number, clip_id, index, selected }) => {try {- const res = await fetch("http://localhost:3847/api/ui-state");- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const state = (await res.json()) as ServerUIState;- const suggestions = state.suggestions ?? [];- const deselected: number[] = state.deselectedIndices ?? [];-- // Find target index (clip_number is 1-based)- let targetIdx = -1;- if (clip_number !== undefined) {- targetIdx = clip_number - 1;- } else if (clip_id) {- targetIdx = suggestions.findIndex((s) => s.clip_id === clip_id);- } else if (index !== undefined) {- targetIdx = index;- }-- if (targetIdx < 0 || targetIdx >= suggestions.length) {- return {- content: [- {- type: "text" as const,- text: "Clip not found. Use get_ui_state to see available clips.",- },- ],- };- }-- let updated: number[];- if (selected) {- updated = deselected.filter((i: number) => i !== targetIdx);- } else {- updated = deselected.includes(targetIdx)- ? deselected- : [...deselected, targetIdx];- }-- await fetch("http://localhost:3847/api/ui-state", {+ // Mutate server-side so concurrent edits aren't lost to a wholesale+ // state replace (clip_number is 1-based).+ const body: Record<string, unknown> = { action: "toggle", selected };+ if (clip_number !== undefined) body.index = clip_number - 1;+ else if (clip_id) body.clip_id = clip_id;+ else if (index !== undefined) body.index = index;++ const res = await fetch(`${webServerUrl}/api/suggestions/modify`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ deselectedIndices: updated }),+ body: JSON.stringify(body),});+ const data = (await res.json()) as ApiError & {+ index: number;+ clip: SuggestedClip;+ total: number;+ selectedCount: number;+ };+ if (!res.ok || data.error) {+ if (res.status === 404) {+ return {+ content: [+ {+ type: "text" as const,+ text: "Clip not found. Use get_ui_state to see available clips.",+ },+ ],+ };+ }+ throw new Error(data.error || `HTTP ${res.status}`);+ }- const clip = suggestions[targetIdx];return {content: [{type: "text" as const,- text: `Clip #${targetIdx + 1} "${clip.title}" is now ${selected ? "selected" : "deselected"}. (${suggestions.length - updated.length}/${suggestions.length} selected)`,+ text: `Clip #${data.index + 1} "${data.clip.title}" is now ${selected ? "selected" : "deselected"}. (${data.selectedCount}/${data.total} selected)`,},],};@@ -1780,7 +1755,7 @@ export function createServer(): McpServer {};}- await fetch("http://localhost:3847/api/ui-state", {+ await fetch(`${webServerUrl}/api/ui-state`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ settings }),@@ -1824,7 +1799,7 @@ export function createServer(): McpServer {{},async () => {try {- const res = await fetch("http://localhost:3847/api/outputs");+ const res = await fetch(`${webServerUrl}/api/outputs`);if (!res.ok) throw new Error(`HTTP ${res.status}`);const clips = (await res.json()) as OutputClip[];@@ -1909,7 +1884,7 @@ export function createServer(): McpServer {};}- const res = await fetch("http://localhost:3847/api/presets", {+ const res = await fetch(`${webServerUrl}/api/presets`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ action, name, config }),@@ -1951,7 +1926,7 @@ export function createServer(): McpServer {if (data.config.outro_path)settings.outroPath = data.config.outro_path;if (Object.keys(settings).length) {- await fetch("http://localhost:3847/api/ui-state", {+ await fetch(`${webServerUrl}/api/ui-state`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ settings }),@@ -2021,7 +1996,7 @@ export function createServer(): McpServer {if ((action === "export" || action === "import") && !filePath) {return mcpError(`'path' is required for action '${action}'.`);}- const base = "http://localhost:3847/api/thumbnail-config";+ const base = `${webServerUrl}/api/thumbnail-config`;if (action === "show") {const res = await fetch(base);if (!res.ok) throw new Error(`HTTP ${res.status}`);@@ -2082,7 +2057,7 @@ export function createServer(): McpServer {// If no video_path, read from UI stateif (!vPath || !segs) {- const stateRes = await fetch("http://localhost:3847/api/ui-state");+ const stateRes = await fetch(`${webServerUrl}/api/ui-state`);if (stateRes.ok) {const state = (await stateRes.json()) as ServerUIState;if (!vPath) vPath = state.videoPath || state.filePath;@@ -2118,7 +2093,7 @@ export function createServer(): McpServer {};}- const res = await fetch("http://localhost:3847/api/analyze-energy", {+ const res = await fetch(`${webServerUrl}/api/analyze-energy`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ video_path: vPath, segments: segs }),@@ -2222,7 +2197,7 @@ export function createServer(): McpServer {},async (params) => {try {- const res = await fetch("http://localhost:3847/api/reel", {+ const res = await fetch(`${webServerUrl}/api/reel`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(params),@@ -2273,7 +2248,7 @@ export function createServer(): McpServer {async ({ file_path }) => {try {// Validate via select-file endpoint- const selectRes = await fetch("http://localhost:3847/api/select-file", {+ const selectRes = await fetch(`${webServerUrl}/api/select-file`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ file_path }),@@ -2293,7 +2268,7 @@ export function createServer(): McpServer {const fileInfo = (await selectRes.json()) as FileInfo;// Push to UI state- await fetch("http://localhost:3847/api/ui-state", {+ await fetch(`${webServerUrl}/api/ui-state`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ videoPath: file_path, filePath: file_path }),@@ -2366,7 +2341,7 @@ export function createServer(): McpServer {},async ({ file_path, transcript }) => {try {- const res = await fetch("http://localhost:3847/api/import-transcript", {+ const res = await fetch(`${webServerUrl}/api/import-transcript`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ file_path, transcript }),@@ -2386,7 +2361,7 @@ export function createServer(): McpServer {const result = (await res.json()) as ImportTranscriptResult;// Push transcript to UI state- await fetch("http://localhost:3847/api/ui-state", {+ await fetch(`${webServerUrl}/api/ui-state`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -2449,7 +2424,7 @@ export function createServer(): McpServer {},async ({ file_path, raw_text, total_duration, time_adjust }) => {try {- const res = await fetch("http://localhost:3847/api/parse-transcript", {+ const res = await fetch(`${webServerUrl}/api/parse-transcript`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -2474,7 +2449,7 @@ export function createServer(): McpServer {const result = (await res.json()) as ImportTranscriptResult;// Push parsed transcript to UI state- await fetch("http://localhost:3847/api/ui-state", {+ await fetch(`${webServerUrl}/api/ui-state`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -2575,7 +2550,7 @@ export function createServer(): McpServer {"- Use modify_clip to adjust timing before export","- Use toggle_clip to select/deselect clips","- Use update_settings to change the default caption style or crop strategy",- "- The user can review and adjust clips in the Web UI at http://localhost:3847",+ `- The user can review and adjust clips in the Web UI at ${webServerUrl}`,].join("\n"),},},diff --git a/src/services/clips-history.ts b/src/services/clips-history.tsindex 368cccb..316a43f 100644--- a/src/services/clips-history.ts+++ b/src/services/clips-history.ts@@ -1,8 +1,9 @@-import { readFile, writeFile, mkdir, rm, rename } from "fs/promises";+import { readFile, writeFile, mkdir, rm } from "fs/promises";import { existsSync } from "fs";import { basename, join } from "path";import { v4 as uuidv4 } from "uuid";import { paths } from "../config/paths.js";+import { writeFileAtomic } from "../utils/atomic-file.js";import { sliceTranscript, sliceWords } from "../utils/transcript.js";import { isDemoMode, demoClips } from "../ui/demo-fixtures.js";import type { BatchClipsResult, ClipHistoryEntry, Format, WordTimestamp } from "../models/index.js";@@ -60,16 +61,7 @@ export class ClipsHistory {private async save(entries: ClipHistoryEntry[]): Promise<void> {if (isDemoMode()) return; // demo fixtures are read-only; never persist to clips.jsonawait this.ensureDir();- // Write to a temp file and atomically rename so a crash or a concurrent- // reader never sees a half-written clips.json.- const tmp = `${this.historyPath}.${process.pid}.${uuidv4().slice(0, 8)}.tmp`;- try {- await writeFile(tmp, JSON.stringify(entries, null, 2), "utf-8");- await rename(tmp, this.historyPath);- } catch (err) {- await rm(tmp, { force: true }).catch(() => {});- throw err;- }+ await writeFileAtomic(this.historyPath, JSON.stringify(entries, null, 2));}// Run load → mutate → save as one critical section, queued behind anydiff --git a/src/services/knowledge-base.test.ts b/src/services/knowledge-base.test.tsindex 2350243..760d973 100644--- a/src/services/knowledge-base.test.ts+++ b/src/services/knowledge-base.test.ts@@ -7,7 +7,7 @@ const tmp = mkdtempSync(join(tmpdir(), "podcli-kb-test-"));process.env.PODCLI_HOME = tmp;process.env.PODCLI_DATA = tmp;-const { KnowledgeBase } = await import("./knowledge-base.js");+const { KnowledgeBase, isFilledIn } = await import("./knowledge-base.js");describe("KnowledgeBase", () => {let kb: InstanceType<typeof KnowledgeBase>;@@ -18,11 +18,49 @@ describe("KnowledgeBase", () => {kb = new KnowledgeBase();});- it("ensureDir creates the directory and seeds a README", async () => {+ it("ensureDir creates an empty directory", async () => {rmSync(join(tmp, "knowledge"), { recursive: true, force: true });await kb.ensureDir();- expect(existsSync(join(tmp, "knowledge", "README.md"))).toBe(true);- expect(readFileSync(join(tmp, "knowledge", "README.md"), "utf-8")).toMatch(/Knowledge Base/);+ expect(existsSync(join(tmp, "knowledge"))).toBe(true);+ expect(await kb.listFiles()).toEqual([]);+ });++ it("initFromTemplates copies the numbered templates and keeps existing files", async () => {+ const first = await kb.initFromTemplates();+ expect(first.created).toContain("01-brand-identity.md");+ expect(first.created).toContain("02-voice-and-tone.md");+ expect(first.kept).toEqual([]);+ expect(readFileSync(join(tmp, "knowledge", "01-brand-identity.md"), "utf-8")).toContain("[Show name]");++ await kb.writeFile("01-brand-identity.md", "# Brand identity\nMine, edited");+ const second = await kb.initFromTemplates();+ expect(second.created).toEqual([]);+ expect(second.kept).toEqual(first.created);+ expect(readFileSync(join(tmp, "knowledge", "01-brand-identity.md"), "utf-8")).toContain("Mine, edited");+ });++ it("status reports which templates are present and which are filled in", async () => {+ const empty = await kb.status();+ expect(empty.templates.length).toBeGreaterThan(0);+ expect(empty.present).toEqual([]);+ expect(empty.missing).toEqual(empty.templates);++ await kb.initFromTemplates();+ const untouched = await kb.status();+ expect(untouched.present).toEqual(untouched.templates);+ expect(untouched.filled).toEqual([]);++ await kb.writeFile("01-brand-identity.md", "# Brand identity\n\n- Name: Deep Dive\n- Audience: founders");+ const edited = await kb.status();+ expect(edited.filled).toEqual(["01-brand-identity.md"]);+ });++ it("isFilledIn treats a mostly-bracketed file as a template", () => {+ const template = "# Voice\n\n- Tone: [tone]\n- Banned: [words]\n- Hook: [hook]\n- Close: [close]";+ expect(isFilledIn(template, template)).toBe(false);+ expect(isFilledIn("# Voice\n\n- Tone: [tone]\n- Banned: hype\n- Hook: [hook]\n- Close: [close]", template)).toBe(false);+ expect(isFilledIn("# Voice\n\n- Tone: blunt\n- Banned: hype\n- Hook: cold open\n- Close: hard cut", template)).toBe(true);+ expect(isFilledIn("", template)).toBe(false);});it("writeFile auto-appends .md extension if missing", async () => {@@ -60,8 +98,7 @@ describe("KnowledgeBase", () => {});it("readAll concatenates all files except README", async () => {- // ensureDir seeds README- await kb.ensureDir();+ await kb.writeFile("README.md", "# ignore me");await kb.writeFile("one.md", "first");await kb.writeFile("two.md", "second");const all = await kb.readAll();@@ -72,7 +109,7 @@ describe("KnowledgeBase", () => {expect(all).not.toContain("README");});- it("readAll returns empty string when only README exists", async () => {+ it("readAll returns empty string when the directory is empty", async () => {await kb.ensureDir();expect(await kb.readAll()).toBe("");});diff --git a/src/services/knowledge-base.ts b/src/services/knowledge-base.tsindex 1a56920..5d6c00d 100644--- a/src/services/knowledge-base.ts+++ b/src/services/knowledge-base.ts@@ -1,33 +1,91 @@-import { readFile, writeFile, readdir, stat, unlink, mkdir } from "fs/promises";+import { readFile, writeFile, readdir, stat, unlink, mkdir, copyFile } from "fs/promises";import { existsSync } from "fs";import { join } from "path";import { paths } from "../config/paths.js";import type { KnowledgeFile } from "../models/index.js";-const DEFAULT_README = `# podcli Knowledge Base+const templatesDir = join(paths.backendDir, "templates", "knowledge");-Add \`.md\` files here to give the AI context when creating clips.+// Template blanks look like [Show name]; a markdown link ([text](url)) is not one.+const PLACEHOLDER = /\[[^\]\n]{1,80}\](?!\()/g;-## Suggested files+function placeholders(text: string): number {+ return text.match(PLACEHOLDER)?.length ?? 0;+}-- \`podcast.md\` — Show name, description, format, episode structure-- \`hosts.md\` — Host names, speaking styles, roles-- \`style.md\` — Preferred caption style, logo, crop strategy, colors-- \`audience.md\` — Target audience, platform preferences (TikTok vs Reels vs Shorts)-- \`avoid.md\` — Topics, segments, or time ranges to skip+export function isFilledIn(content: string, template: string): boolean {+ const body = content.trim();+ if (!body || body === template.trim()) return false;+ return placeholders(body) <= placeholders(template) * 0.3;+}-The MCP server reads all files here before processing requests.-`;+export interface KnowledgeStatus {+ templates: string[];+ present: string[];+ filled: string[];+ missing: string[];+}export class KnowledgeBase {private dir = paths.knowledge;async ensureDir() {- if (!existsSync(this.dir)) {- await mkdir(this.dir, { recursive: true });- // Write default README- await writeFile(join(this.dir, "README.md"), DEFAULT_README, "utf-8");+ await mkdir(this.dir, { recursive: true });+ }++ private async loadTemplates(): Promise<Map<string, string>> {+ const templates = new Map<string, string>();+ let names: string[];+ try {+ names = (await readdir(templatesDir)).filter((f) => f.endsWith(".md")).sort();+ } catch {+ return templates;+ }+ for (const name of names) {+ templates.set(name, await readFile(join(templatesDir, name), "utf-8"));+ }+ return templates;+ }++ /** Copy the starter templates in, never overwriting a file the user already has. */+ async initFromTemplates(): Promise<{ created: string[]; kept: string[] }> {+ const templates = await this.loadTemplates();+ if (templates.size === 0) {+ throw new Error(`No knowledge templates found at ${templatesDir}`);+ }+ await this.ensureDir();++ const created: string[] = [];+ const kept: string[] = [];+ for (const name of templates.keys()) {+ const target = join(this.dir, name);+ if (existsSync(target)) {+ kept.push(name);+ continue;+ }+ await copyFile(join(templatesDir, name), target);+ created.push(name);+ }+ return { created, kept };+ }++ async status(): Promise<KnowledgeStatus> {+ const templates = await this.loadTemplates();+ const byName = new Map((await this.listFiles()).map((f) => [f.filename, f.content]));++ const present: string[] = [];+ const filled: string[] = [];+ const missing: string[] = [];+ for (const [name, template] of templates) {+ const content = byName.get(name);+ if (content === undefined) {+ missing.push(name);+ continue;+ }+ present.push(name);+ if (isFilledIn(content, template)) filled.push(name);}+ return { templates: [...templates.keys()], present, filled, missing };}async listFiles(): Promise<KnowledgeFile[]> {diff --git a/src/services/python-executor.test.ts b/src/services/python-executor.test.tsnew file mode 100644index 0000000..56d269e--- /dev/null+++ b/src/services/python-executor.test.ts@@ -0,0 +1,110 @@+import { EventEmitter } from "events";+import type { ChildProcess } from "child_process";+import { describe, it, expect, vi, afterEach } from "vitest";+import { stderrTail, terminateProcessTree } from "./python-executor.js";++describe("stderrTail", () => {+ it("returns short stderr unchanged", () => {+ expect(stderrTail("boom")).toBe("boom");+ });++ it("keeps the tail of long stderr", () => {+ const noise = "x".repeat(10_000) + "END";+ const tail = stderrTail(noise);+ expect(tail.length).toBe(4000);+ expect(tail.endsWith("END")).toBe(true);+ });++ it("prefers the last traceback block", () => {+ const stderr = [+ "progress line",+ "Traceback (most recent call last):",+ ' File "old.py", line 1',+ "OldError: first failure",+ "retrying...",+ "Traceback (most recent call last):",+ ' File "new.py", line 9',+ "ValueError: actual failure",+ ].join("\n");+ const tail = stderrTail(stderr);+ expect(tail.startsWith("Traceback (most recent call last):")).toBe(true);+ expect(tail).toContain("ValueError: actual failure");+ expect(tail).not.toContain("OldError");+ });++ it("truncates a huge traceback to the tail", () => {+ const stderr = "Traceback (most recent call last):\n" + "y".repeat(9000) + "\nValueError: end";+ const tail = stderrTail(stderr);+ expect(tail.length).toBe(4000);+ expect(tail.endsWith("ValueError: end")).toBe(true);+ });+});++describe("terminateProcessTree", () => {+ const fakeProc = () => {+ const proc = new EventEmitter() as unknown as ChildProcess;+ Object.assign(proc, { pid: 4242, exitCode: null, signalCode: null, kill: vi.fn() });+ return proc;+ };++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("escalates a POSIX process group to SIGKILL", () => {+ vi.useFakeTimers();+ const proc = fakeProc();+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);+ terminateProcessTree(proc, 2000, { platform: "linux" });++ expect(kill).toHaveBeenCalledWith(-4242, "SIGTERM");+ vi.advanceTimersByTime(2000);+ expect(kill).toHaveBeenCalledWith(-4242, "SIGKILL");+ });++ it("cancels POSIX escalation once the process exits", () => {+ vi.useFakeTimers();+ const proc = fakeProc();+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);+ terminateProcessTree(proc, 2000, { platform: "linux" });++ proc.emit("exit", null, "SIGTERM");+ vi.advanceTimersByTime(10_000);++ expect(kill).toHaveBeenCalledTimes(1);+ });++ it("does not signal an already-exited POSIX process group", () => {+ vi.useFakeTimers();+ const proc = fakeProc();+ Object.assign(proc, { exitCode: 0 });+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);+ terminateProcessTree(proc, 2000, { platform: "linux" });++ vi.advanceTimersByTime(10_000);+ expect(kill).not.toHaveBeenCalled();+ });++ it("terminates the full Windows process tree", () => {+ vi.useFakeTimers();+ const proc = fakeProc();+ const taskkillProc = new EventEmitter();+ const spawnProcess = vi.fn().mockReturnValue(taskkillProc);+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);++ terminateProcessTree(proc, 2000, {+ platform: "win32",+ spawnProcess: spawnProcess as never,+ });++ expect(spawnProcess).toHaveBeenCalledWith(+ "taskkill",+ ["/pid", "4242", "/T", "/F"],+ { stdio: "ignore", windowsHide: true }+ );+ expect(proc.kill).not.toHaveBeenCalled();+ expect(kill).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/src/services/python-executor.ts b/src/services/python-executor.tsindex de7e527..0b98753 100644--- a/src/services/python-executor.ts+++ b/src/services/python-executor.ts@@ -7,16 +7,75 @@ type ProgressCallback = (event: ProgressEvent) => void;const isWindows = process.platform === "win32";-function killProcessTree(proc: ChildProcess, signal: NodeJS.Signals): void {- if (proc.pid === undefined) return;+type ProcessTreeOptions = {+ platform?: NodeJS.Platform;+ spawnProcess?: typeof spawn;+};++function hasExited(proc: ChildProcess): boolean {+ return proc.exitCode !== null || proc.signalCode !== null;+}++export function killProcessTree(+ proc: ChildProcess,+ signal: NodeJS.Signals,+ options: ProcessTreeOptions = {}+): void {+ if (proc.pid === undefined || hasExited(proc)) return;+ const platform = options.platform ?? process.platform;try {- // Negative pid kills the whole group — the child is a detached group- // leader, so its ffmpeg/whisper children die with it.- if (isWindows) proc.kill(signal);- else process.kill(-proc.pid, signal);- } catch {- // Already exited.+ if (platform === "win32") {+ const taskkill = (options.spawnProcess ?? spawn)(+ "taskkill",+ ["/pid", String(proc.pid), "/T", "/F"],+ { stdio: "ignore", windowsHide: true }+ );+ taskkill.once("error", () => undefined);+ } else process.kill(-proc.pid, signal);+ } catch {}+}++const KILL_GRACE_MS = 2000;++export function terminateProcessTree(+ proc: ChildProcess,+ graceMs = KILL_GRACE_MS,+ options: ProcessTreeOptions = {}+): void {+ if (hasExited(proc)) return;+ const platform = options.platform ?? process.platform;+ if (platform === "win32") {+ killProcessTree(proc, "SIGKILL", options);+ return;}++ let exited = false;+ let escalation: NodeJS.Timeout | undefined;+ const onExit = (): void => {+ exited = true;+ if (escalation) clearTimeout(escalation);+ };+ proc.once("exit", onExit);+ if (hasExited(proc)) {+ proc.removeListener("exit", onExit);+ return;+ }++ killProcessTree(proc, "SIGTERM", options);+ if (exited || hasExited(proc)) return;++ escalation = setTimeout(() => {+ if (!exited && !hasExited(proc)) killProcessTree(proc, "SIGKILL", options);+ }, graceMs);+ escalation.unref();+}++// Prefer the last traceback block — that's where the actual failure is —+// and keep a tail long enough to include it.+export function stderrTail(stderr: string, maxChars = 4000): string {+ const tb = stderr.lastIndexOf("Traceback (most recent call last):");+ const tail = tb !== -1 ? stderr.slice(tb) : stderr;+ return tail.slice(-maxChars);}function parseResultLine<T>(stdout: string): TaskResult<T> | null {@@ -129,7 +188,7 @@ export class PythonExecutor {reject(new Error(`No parseable output from Python task. Exit code: ${code}. ` +- `Stdout: ${stdout.slice(-300)}. Stderr: ${stderr.slice(-300)}`+ `Stdout: ${stdout.slice(-300)}. Stderr: ${stderrTail(stderr)}`));return;@@ -150,8 +209,7 @@ export class PythonExecutor {} catch {}timer = setTimeout(() => {- killProcessTree(proc, "SIGTERM");- setTimeout(() => killProcessTree(proc, "SIGKILL"), 2000).unref();+ terminateProcessTree(proc);finish(() => reject(new Error(`Task timed out after ${this.timeoutMs / 1000}s`)));}, this.timeoutMs);});diff --git a/src/ui/client/ConfirmDialog.tsx b/src/ui/client/ConfirmDialog.tsxindex 6d7b94d..3f4aa4e 100644--- a/src/ui/client/ConfirmDialog.tsx+++ b/src/ui/client/ConfirmDialog.tsx@@ -1,5 +1,6 @@import React from "react";import { createPortal } from "react-dom";+import { useDialog } from "./useDialog";export default function ConfirmDialog({open,@@ -18,10 +19,19 @@ export default function ConfirmDialog({onConfirm: () => void;onCancel: () => void;}) {+ const dialogRef = useDialog(open, onCancel);if (!open) return null;return createPortal(<div className="modal-overlay" onClick={onCancel}>- <div className="modal-body confirm-dialog" onClick={(e) => e.stopPropagation()}>+ <div+ ref={dialogRef}+ className="modal-body confirm-dialog"+ role="dialog"+ aria-modal="true"+ aria-label={title}+ tabIndex={-1}+ onClick={(e) => e.stopPropagation()}+ ><h3>{title}</h3>{message && <p>{message}</p>}<div className="confirm-actions">diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsxindex 1eb15e3..c4494de 100644--- a/src/ui/client/EpisodeWorkspace.jsx+++ b/src/ui/client/EpisodeWorkspace.jsx@@ -27,10 +27,17 @@ import {import CopyButton from './CopyButton';import AssetPicker from './AssetPicker';import RecentSources from './RecentSources';+import MomentTrim from './MomentTrim';+import { useDialog } from './useDialog';import { PageHeader } from './Page';+import { buildPreviewChunks, activePreviewChunk, selectPreviewWords } from './captionChunks';+import { findClipResult, resultBoundsKey, clipKey, buildEnergyMap, dropEnergy, clampClipIndex } from './lib';const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());+const onKeyActivate = (fn) => (e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); fn(e); }+};const api = async (path, opts = {}) => {const res = await fetch(`/api${path}`, { headers: { 'Content-Type': 'application/json', ...opts.headers }, ...opts });let body = null;@@ -96,7 +103,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());branded: {fontSize: px(100), fontWeight: 700, bottom: PROD_TO_PCT(420),lineHeight: 1.2, uppercase: false,- wordsPerChunk: 3, maxCharsPerChunk: 18, splitLines: true,+ wordsPerChunk: 3, maxCharsPerChunk: 18, splitTail: true, splitLines: true,color: '#fff', activeColor: '#fff',activePill: { background: 'rgba(0,0,0,0.85)', borderRadius: 8, paddingX: 8 },chunkBg: null, gradient: true,@@ -105,7 +112,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());hormozi: {fontSize: px(90), fontWeight: 800, bottom: PROD_TO_PCT(400),lineHeight: 1.2, uppercase: true,- wordsPerChunk: 3, maxCharsPerChunk: 22, splitLines: false,+ wordsPerChunk: 3, absorbTail: 1, splitLines: false,color: '#fff', activeColor: '#ffff00',activePill: null,chunkBg: { background: 'rgba(0,0,0,0.8)', borderRadius: 5, paddingX: 10, paddingY: 5 },@@ -115,7 +122,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());karaoke: {fontSize: px(80), fontWeight: 600, bottom: PROD_TO_PCT(400),lineHeight: 1.25, uppercase: false,- wordsPerChunk: 5, maxCharsPerChunk: 28, splitLines: false,+ wordsPerChunk: 5, absorbTail: 1, splitLines: false,color: 'rgba(255,255,255,0.4)', activeColor: '#fff',activePill: null, chunkBg: null, gradient: false,sample: ['the', 'secret', 'to', 'building', 'something'],@@ -123,31 +130,13 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());subtle: {fontSize: px(64), fontWeight: 400, bottom: PROD_TO_PCT(200),lineHeight: 1.3, uppercase: false,- wordsPerChunk: 6, maxCharsPerChunk: 36, splitLines: false,+ wordsPerChunk: 6, absorbTail: 2, splitLines: false,color: 'rgba(255,255,255,0.95)', activeColor: 'rgba(255,255,255,0.95)',activePill: null, chunkBg: null, gradient: false,sample: ['the', 'secret', 'to', 'building', 'something', 'people'],},};- function buildPreviewChunks(words, perChunk, maxChars) {- const out = [];- let i = 0;- while (i < words.length) {- let end = i, count = 0;- while (end < words.length && end - i < perChunk) {- const w = words[end];- const next = count === 0 ? w.length : count + 1 + w.length;- if (end > i && maxChars && next > maxChars) break;- count = next; end++;- }- if (end === i) end = i + 1;- if (words.length - end === 1 && end - i > 2) end -= 1;- out.push(words.slice(i, end));- i = end;- }- return out;- }function splitBrandedLines(chunk) {if (chunk.length <= 2) return [chunk, []];return [chunk.slice(0, 2), chunk.slice(2)];@@ -301,58 +290,71 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());return <div style={{ whiteSpace: 'normal' }}>{inner}</div>;}- function LivePhonePreview({ videoUrl, videoRef, captionStyle, activeClip, transcriptWords, logoPath, previewSrc, showTikTokFrame, onToggleFrame }) {+ function LivePhonePreview({ videoUrl, videoRef, captionStyle, activeClip, transcriptWords, logoPath, showTikTokFrame, onToggleFrame, clipEnded, onReplay }) {const cfg = STYLE_CONFIGS[captionStyle] || STYLE_CONFIGS.branded;const [logoBroken, setLogoBroken] = useState(false);useEffect(() => { setLogoBroken(false); }, [logoPath]);- // Pull all transcribed words from the active clip (or first N from the- // whole transcript). The chunker decides how many show at once.const sourcePool = useMemo(() => {- if (!transcriptWords || !transcriptWords.length) return null;- let pool = transcriptWords;- if (activeClip) {- pool = transcriptWords.filter(w =>- w.end > activeClip.start_second && w.start < activeClip.end_second- );- }- if (!pool.length) return null;- const out = pool.slice(0, 80).map(w => (w.word || w.text || '').trim()).filter(Boolean);- return out.length >= 2 ? out : null;+ const words = selectPreviewWords(transcriptWords, activeClip);+ return words.length >= 2 ? words : null;}, [activeClip, transcriptWords]);const usingSample = !sourcePool;- const poolWords = sourcePool || cfg.sample;+ const poolWords = useMemo(+ () => sourcePool || cfg.sample.map(text => ({ text, start: 0, end: 0 })),+ [sourcePool, cfg.sample]+ );- // Chunk the same way the Remotion renderer does. The active chunk- // is what appears on screen; the active word inside it gets the- // pill / accent color.const chunks = useMemo(- () => buildPreviewChunks(poolWords, cfg.wordsPerChunk, cfg.maxCharsPerChunk),- [poolWords, cfg.wordsPerChunk, cfg.maxCharsPerChunk]+ () => buildPreviewChunks(poolWords, cfg, activeClip?.end_second),+ [poolWords, cfg, activeClip]);- const [cursor, setCursor] = useState(0); // global word index+ // Real timings drive the captions off the video clock, the way the renderer+ // does. Sample words carry no timings, so they cycle on an interval instead.+ const timed = !usingSample && !!videoUrl;+ const [cursor, setCursor] = useState(0); // sample mode: global word index+ const [clock, setClock] = useState(0);useEffect(() => {setCursor(0);+ setClock(0);if (poolWords.length <= 1) return;+ if (timed) {+ let raf;+ const step = () => {+ const v = videoRef?.current;+ if (v) setClock(v.currentTime);+ raf = requestAnimationFrame(step);+ };+ raf = requestAnimationFrame(step);+ return () => cancelAnimationFrame(raf);+ }const tick = captionStyle === 'karaoke' ? 320 : 420;const iv = setInterval(() => setCursor(i => (i + 1) % poolWords.length), tick);return () => clearInterval(iv);- }, [captionStyle, poolWords.length, poolWords[0]]);-- // Find which chunk the cursor is currently in, and which word within it.- let activeChunkIdx = 0, activeWordInChunk = 0, consumed = 0;- for (let ci = 0; ci < chunks.length; ci++) {- const len = chunks[ci].length;- if (cursor < consumed + len) {- activeChunkIdx = ci;- activeWordInChunk = cursor - consumed;- break;+ }, [captionStyle, poolWords, timed]);++ let activeChunk = null, activeWordInChunk = 0;+ if (timed) {+ activeChunk = activePreviewChunk(chunks, clock) || null;+ if (activeChunk) {+ for (let k = 0; k < activeChunk.words.length; k++) {+ if (activeChunk.words[k].start <= clock) activeWordInChunk = k;+ else break;+ }+ }+ } else {+ let consumed = 0;+ for (const chunk of chunks) {+ if (cursor < consumed + chunk.words.length) {+ activeChunk = chunk;+ activeWordInChunk = cursor - consumed;+ break;+ }+ consumed += chunk.words.length;}- consumed += len;}- const activeChunk = chunks[activeChunkIdx] || [];return (<>@@ -360,8 +362,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());<div className="phone-notch" />{videoUrl ? (<video key={videoUrl} ref={videoRef} src={videoUrl}- muted playsInline preload="auto"- className={previewSrc ? '' : ''} />+ muted playsInline preload="auto" />) : (<div className="phone-empty"><div style={{ opacity: 0.4, display: 'flex' }}><Play size={22} /></div>@@ -369,9 +370,22 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());</div>)}{videoUrl && cfg.gradient && <div className="phone-gradient" />}+ {videoUrl && clipEnded && (+ <button onClick={onReplay} aria-label="Replay clip"+ style={{+ position: 'absolute', inset: 0, margin: 'auto', width: 48, height: 48,+ borderRadius: '50%', background: 'rgba(0,0,0,0.65)',+ border: '1px solid rgba(255,255,255,0.35)', color: '#fff',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ cursor: 'pointer', zIndex: 6,+ }}>+ <RotateCcw size={18} />+ </button>+ )}{videoUrl && captionStyle === 'branded' && logoPath && !logoBroken && (<div className="phone-logo"><img src={`/api/stream-source?path=${encodeURIComponent(logoPath)}`}+ alt="Logo"onError={() => setLogoBroken(true)}style={{ width: '100%', height: '100%', objectFit: 'contain' }} /></div>@@ -384,7 +398,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());fontFamily: "'DM Sans', 'Inter', Arial, sans-serif",}}><PhoneCaptionBody- chunk={activeChunk}+ chunk={activeChunk ? activeChunk.words.map(w => w.text) : null}activeWordInChunk={activeWordInChunk}cfg={cfg}/>@@ -471,7 +485,10 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());return (<div className="mcp-hints">- <div className="mcp-hints-header" style={{ cursor: 'pointer' }} onClick={() => setCollapsed(!collapsed)}>+ <div className="mcp-hints-header" style={{ cursor: 'pointer' }}+ role="button" tabIndex={0} aria-expanded={!collapsed}+ onClick={() => setCollapsed(!collapsed)}+ onKeyDown={onKeyActivate(() => setCollapsed(v => !v))}><div className="mcp-hints-icon">AI</div><div className="mcp-hints-title">MCP prompts</div><div className="mcp-hints-subtitle">@@ -577,9 +594,29 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());// Clip editingconst [editingClip, setEditingClip] = useState(null); // indexconst [editForm, setEditForm] = useState({ title: '', start: 0, end: 0 });+ const [editDuration, setEditDuration] = useState(0);+ const editDialogRef = useDialog(editingClip !== null, () => setEditingClip(null));+ const previewDialogRef = useDialog(!!previewFile, () => setPreviewFile(null));++ // Transcript export menu+ const [exportMenuOpen, setExportMenuOpen] = useState(false);+ const exportMenuRef = useRef(null);+ useEffect(() => {+ if (!exportMenuOpen) return;+ const onDown = (e) => {+ if (exportMenuRef.current && !exportMenuRef.current.contains(e.target)) setExportMenuOpen(false);+ };+ const onKey = (e) => { if (e.key === 'Escape') setExportMenuOpen(false); };+ document.addEventListener('mousedown', onDown);+ document.addEventListener('keydown', onKey);+ return () => {+ document.removeEventListener('mousedown', onDown);+ document.removeEventListener('keydown', onKey);+ };+ }, [exportMenuOpen]);// Energy analysis- const [energyData, setEnergyData] = useState({}); // clip_id → { peak, avg, level }+ const [energyData, setEnergyData] = useState({}); // clipKey(clip) → { score, level }const [analyzingEnergy, setAnalyzingEnergy] = useState(false);// Auto-transcribe + cache@@ -666,26 +703,36 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());};// Clip editing- const openClipEdit = (idx, e) => {- e.stopPropagation();+ const openClipEdit = (idx) => {const clip = suggestions[idx];+ if (!clip) return;setEditingClip(idx);setEditForm({ title: clip.title, start: clip.start_second, end: clip.end_second });};+ const clampEditTime = (v) => {+ const n = Number.isFinite(v) ? Math.max(0, v) : 0;+ return editDuration ? Math.min(n, editDuration) : n;+ };+const saveClipEdit = () => {- if (editingClip === null) return;+ if (editingClip === null || editForm.end <= editForm.start) return;+ const edited = suggestions[editingClip];+ const reTimed = edited && (edited.start_second !== editForm.start || edited.end_second !== editForm.end);setSuggestions(prev => {const next = [...prev];next[editingClip] = { ...next[editingClip], title: editForm.title, start_second: editForm.start, end_second: editForm.end, duration: Math.round(editForm.end - editForm.start), segments: undefined };return next;});+ // The score was measured over the old range, so it no longer describes this clip.+ if (reTimed) setEnergyData(prev => dropEnergy(prev, edited));setEditingClip(null);};const deleteClipEdit = () => {if (editingClip === null) return;if (!confirm(`Delete clip "${editForm.title}" from this batch?`)) return;+ const removed = suggestions[editingClip];setSuggestions(prev => prev.filter((_, i) => i !== editingClip));setDeselected(prev => {const next = new Set();@@ -695,27 +742,20 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());}return next;});+ if (removed) setEnergyData(prev => dropEnergy(prev, removed));setEditingClip(null);};// Energy analysisconst analyzeEnergy = async () => {setAnalyzingEnergy(true);+ const analyzed = suggestions;try {- const segments = suggestions.map(c => ({ start: c.start_second, end: c.end_second }));+ const segments = analyzed.map(c => ({ start: c.start_second, end: c.end_second }));const vp = file?.file_path || videoPath.trim();const d = await api('/analyze-energy', { method: 'POST', body: JSON.stringify({ video_path: vp, segments }) });// Backend returns { segment_scores: [0-10, ...], peak_times: [...] }- if (d.segment_scores && Array.isArray(d.segment_scores)) {- const map = {};- d.segment_scores.forEach((score, i) => {- if (suggestions[i]) {- const level = score >= 7 ? 'high' : score >= 4 ? 'medium' : 'low';- map[i] = { score: score, level };- }- });- setEnergyData(map);- }+ if (Array.isArray(d.segment_scores)) setEnergyData(buildEnergyMap(d.segment_scores, analyzed));} catch {}finally { setAnalyzingEnergy(false); }};@@ -798,7 +838,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());filePath: file?.file_path || '',suggestions,deselectedIndices: Array.from(deselected),- settings: { captionStyle, cropStrategy, format, logoPath, outroPath, introPath },+ settings: { captionStyle, cropStrategy, format, logoPath, outroPath, introPath, cleanFillers },phase,results,energyData,@@ -807,7 +847,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (key === prevSyncRef.current) return;prevSyncRef.current = key;fetch('/api/ui-state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: key }).catch(() => { });- }, [videoPath, file, suggestions, deselected, captionStyle, cropStrategy, format, logoPath, outroPath, introPath, phase, results, energyData]);+ }, [videoPath, file, suggestions, deselected, captionStyle, cropStrategy, format, logoPath, outroPath, introPath, cleanFillers, phase, results, energyData]);// Sync transcript separately (large payload)const prevTranscriptRef = useRef(null);@@ -829,6 +869,22 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());}}, [transcriptText]);+ const resultFor = useCallback(+ (clip, resultIdx) => findClipResult(results, clip, resultIdx),+ [results],+ );++ const applyClipResult = useCallback((row) => {+ if (!row || typeof row.clip_index !== 'number') return;+ setResults(prev => {+ const cur = prev[row.clip_index];+ if (cur && cur.status === row.status && cur.output_path === row.output_path) return prev;+ const next = [...prev];+ next[row.clip_index] = row;+ return next;+ });+ }, []);+// React to SSE events from MCPconst lastHandledTsRef = useRef(0);useEffect(() => {@@ -837,10 +893,8 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (sseEvent.type === 'state-sync' || sseEvent.type === 'state') {const d = sseEvent.data;- if (d.suggestions) {- setSuggestions(d.suggestions);- setEnergyData(sseEvent.type === 'state' && d.energyData ? d.energyData : {});- }+ if (d.suggestions) setSuggestions(d.suggestions);+ if (d.energyData !== undefined) setEnergyData(d.energyData || {});if (d.deselectedIndices !== undefined) setDeselected(new Set(d.deselectedIndices));else if (d.suggestions && !d.deselectedIndices) setDeselected(new Set());if (d.phase) setPhase(d.phase);@@ -860,6 +914,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (d.settings.logoPath !== undefined) setLogoPath(d.settings.logoPath);if (d.settings.outroPath !== undefined) setOutroPath(d.settings.outroPath);if (d.settings.introPath !== undefined) setIntroPath(d.settings.introPath);+ if (d.settings.cleanFillers !== undefined) setCleanFillers(d.settings.cleanFillers !== false);}// Mark initialized after first state restoration so sync useEffects don't overwrite with defaultsif (sseEvent.type === 'state') {@@ -868,6 +923,8 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());} else if (sseEvent.type === 'export-started') {setBatchJobId(sseEvent.data.jobId);setPhase('exporting');+ } else if (sseEvent.type === 'job-update') {+ if (sseEvent.data.clip_result) applyClipResult(sseEvent.data.clip_result);} else if (sseEvent.type === 'job-complete') {if (phase === 'exporting' || sseEvent.data.result?.results) {setPhase('done');@@ -883,13 +940,22 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());}// phase/transcript are read above; the ts-guard makes re-runs on their// change a no-op, so depending on them just keeps the reads fresh.- }, [sseEvent, phase, transcript]);+ }, [sseEvent, phase, transcript, applyClipResult]);// Preview panel stateconst videoRef = useRef();const [activeClipIdx, setActiveClipIdx] = useState(null);const [previewSrc, setPreviewSrc] = useState(null); // null=source, string=rendered clip filenameconst [settingsFlash, setSettingsFlash] = useState(null);+ const [clipEnded, setClipEnded] = useState(false);++ const activeClip = activeClipIdx !== null ? suggestions[activeClipIdx] : null;++ // An agent can delete a clip out from under the cursor, leaving it on a row+ // that no longer exists — space would then deselect an index nobody owns.+ useEffect(() => {+ setActiveClipIdx(prev => clampClipIndex(prev, suggestions.length));+ }, [suggestions.length]);// Video source URLconst videoUrl = previewSrc@@ -898,18 +964,39 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());? `/api/stream-source?path=${encodeURIComponent(videoPath)}`: null;- // Seek to clip when active clip changes (and showing source)+ // Seek to clip when active clip changes (and showing source), pause at+ // its end boundary so the preview doesn't run into the rest of the episodeuseEffect(() => {+ setClipEnded(false);if (activeClipIdx === null || previewSrc) return;- const clip = suggestions[activeClipIdx];- if (!clip || !videoRef.current) return;+ const v = videoRef.current;+ if (!activeClip || !v) return;const seek = () => {- videoRef.current.currentTime = clip.start_second;- videoRef.current.play().catch(() => { });+ v.currentTime = activeClip.start_second;+ v.play().catch(() => { });};- if (videoRef.current.readyState >= 1) seek();- else videoRef.current.addEventListener('loadedmetadata', seek, { once: true });- }, [activeClipIdx, previewSrc]);+ if (v.readyState >= 1) seek();+ else v.addEventListener('loadedmetadata', seek, { once: true });+ const onTime = () => {+ if (v.currentTime >= activeClip.end_second) {+ v.pause();+ setClipEnded(true);+ }+ };+ v.addEventListener('timeupdate', onTime);+ return () => {+ v.removeEventListener('loadedmetadata', seek);+ v.removeEventListener('timeupdate', onTime);+ };+ }, [activeClipIdx, previewSrc, activeClip?.start_second, activeClip?.end_second]);++ const replayClip = () => {+ const v = videoRef.current;+ if (!v || !activeClip) return;+ v.currentTime = activeClip.start_second;+ setClipEnded(false);+ v.play().catch(() => { });+ };// Flash settings when they changeconst flashSetting = (key) => {@@ -1044,14 +1131,23 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());setBatchJobId(data.job_id);};+ useEffect(() => {+ if (!batchStream) return;+ const rows = Array.isArray(batchStream.clip_results)+ ? batchStream.clip_results+ : batchStream.clip_result ? [batchStream.clip_result] : [];+ rows.forEach(applyClipResult);+ }, [batchStream, applyClipResult]);+useEffect(() => {if (batchStream?.status === 'done') { setPhase('done'); setResults(batchStream.result?.results || []); setBatchJobId(null); }if (batchStream?.status === 'error') { setError('Export failed: ' + batchStream.error); setPhase('review'); setBatchJobId(null); }}, [batchStream?.status]);+ const retryClipRef = useRef(null);const retryClip = async (idx) => {const sc = suggestions.filter((_, i) => !deselected.has(i));- const c = sc[idx]; setRetryIdx(idx); setRetryJobId(null);+ const c = sc[idx]; retryClipRef.current = c; setRetryIdx(idx); setRetryJobId(null);const vp = file?.file_path || videoPath.trim();const data = await api('/create-clip', {method: 'POST', body: JSON.stringify({@@ -1065,14 +1161,67 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());};useEffect(() => {- if (retryStream?.status === 'done') {- setResults(prev => { const n = [...prev]; n[retryIdx] = { ...retryStream.result, status: 'success' }; return n; });- setRetryIdx(null); setRetryJobId(null);- }+ if (retryStream?.status !== 'done') return;+ const c = retryClipRef.current;+ const row = {+ ...retryStream.result,+ status: 'success',+ ...(c && { source_start_second: c.start_second, source_end_second: c.end_second }),+ };+ setResults(prev => {+ const key = resultBoundsKey(row);+ const found = key ? prev.findIndex(r => resultBoundsKey(r) === key) : -1;+ const at = found >= 0 ? found : typeof retryIdx === 'number' ? retryIdx : prev.length;+ const next = [...prev];+ next[at] = row;+ return next;+ });+ setRetryIdx(null); setRetryJobId(null);}, [retryStream?.status]);const toggleClip = (i) => setDeselected(prev => { const n = new Set(prev); n.has(i) ? n.delete(i) : n.add(i); return n; });- const selectedCount = suggestions.length - deselected.size;+ const selectedClips = suggestions.filter((_, i) => !deselected.has(i));+ const selectedCount = selectedClips.length;+ const clipRowRefs = useRef([]);++ // Keyboard shortcuts: j/k move clip selection, space toggles include, e edits+ useEffect(() => {+ const onKey = (e) => {+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ const t = e.target instanceof Element ? e.target : null;+ if (t?.closest('input, textarea, select, [contenteditable="true"]')) return;+ // Reviewing a clip means focusing its row, so the row is the one control+ // these keys must still reach. Anything else that activates on the same+ // key would fire twice.+ const control = t?.closest('button, a, [role="button"], [role="checkbox"], [role="switch"], [role="tab"], [role="menuitem"]');+ if (control && !control.hasAttribute('data-clip-row')) return;+ if (editingClip !== null || previewFile) return;+ if (!suggestions.length) return;+ const key = e.key.toLowerCase();+ if (key === 'j' || key === 'k') {+ e.preventDefault();+ setPreviewSrc(null);+ const cur = activeClipIdx === null ? -1 : activeClipIdx;+ const next = key === 'j'+ ? Math.min(cur + 1, suggestions.length - 1)+ : Math.max(cur - 1, 0);+ setActiveClipIdx(next);+ // Without this the focus ring, the highlight, and what Enter+ // re-activates drift onto different rows.+ clipRowRefs.current[next]?.focus();+ } else if (key === ' ') {+ if (phase !== 'review' || activeClipIdx === null) return;+ e.preventDefault();+ toggleClip(activeClipIdx);+ } else if (key === 'e') {+ if (phase !== 'review' || activeClipIdx === null) return;+ e.preventDefault();+ openClipEdit(activeClipIdx);+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [suggestions, phase, activeClipIdx, editingClip, previewFile]);const buildLocalPrompt = () => {const parts = [];const hasTranscriptReady = transcript || transcriptText.trim();@@ -1165,7 +1314,7 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());if (data.clips && data.clips.length > 0) {// Claude returned suggestions — populate directlyconst mapped = data.clips.map((c, i) => ({- id: `claude-${i}`,+ clip_id: `claude-${i}`,title: c.title,start_second: c.start_second,end_second: c.end_second,@@ -1208,21 +1357,19 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());const isProcessing = phase === 'parsing' || phase === 'suggesting' || phase === 'exporting' || transcribing || downloadingVideo;const sourceIsUrl = isHttpUrl(videoPath);- const selectedClips = suggestions.filter((_, i) => !deselected.has(i));const exportStats = phase === 'done' ? {- total: selectedClips.length,+ total: results.length || selectedClips.length,ok: results.filter(r => r?.status === 'success').length,failed: results.filter(r => r?.status === 'error').length,} : null;- const getExportStatus = (resultIdx) => {- if (phase !== 'exporting' || !batchStream) return null;- const total = selectedClips.length; if (!total) return null;- const pct = batchStream.progress || 0;- const done = Math.floor(pct / (100 / total));- if (resultIdx < done) return 'exported';- if (resultIdx === done && pct < 100) return 'rendering';- return 'pending';+ // Clips render in parallel and report as they finish, so a clip is only+ // exported once its own row has arrived. Anything else is still in the queue.+ const getExportStatus = (clip, resultIdx) => {+ if (phase !== 'exporting') return null;+ const r = resultFor(clip, resultIdx);+ if (r) return r.status === 'error' ? 'failed' : 'exported';+ return batchStream ? 'pending' : null;};const handleVideoDrop = (e) => {@@ -1234,8 +1381,6 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());const handleTranscriptFileSelect = (e) => { const f = e.target.files?.[0]; if (!f) return; setTranscriptFileName(f.name); const reader = new FileReader(); reader.onload = (ev) => setTranscriptText(ev.target.result); reader.readAsText(f); };const preventDef = (e) => e.preventDefault();- const activeClip = activeClipIdx !== null ? suggestions[activeClipIdx] : null;-return (<div className="app"><PageHeader@@ -1336,9 +1481,13 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{/* Transcript */}<div className="section card"><div className="section-label">Transcript</div>- <div className="tabs">- <div className={`tab ${transcriptMode === 'import' ? 'active' : ''}`} onClick={() => setTranscriptMode('import')}>Paste transcript</div>- <div className={`tab ${transcriptMode === 'whisper' ? 'active' : ''}`} onClick={() => setTranscriptMode('whisper')}>Auto</div>+ <div className="tabs" role="tablist" aria-label="Transcript source">+ {[['import', 'Paste transcript'], ['whisper', 'Auto']].map(([mode, label]) => (+ <div key={mode} className={`tab ${transcriptMode === mode ? 'active' : ''}`}+ role="tab" tabIndex={0} aria-selected={transcriptMode === mode}+ onClick={() => setTranscriptMode(mode)}+ onKeyDown={onKeyActivate(() => setTranscriptMode(mode))}>{label}</div>+ ))}</div>{transcriptMode === 'import' && (<div className="fade-in">@@ -1513,7 +1662,9 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{/* Advanced Settings */}<div style={{ marginTop: 14 }}><div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, fontWeight: 700, letterSpacing: '0.8px', color: 'var(--text2)', textTransform: 'uppercase' }}- onClick={() => setAdvancedOpen(!advancedOpen)}>+ role="button" tabIndex={0} aria-expanded={advancedOpen}+ onClick={() => setAdvancedOpen(!advancedOpen)}+ onKeyDown={onKeyActivate(() => setAdvancedOpen(v => !v))}><span style={{ transition: 'transform 0.15s', transform: advancedOpen ? 'rotate(90deg)' : 'rotate(0deg)', display: 'inline-flex' }}><ChevronRight size={12} /></span>Advanced</div>@@ -1548,11 +1699,17 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());</div><div className="toggle-row" style={{ gridColumn: '1 / -1' }}><span className="toggle-label">Clean filler words (um, uh, hmm)</span>- <div className={`toggle ${cleanFillers ? 'on' : ''}`} onClick={() => setCleanFillers(!cleanFillers)} />+ <div className={`toggle ${cleanFillers ? 'on' : ''}`} role="switch" tabIndex={0}+ aria-checked={cleanFillers} aria-label="Clean filler words"+ onClick={() => setCleanFillers(!cleanFillers)}+ onKeyDown={onKeyActivate(() => setCleanFillers(v => !v))} /></div><div className="toggle-row" style={{ gridColumn: '1 / -1', paddingTop: 0 }}><span className="toggle-label">Energy boost (normalize loud moments)</span>- <div className={`toggle ${energyBoost ? 'on' : ''}`} onClick={() => setEnergyBoost(!energyBoost)} />+ <div className={`toggle ${energyBoost ? 'on' : ''}`} role="switch" tabIndex={0}+ aria-checked={energyBoost} aria-label="Energy boost"+ onClick={() => setEnergyBoost(!energyBoost)}+ onKeyDown={onKeyActivate(() => setEnergyBoost(v => !v))} /></div></div>)}@@ -1561,7 +1718,10 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{/* Word Corrections */}<div className="section">- <div className="section-label" style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }} onClick={() => setCorrectionsOpen(!correctionsOpen)}>+ <div className="section-label" style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}+ role="button" tabIndex={0} aria-expanded={correctionsOpen}+ onClick={() => setCorrectionsOpen(!correctionsOpen)}+ onKeyDown={onKeyActivate(() => setCorrectionsOpen(v => !v))}><span style={{ transition: 'transform 0.15s', transform: correctionsOpen ? 'rotate(90deg)' : 'rotate(0deg)', display: 'inline-flex' }}><ChevronRight size={12} /></span>Word Corrections{Object.keys(corrections).length > 0 && (@@ -1686,6 +1846,16 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());: phase === 'review' ? `Clips \u00B7 ${selectedCount} selected` : 'Clips'}</div><div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>+ {phase === 'review' && (+ <>+ <button className="btn btn-ghost btn-sm" onClick={() => setDeselected(new Set())} disabled={deselected.size === 0}>+ Select all+ </button>+ <button className="btn btn-ghost btn-sm" onClick={() => setDeselected(new Set(suggestions.keys()))} disabled={selectedCount === 0}>+ Select none+ </button>+ </>+ )}{phase === 'review' && videoPath && (<button className="btn btn-ghost btn-sm" onClick={analyzeEnergy} disabled={analyzingEnergy || suggestions.length === 0} title="Analyze audio energy levels">{analyzingEnergy ? <><div className="spinner sm" /> Analyzing…</> : <><Activity size={14} /> Energy</>}@@ -1697,18 +1867,21 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());</button>)}{transcript && (phase === 'review' || phase === 'done') && (- <div style={{ position: 'relative' }}>- <button className="btn btn-ghost btn-sm overflow-menu-btn" onClick={e => { const m = e.currentTarget.nextElementSibling; m.style.display = m.style.display === 'block' ? 'none' : 'block'; }} style={{ padding: '6px 10px', fontSize: 14, color: 'var(--text3)', lineHeight: 1 }}>+ <div style={{ position: 'relative' }} ref={exportMenuRef}>+ <button className="btn btn-ghost btn-sm overflow-menu-btn" aria-label="More actions" aria-haspopup="menu" aria-expanded={exportMenuOpen}+ onClick={() => setExportMenuOpen(v => !v)} style={{ padding: '6px 10px', fontSize: 14, color: 'var(--text3)', lineHeight: 1 }}>{'\u22EF'}</button>- <div className="overflow-menu" style={{ display: 'none' }}>- <div className="overflow-menu-label">Export transcript</div>- {['SRT', 'VTT', 'JSON'].map(fmt => (- <button key={fmt} className="overflow-menu-item" onClick={e => { window.open(`/api/export-transcript?format=${fmt.toLowerCase()}`, '_blank'); e.currentTarget.closest('.overflow-menu').style.display = 'none'; }}>- {fmt}- </button>- ))}- </div>+ {exportMenuOpen && (+ <div className="overflow-menu" role="menu">+ <div className="overflow-menu-label">Export transcript</div>+ {['SRT', 'VTT', 'JSON'].map(fmt => (+ <button key={fmt} role="menuitem" className="overflow-menu-item" onClick={() => { window.open(`/api/export-transcript?format=${fmt.toLowerCase()}`, '_blank'); setExportMenuOpen(false); }}>+ {fmt}+ </button>+ ))}+ </div>+ )}</div>)}</div>@@ -1717,26 +1890,36 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{suggestions.map((clip, i) => {const off = deselected.has(i);const resultIdx = [...suggestions.keys()].filter(k => !deselected.has(k)).indexOf(i);- const r = results[resultIdx];+ const r = resultFor(clip, resultIdx);const outputFile = r?.output_path?.split('/').pop();const failed = r?.status === 'error';const isRetryingThis = retryIdx === resultIdx;- const exportStatus = !off ? getExportStatus(resultIdx) : null;+ const exportStatus = !off ? getExportStatus(clip, resultIdx) : null;const isSelected = activeClipIdx === i && !previewSrc;+ const energy = energyData[clipKey(clip)];return (- <div key={i}- className={`clip-item ${off && phase === 'review' ? 'dimmed' : ''} ${exportStatus === 'rendering' ? 'active-clip' : ''} ${phase === 'suggesting' ? 'clip-reveal' : ''} ${isSelected ? 'selected' : ''}`}- onClick={() => onClipClick(i)}>+ <div key={i} data-clip-row+ ref={el => { clipRowRefs.current[i] = el; }}+ className={`clip-item ${off && phase === 'review' ? 'dimmed' : ''} ${phase === 'suggesting' ? 'clip-reveal' : ''} ${isSelected ? 'selected' : ''}`}+ role="button" tabIndex={0} aria-label={`Preview clip: ${clip.title}`}+ onClick={() => onClipClick(i)}+ onFocus={e => { if (e.target === e.currentTarget) onClipClick(i); }}+ onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); onClipClick(i); } }}>{phase === 'review' && (- <div className={`checkbox ${!off ? 'checked' : ''}`} onClick={(e) => { e.stopPropagation(); toggleClip(i); }}>+ <div className={`checkbox ${!off ? 'checked' : ''}`}+ role="checkbox" tabIndex={0} aria-checked={!off} aria-label={`Include ${clip.title} in export`}+ onClick={(e) => { e.stopPropagation(); toggleClip(i); }}+ onKeyDown={onKeyActivate(() => toggleClip(i))}>{!off && <CheckIcon />}</div>)}{phase === 'exporting' && !off && exportStatus && (- <div className={`clip-status ${exportStatus}`}>{exportStatus === 'exported' && <CheckSmall />}</div>+ exportStatus === 'failed'+ ? <div className="status-dot fail"><X size={11} /></div>+ : <div className={`clip-status ${exportStatus}`}>{exportStatus === 'exported' && <CheckSmall />}</div>)}{phase === 'done' && !off && r && (@@ -1747,20 +1930,19 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());<div className="clip-title">{clip.title}</div><div className="clip-meta">{fmt(clip.start_second)} {'\u2192'} {fmt(clip.end_second)} {'\u00B7'} {clip.duration}s- {energyData[i] && (- <span className={`energy-badge ${energyData[i].level}`} title={`Energy: ${energyData[i].score}/10`}>- {energyData[i].level === 'high' ? <Activity size={10} /> : energyData[i].level === 'medium' ? '~' : '○'} {energyData[i].score.toFixed(1)}+ {energy && (+ <span className={`energy-badge ${energy.level}`} title={`Energy: ${energy.score}/10`}>+ {energy.level === 'high' ? <Activity size={10} /> : energy.level === 'medium' ? '~' : '○'} {energy.score.toFixed(1)}</span>)}{r && !failed && <span> {'\u00B7'} {r.file_size_mb}MB</span>}{r && !failed && r.warning && <span className="warn"> {'\u00B7'} {r.warning}</span>}{failed && <span className="err"> {'\u00B7'} {r.error?.slice(0, 60)}</span>}- {exportStatus === 'rendering' && <span style={{ color: 'var(--accent)' }}> {'\u00B7'} rendering{'\u2026'}</span>}</div></div>{phase === 'review' && (- <button className="btn btn-ghost btn-sm clip-edit-btn" onClick={(e) => openClipEdit(i, e)} title="Edit clip"><Pencil size={13} /></button>+ <button className="btn btn-ghost btn-sm clip-edit-btn" onClick={(e) => { e.stopPropagation(); openClipEdit(i); }} title="Edit clip"><Pencil size={13} /></button>)}{phase === 'done' && !off && r && !failed && outputFile && (@@ -1855,7 +2037,9 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{clipHistory.length > 0 && (<div className="section" style={{ marginTop: 16 }}><div className="section-label" style={{ cursor: 'pointer', userSelect: 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}- onClick={() => setHistoryOpen(!historyOpen)}>+ role="button" tabIndex={0} aria-expanded={historyOpen}+ onClick={() => setHistoryOpen(!historyOpen)}+ onKeyDown={onKeyActivate(() => setHistoryOpen(v => !v))}><span>History ({clipHistory.length})</span><span className="hint-xs" style={{ transition: 'transform 0.2s', transform: historyOpen ? 'rotate(180deg)' : 'rotate(0)' }}><ChevronDown size={12} /></span></div>@@ -1868,7 +2052,9 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());const fname = c.output_path?.split('/').pop() || c.title;return (<div key={c.id || i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', background: 'var(--surface)', borderRadius: 'var(--radius-sm)', fontSize: 12, cursor: 'pointer' }}- onClick={() => { const f = c.output_path?.split('/').pop(); if (f) setPreviewSrc(f); }}>+ role="button" tabIndex={0} aria-label={`Preview ${c.title || fname}`}+ onClick={() => { const f = c.output_path?.split('/').pop(); if (f) setPreviewSrc(f); }}+ onKeyDown={onKeyActivate(() => { const f = c.output_path?.split('/').pop(); if (f) setPreviewSrc(f); })}><div style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--green)', flexShrink: 0 }} /><div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.title || fname}</div>@@ -1916,7 +2102,8 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());</div>)}- {/* Style preview mockup — hidden when rendered clip is playing */}+ {/* Style preview mockup — hidden when rendered clip is playing, whose+ captions are already burned in and whose clock is clip-relative */}{!previewSrc && (<LivePhonePreviewvideoUrl={videoUrl}@@ -1925,9 +2112,10 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());activeClip={activeClip}transcriptWords={transcript ? transcript.words : null}logoPath={logoPath}- previewSrc={previewSrc}showTikTokFrame={showTikTokFrame}onToggleFrame={() => setShowTikTokFrame(v => !v)}+ clipEnded={clipEnded}+ onReplay={replayClip}/>)}<SpecRecap@@ -1946,30 +2134,46 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{/* Clip Edit Modal */}{editingClip !== null && suggestions[editingClip] && createPortal(<div className="clip-edit-overlay" onClick={() => setEditingClip(null)}>- <div className="clip-edit-panel" onClick={e => e.stopPropagation()}>+ <div ref={editDialogRef} className="clip-edit-panel" role="dialog" aria-modal="true"+ aria-label={`Edit clip ${editingClip + 1}`} tabIndex={-1} onClick={e => e.stopPropagation()}><h3>Edit clip #{editingClip + 1}</h3><div className="edit-field"><label>Title</label><input type="text" value={editForm.title} onChange={e => setEditForm(f => ({ ...f, title: e.target.value }))}onKeyDown={e => { if (e.key === 'Enter') saveClipEdit(); }} autoFocus /></div>+ {videoPath && !sourceIsUrl && (+ <div className="edit-field">+ <label>Trim</label>+ <MomentTrim+ src={`/api/stream-source?path=${encodeURIComponent(videoPath)}`}+ start={editForm.start}+ end={editForm.end}+ onCommit={(s, e2) => setEditForm(f => ({ ...f, start: clampEditTime(s), end: clampEditTime(e2) }))}+ onDuration={setEditDuration}+ />+ </div>+ )}<div className="edit-field"><label>Time range</label><div className="time-row"><div>- <input type="number" step="0.5" value={editForm.start} onChange={e => setEditForm(f => ({ ...f, start: parseFloat(e.target.value) || 0 }))}- style={{ textAlign: 'center' }} />+ <input type="number" step="0.5" min="0" max={editDuration || undefined} value={editForm.start}+ onChange={e => setEditForm(f => ({ ...f, start: clampEditTime(parseFloat(e.target.value)) }))}+ aria-label="Start time in seconds" style={{ textAlign: 'center' }} /><div className="hint-xs" style={{ textAlign: 'center', marginTop: 2 }}>{fmt(editForm.start)}</div></div><div className="arrow"><ArrowRight size={14} /></div><div>- <input type="number" step="0.5" value={editForm.end} onChange={e => setEditForm(f => ({ ...f, end: parseFloat(e.target.value) || 0 }))}- style={{ textAlign: 'center' }} />+ <input type="number" step="0.5" min="0" max={editDuration || undefined} value={editForm.end}+ onChange={e => setEditForm(f => ({ ...f, end: clampEditTime(parseFloat(e.target.value)) }))}+ aria-label="End time in seconds" style={{ textAlign: 'center' }} /><div className="hint-xs" style={{ textAlign: 'center', marginTop: 2 }}>{fmt(editForm.end)}</div></div></div><div className="hint" style={{ marginTop: 6, textAlign: 'center' }}>Duration: {Math.round(editForm.end - editForm.start)}s+ {editForm.end <= editForm.start && <span style={{ color: 'var(--red)' }}> {'·'} end must be after start</span>}</div></div><div className="clip-edit-actions">@@ -1984,7 +2188,8 @@ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());{/* Modal (mobile fallback) */}{previewFile && createPortal(<div className="modal-overlay" onClick={() => setPreviewFile(null)}>- <div className="modal-body" onClick={e => e.stopPropagation()}>+ <div ref={previewDialogRef} className="modal-body" role="dialog" aria-modal="true"+ aria-label="Clip preview" tabIndex={-1} onClick={e => e.stopPropagation()}><video src={`/api/preview/${previewFile}`} controls autoPlay /><div style={{ textAlign: 'center', marginTop: 12 }}><button className="btn btn-ghost btn-sm" onClick={() => setPreviewFile(null)}>Close</button>diff --git a/src/ui/client/HighlightsPage.tsx b/src/ui/client/HighlightsPage.tsxindex 28428cd..ef4e4d0 100644--- a/src/ui/client/HighlightsPage.tsx+++ b/src/ui/client/HighlightsPage.tsx@@ -4,7 +4,8 @@ import { api, basename, fmt } from "./lib";import { useJob } from "./useJob";import AssetPicker from "./AssetPicker";import RecentSources from "./RecentSources";-import { BackIcon, TrashIcon, PlayIcon, PauseIcon, DownloadIcon } from "./icons";+import MomentTrim from "./MomentTrim";+import { BackIcon, TrashIcon, DownloadIcon } from "./icons";interface Moment {start: number;@@ -60,137 +61,6 @@ function Field({ label, children }: { label: string; children: React.ReactNode });}-function MomentTrim({- src,- moment,- onCommit,- saving,-}: {- src: string;- moment: Moment;- onCommit: (start: number, end: number) => void;- saving: boolean;-}) {- const video = useRef<HTMLVideoElement>(null);- const trackRef = useRef<HTMLDivElement>(null);- const [dur, setDur] = useState(0);- const [cur, setCur] = useState(moment.start);- const [playing, setPlaying] = useState(false);- const [draft, setDraft] = useState<{ start: number; end: number } | null>(null);- const drag = useRef<null | "in" | "out">(null);-- const start = draft?.start ?? moment.start;- const end = draft?.end ?? moment.end;-- const pad = Math.max(8, (moment.end - moment.start) * 0.6);- const winA = Math.max(0, moment.start - pad);- const winB = Math.min(dur || moment.end + pad, moment.end + pad);- const span = Math.max(0.1, winB - winA);- const pct = (t: number) => `${((t - winA) / span) * 100}%`;-- useEffect(() => {- const v = video.current;- if (v) v.currentTime = moment.start;- setCur(moment.start);- }, [moment.start, moment.end, src]);-- const timeAt = (clientX: number) => {- const el = trackRef.current;- if (!el) return winA;- const r = el.getBoundingClientRect();- return winA + Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * span;- };-- const onMove = (e: React.PointerEvent) => {- if (!drag.current) return;- const t = timeAt(e.clientX);- setDraft((d) => {- const base = d ?? { start: moment.start, end: moment.end };- if (drag.current === "in") return { start: Math.min(t, base.end - 0.5), end: base.end };- return { start: base.start, end: Math.max(t, base.start + 0.5) };- });- if (video.current) {- video.current.currentTime = t;- setCur(t);- }- };-- const endDrag = (e: React.PointerEvent) => {- if (!drag.current) return;- e.currentTarget.releasePointerCapture(e.pointerId);- drag.current = null;- if (draft) onCommit(round1(draft.start), round1(draft.end));- };-- const toggle = () => {- const v = video.current;- if (!v) return;- if (v.paused) {- if (v.currentTime < start || v.currentTime >= end) v.currentTime = start;- v.play();- } else v.pause();- };-- const onTime = (e: React.SyntheticEvent<HTMLVideoElement>) => {- const t = e.currentTarget.currentTime;- if (playing && t >= end) {- e.currentTarget.currentTime = start;- setCur(start);- } else setCur(t);- };-- return (- <div>- <div className="clip-player" style={{ marginBottom: 10 }}>- <video- ref={video}- src={src}- playsInline- preload="metadata"- onClick={toggle}- onPlay={() => setPlaying(true)}- onPause={() => setPlaying(false)}- onTimeUpdate={onTime}- onLoadedMetadata={(e) => setDur(e.currentTarget.duration)}- style={{ maxHeight: 360, width: "100%", objectFit: "contain", background: "#000" }}- />- </div>-- <div style={{ display: "flex", alignItems: "center", gap: 12 }}>- <button className="clip-player-btn" onClick={toggle} aria-label={playing ? "Pause" : "Play"}- style={{ flexShrink: 0 }}>- {playing ? <PauseIcon /> : <PlayIcon />}- </button>- <div- ref={trackRef}- className="rf-track"- style={{ flex: 1, marginTop: 0 }}- onPointerMove={onMove}- onPointerUp={endDrag}- >- <div className="rf-region" style={{ left: pct(start), width: `calc(${pct(end)} - ${pct(start)})` }} />- <div className="rf-playhead" style={{ left: pct(cur) }} />- <div- className="rf-handle"- style={{ left: pct(start), background: "var(--accent)" }}- onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); drag.current = "in"; }}- />- <div- className="rf-handle"- style={{ left: pct(end), background: "var(--accent)" }}- onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); drag.current = "out"; }}- />- </div>- <span className="clip-player-time" style={{ minWidth: 118, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>- {saving ? "saving…" : `${fmt(start)}-${fmt(end)} · ${Math.round(end - start)}s`}- </span>- </div>- </div>- );-}--const round1 = (n: number) => Math.round(n * 10) / 10;-function DownloadRow({jobId,url,@@ -570,7 +440,8 @@ export default function HighlightsPage() {<MomentTrimkey={selected}src={streamSrc}- moment={active}+ start={active.start}+ end={active.end}saving={saving}onCommit={(s, e) => commitTrim(selected, s, e)}/>diff --git a/src/ui/client/KnowledgePage.jsx b/src/ui/client/KnowledgePage.jsxindex f0b1f33..05813a4 100644--- a/src/ui/client/KnowledgePage.jsx+++ b/src/ui/client/KnowledgePage.jsx@@ -2,6 +2,9 @@ import React, { useState, useEffect, useCallback } from 'react';import { PageHeader } from "./Page";import { Trash2 } from 'lucide-react';import { api, upload } from './lib';+import CopyButton from './CopyButton';++const BOOTSTRAP_COMMAND = 'podcli bootstrap-knowledge <channel-url>';export default function KnowledgePage() {const [files, setFiles] = useState([]);@@ -12,6 +15,8 @@ export default function KnowledgePage() {const [toast, setToast] = useState(null);const [newName, setNewName] = useState('');const [kbDir, setKbDir] = useState('');+ const [creating, setCreating] = useState(false);+ const [created, setCreated] = useState(null);const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2000); };@@ -67,6 +72,16 @@ export default function KnowledgePage() {} catch (e) { showToast(`Create failed: ${e.message}`); }};+ const createStarterFiles = async () => {+ setCreating(true);+ try {+ const r = await api('/knowledge/init', { method: 'POST' });+ setCreated(r.created || []);+ await loadFiles();+ } catch (e) { showToast(`Create failed: ${e.message}`); }+ finally { setCreating(false); }+ };+const uploadFiles = async (fileList, label) => {const fd = new FormData();for (const f of fileList) {@@ -114,6 +129,12 @@ export default function KnowledgePage() {<input type="file" accept=".md,.txt" multiple onChange={handleFileInput} /></div>+ {created?.length > 0 && (+ <div className="set-note ok" style={{ marginBottom: 16 }}>+ Created {created.length} files. Fill in <strong>01-brand-identity.md</strong> and <strong>02-voice-and-tone.md</strong> first: the clip scorer reads those two on every run.+ </div>+ )}+{realFiles.length > 0 ? (<div className="file-grid">{realFiles.map(f => (@@ -130,8 +151,21 @@ export default function KnowledgePage() {))}</div>) : (- <div className="empty-state">- No knowledge files yet. Drop .md files above or create one below.+ <div className="section card" style={{ marginTop: 16 }}>+ <div className="section-label">Start here</div>+ <div className="meta" style={{ marginBottom: 14 }}>+ podcli reads 14 numbered files when it picks clips and writes titles. Create the starter set, then fill in the [brackets].+ </div>+ <button className="btn btn-primary" onClick={createStarterFiles} disabled={creating}>+ {creating ? <div className="spinner sm" /> : 'Create starter templates'}+ </button>+ <div className="code-block">+ <div className="code-block-head">+ <span>or draft them from a channel you already run</span>+ <CopyButton className="btn btn-ghost btn-sm" style={{ padding: '3px 10px' }} text={BOOTSTRAP_COMMAND} />+ </div>+ <pre>{BOOTSTRAP_COMMAND}</pre>+ </div></div>)}diff --git a/src/ui/client/MomentTrim.tsx b/src/ui/client/MomentTrim.tsxnew file mode 100644index 0000000..3224393--- /dev/null+++ b/src/ui/client/MomentTrim.tsx@@ -0,0 +1,142 @@+import React, { useEffect, useRef, useState } from "react";+import { fmt } from "./lib";+import { PlayIcon, PauseIcon } from "./icons";++const round1 = (n: number) => Math.round(n * 10) / 10;++export default function MomentTrim({+ src,+ start: startProp,+ end: endProp,+ onCommit,+ saving = false,+ onDuration,+}: {+ src: string;+ start: number;+ end: number;+ onCommit: (start: number, end: number) => void;+ saving?: boolean;+ onDuration?: (duration: number) => void;+}) {+ const video = useRef<HTMLVideoElement>(null);+ const trackRef = useRef<HTMLDivElement>(null);+ const [dur, setDur] = useState(0);+ const [cur, setCur] = useState(startProp);+ const [playing, setPlaying] = useState(false);+ const [draft, setDraft] = useState<{ start: number; end: number } | null>(null);+ const drag = useRef<null | "in" | "out">(null);++ const start = draft?.start ?? startProp;+ const end = draft?.end ?? endProp;++ const pad = Math.max(8, (endProp - startProp) * 0.6);+ const winA = Math.max(0, startProp - pad);+ const winB = Math.min(dur || endProp + pad, endProp + pad);+ const span = Math.max(0.1, winB - winA);+ const pct = (t: number) => `${((t - winA) / span) * 100}%`;++ useEffect(() => {+ setDraft(null);+ const v = video.current;+ if (v) v.currentTime = startProp;+ setCur(startProp);+ }, [startProp, endProp, src]);++ const timeAt = (clientX: number) => {+ const el = trackRef.current;+ if (!el) return winA;+ const r = el.getBoundingClientRect();+ return winA + Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * span;+ };++ const onMove = (e: React.PointerEvent) => {+ if (!drag.current) return;+ const t = timeAt(e.clientX);+ setDraft((d) => {+ const base = d ?? { start: startProp, end: endProp };+ if (drag.current === "in") return { start: Math.min(t, base.end - 0.5), end: base.end };+ return { start: base.start, end: Math.max(t, base.start + 0.5) };+ });+ if (video.current) {+ video.current.currentTime = t;+ setCur(t);+ }+ };++ const endDrag = (e: React.PointerEvent) => {+ if (!drag.current) return;+ e.currentTarget.releasePointerCapture(e.pointerId);+ drag.current = null;+ if (draft) onCommit(round1(draft.start), round1(draft.end));+ };++ const toggle = () => {+ const v = video.current;+ if (!v) return;+ if (v.paused) {+ if (v.currentTime < start || v.currentTime >= end) v.currentTime = start;+ v.play();+ } else v.pause();+ };++ const onTime = (e: React.SyntheticEvent<HTMLVideoElement>) => {+ const t = e.currentTarget.currentTime;+ if (playing && t >= end) {+ e.currentTarget.currentTime = start;+ setCur(start);+ } else setCur(t);+ };++ return (+ <div>+ <div className="clip-player" style={{ marginBottom: 10 }}>+ <video+ ref={video}+ src={src}+ playsInline+ preload="metadata"+ onClick={toggle}+ onPlay={() => setPlaying(true)}+ onPause={() => setPlaying(false)}+ onTimeUpdate={onTime}+ onLoadedMetadata={(e) => {+ setDur(e.currentTarget.duration);+ onDuration?.(e.currentTarget.duration);+ }}+ style={{ maxHeight: 360, width: "100%", objectFit: "contain", background: "#000" }}+ />+ </div>++ <div style={{ display: "flex", alignItems: "center", gap: 12 }}>+ <button className="clip-player-btn" onClick={toggle} aria-label={playing ? "Pause" : "Play"}+ style={{ flexShrink: 0 }}>+ {playing ? <PauseIcon /> : <PlayIcon />}+ </button>+ <div+ ref={trackRef}+ className="rf-track"+ style={{ flex: 1, marginTop: 0 }}+ onPointerMove={onMove}+ onPointerUp={endDrag}+ >+ <div className="rf-region" style={{ left: pct(start), width: `calc(${pct(end)} - ${pct(start)})` }} />+ <div className="rf-playhead" style={{ left: pct(cur) }} />+ <div+ className="rf-handle"+ style={{ left: pct(start), background: "var(--accent)" }}+ onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); drag.current = "in"; }}+ />+ <div+ className="rf-handle"+ style={{ left: pct(end), background: "var(--accent)" }}+ onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); drag.current = "out"; }}+ />+ </div>+ <span className="clip-player-time" style={{ minWidth: 118, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>+ {saving ? "saving…" : `${fmt(start)}-${fmt(end)} · ${Math.round(end - start)}s`}+ </span>+ </div>+ </div>+ );+}diff --git a/src/ui/client/SetupChecklist.tsx b/src/ui/client/SetupChecklist.tsxnew file mode 100644index 0000000..f333c8e--- /dev/null+++ b/src/ui/client/SetupChecklist.tsx@@ -0,0 +1,120 @@+import React, { useCallback, useEffect, useState } from "react";+import { Link } from "react-router-dom";+import { Check } from "lucide-react";+import { api } from "./lib";++interface Onboarding {+ knowledge: { total: number; present: number; filled: string[]; missing: string[] };+ assets: { count: number; branding: boolean };+ aiCli: { available: boolean };+ clips: { count: number };+ dismissed: boolean;+}++interface Step {+ title: string;+ desc: string;+ done: boolean;+ action: React.ReactNode;+}++const BRAND_FILES = ["01-brand-identity.md", "02-voice-and-tone.md"];++export default function SetupChecklist() {+ const [state, setState] = useState<Onboarding | null>(null);+ const [dismissed, setDismissed] = useState(false);+ const [creating, setCreating] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const load = useCallback(() => {+ api<Onboarding>("/onboarding")+ .then(setState)+ .catch(() => setState(null));+ }, []);++ useEffect(load, [load]);++ if (!state || state.dismissed || dismissed) return null;++ const createKnowledge = async () => {+ setCreating(true);+ setError(null);+ try {+ await api("/knowledge/init", { method: "POST" });+ load();+ } catch (e) {+ setError(e instanceof Error ? e.message : "Could not create the knowledge base");+ } finally {+ setCreating(false);+ }+ };++ const dismiss = () => {+ setDismissed(true);+ api("/ui-state", {+ method: "POST",+ body: JSON.stringify({ _source: "ui", settings: { onboardingDismissed: true } }),+ }).catch(() => { });+ };++ const steps: Step[] = [+ {+ title: "Create the knowledge base",+ desc: "The files podcli reads before it picks a single clip.",+ done: state.knowledge.total > 0 && state.knowledge.present === state.knowledge.total,+ action: (+ <button className="btn btn-primary btn-sm" onClick={createKnowledge} disabled={creating}>+ {creating ? <div className="spinner sm" /> : "Create starter templates"}+ </button>+ ),+ },+ {+ title: "Fill in brand identity and voice",+ desc: "Who the show is for, and the words it never uses.",+ done: BRAND_FILES.every((f) => state.knowledge.filled.includes(f)),+ action: <Link to="/knowledge" className="btn btn-ghost btn-sm">Open knowledge</Link>,+ },+ {+ title: "Add a logo or outro",+ desc: "Branding that gets stamped onto every clip you render.",+ done: state.assets.branding,+ action: <Link to="/assets" className="btn btn-ghost btn-sm">Open assets</Link>,+ },+ {+ title: "Connect an AI CLI",+ desc: "Clip suggestions run through Claude Code or Codex on your machine.",+ done: state.aiCli.available,+ action: <Link to="/mcp" className="btn btn-ghost btn-sm">Setup guide</Link>,+ },+ ];++ const done = steps.filter((s) => s.done).length;+ if (done === steps.length) return null;++ return (+ <div className="section card setup fade-in">+ <div className="setup-head">+ <div>+ <div className="section-label" style={{ marginBottom: 2 }}>Set up your studio</div>+ <div className="meta">{done} of {steps.length} done</div>+ </div>+ <button className="btn btn-ghost btn-sm" onClick={dismiss}>Dismiss</button>+ </div>++ <ul className="setup-steps">+ {steps.map((s) => (+ <li key={s.title} className={`setup-step${s.done ? " done" : ""}`}>+ <span className="setup-mark">{s.done && <Check size={12} strokeWidth={3} />}</span>+ <div className="setup-body">+ <div className="setup-title">{s.title}</div>+ <div className="setup-desc">{s.desc}</div>+ </div>+ {!s.done && <div className="setup-action">{s.action}</div>}+ </li>+ ))}+ </ul>++ {error && <div className="set-note err">{error}</div>}+ </div>+ );+}diff --git a/src/ui/client/StudioHome.tsx b/src/ui/client/StudioHome.tsxindex 526f0eb..ae68924 100644--- a/src/ui/client/StudioHome.tsx+++ b/src/ui/client/StudioHome.tsx@@ -3,6 +3,7 @@ import { PageHeader } from "./Page";import { Link } from "react-router-dom";import { api, fmt, timeAgo, basename } from "./lib";import { TrashIcon, PlayIcon } from "./icons";+import SetupChecklist from "./SetupChecklist";interface Clip {id: string;@@ -87,6 +88,8 @@ export default function StudioHome() {actions={<Link to="/episode" className="btn btn-primary btn-sm" style={{ textDecoration: "none" }}>+ New episode</Link>}/>+ <SetupChecklist />+{exporting > 0 && (<div className="set-note ok" style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}><div className="spinner sm" /> Exporting {exporting} clip{exporting > 1 ? "s" : ""}. They appear here as each finishes.diff --git a/src/ui/client/captionChunks.test.ts b/src/ui/client/captionChunks.test.tsnew file mode 100644index 0000000..da3d788--- /dev/null+++ b/src/ui/client/captionChunks.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";+import {+ activePreviewChunk,+ buildPreviewChunks,+ selectPreviewWords,+ type PreviewWord,+} from "./captionChunks";+import { buildChunks } from "../../../remotion/src/chunks";+import type { Word } from "../../../remotion/src/types";++const words: PreviewWord[] = [+ { text: "the", start: 0, end: 0.2, speaker: "A" },+ { text: "secret", start: 0.2, end: 0.6, speaker: "A" },+ { text: "to", start: 0.6, end: 0.7, speaker: "A" },+ { text: "growth.", start: 0.7, end: 1.2, speaker: "A" },+ { text: "is", start: 1.3, end: 1.5, speaker: "A" },+ { text: "boring", start: 1.5, end: 1.9, speaker: "A" },+ { text: "work", start: 1.9, end: 2.3, speaker: "A" },+ { text: "really?", start: 4.0, end: 4.4, speaker: "B" },+ { text: "yes", start: 4.5, end: 4.8, speaker: "B" },+];++const asRendererWords = (ws: PreviewWord[]): Word[] =>+ ws.map((w) => ({ word: w.text, start: w.start, end: w.end, speaker: w.speaker ?? null })) as Word[];++const shapes = (chunks: { words: { text?: string; word?: string }[] }[]) =>+ chunks.map((c) => c.words.map((w) => w.text ?? w.word));++describe("buildPreviewChunks", () => {+ // The phone preview exists to show what the MP4 will look like; if the two+ // chunkers disagree, it is showing a different video.+ it("groups and holds exactly like the renderer", () => {+ for (const cfg of [+ { wordsPerChunk: 3, maxCharsPerChunk: 18, splitTail: true },+ { wordsPerChunk: 3, absorbTail: 1 },+ { wordsPerChunk: 5, absorbTail: 1 },+ { wordsPerChunk: 6, absorbTail: 2 },+ ]) {+ const preview = buildPreviewChunks(words, cfg, 6);+ const rendered = buildChunks(asRendererWords(words), {+ perChunk: cfg.wordsPerChunk,+ maxChars: cfg.maxCharsPerChunk,+ absorbTail: cfg.absorbTail,+ splitTail: cfg.splitTail,+ clipEnd: 6,+ });+ expect(shapes(preview)).toEqual(shapes(rendered));+ expect(preview.map((c) => c.displayEnd)).toEqual(rendered.map((c) => c.displayEnd));+ }+ });++ it("breaks on terminal punctuation, speaker change and long gaps", () => {+ const chunks = buildPreviewChunks(words, { wordsPerChunk: 6, absorbTail: 2 });+ expect(shapes(chunks)).toEqual([+ ["the", "secret", "to", "growth."],+ ["is", "boring", "work"],+ ["really?"],+ ["yes"],+ ]);+ });++ it("holds a chunk through a short pause but not through a long one", () => {+ const chunks = buildPreviewChunks(words, { wordsPerChunk: 6, absorbTail: 2 });+ // 0.1s gap to the next chunk: held all the way to it.+ expect(chunks[0].displayEnd).toBeCloseTo(1.3);+ // 1.7s gap: held for the 0.4s fill, then the caption clears.+ expect(chunks[1].displayEnd).toBeCloseTo(2.7);+ expect(activePreviewChunk(chunks, 3.5)).toBeUndefined();+ });++ it("caps the last chunk's hold at the clip end", () => {+ const chunks = buildPreviewChunks(words, { wordsPerChunk: 6, absorbTail: 2 }, 5.0);+ expect(chunks[chunks.length - 1].displayEnd).toBeCloseTo(5.0);+ });++ it("keeps captions active beyond the first 80 transcript words", () => {+ const transcript = Array.from({ length: 120 }, (_, index) => ({+ word: `word-${index}`,+ start: index * 0.5,+ end: index * 0.5 + 0.4,+ speaker: "A",+ }));+ const source = selectPreviewWords(transcript, {+ start_second: 0,+ end_second: 60,+ });+ const chunks = buildPreviewChunks(source, { wordsPerChunk: 5, absorbTail: 1 }, 60);++ expect(source).toHaveLength(120);+ expect(activePreviewChunk(chunks, 50.1)?.words.map((word) => word.text)).toContain("word-100");+ });+});diff --git a/src/ui/client/captionChunks.ts b/src/ui/client/captionChunks.tsnew file mode 100644index 0000000..9179c6c--- /dev/null+++ b/src/ui/client/captionChunks.ts@@ -0,0 +1,153 @@+// Port of remotion/src/chunks.ts, the chunker the renderer burns into the MP4.+// The studio's phone preview is only worth showing if it groups and holds words+// exactly like the render, so the two must be changed together.++export interface PreviewWord {+ text: string;+ start: number;+ end: number;+ speaker?: string | null;+}++export interface PreviewChunk {+ words: PreviewWord[];+ start: number;+ end: number;+ displayEnd: number;+}++export interface PreviewChunkOptions {+ wordsPerChunk: number;+ maxCharsPerChunk?: number;+ absorbTail?: number;+ splitTail?: boolean;+}++export interface TranscriptPreviewWord {+ word?: string;+ text?: string;+ start: number;+ end: number;+ speaker?: string | null;+}++export interface PreviewClipBounds {+ start_second: number;+ end_second: number;+}++const BREAK_GAP_SECONDS = 0.8;+const GAP_FILL_MAX_SECONDS = 0.4;+const LAST_CHUNK_HOLD_SECONDS = 1.2;+const TERMINAL_PUNCTUATION = /[.!?…]["')\]]?$/;++export function selectPreviewWords(+ transcriptWords: TranscriptPreviewWord[] | null | undefined,+ activeClip?: PreviewClipBounds | null,+): PreviewWord[] {+ if (!transcriptWords?.length) return [];++ const words = activeClip+ ? transcriptWords.filter(+ (word) => word.end > activeClip.start_second && word.start < activeClip.end_second,+ )+ : transcriptWords;++ return words+ .map((word) => ({+ text: (word.word ?? word.text ?? "").trim(),+ start: word.start,+ end: word.end,+ speaker: word.speaker,+ }))+ .filter((word) => word.text.length > 0);+}++function breaksAfter(prev: PreviewWord, next: PreviewWord): boolean {+ return (+ TERMINAL_PUNCTUATION.test(prev.text.trim()) ||+ (prev.speaker != null && next.speaker != null && prev.speaker !== next.speaker) ||+ next.start - prev.end > BREAK_GAP_SECONDS+ );+}++function hasBreakBetween(words: PreviewWord[], from: number, to: number): boolean {+ for (let i = from; i < to; i++) {+ if (breaksAfter(words[i], words[i + 1])) return true;+ }+ return false;+}++export function buildPreviewChunks(+ words: PreviewWord[],+ cfg: PreviewChunkOptions,+ clipEnd?: number,+): PreviewChunk[] {+ const chunks: PreviewChunk[] = [];+ let i = 0;++ while (i < words.length) {+ let end = i + 1;+ let charCount = words[i].text.trim().length;++ while (end < words.length && end - i < cfg.wordsPerChunk) {+ if (breaksAfter(words[end - 1], words[end])) break;+ if (cfg.maxCharsPerChunk != null) {+ const nextChars = charCount + 1 + words[end].text.trim().length;+ if (nextChars > cfg.maxCharsPerChunk) break;+ charCount = nextChars;+ }+ end += 1;+ }++ if (+ cfg.absorbTail != null &&+ end < words.length &&+ words.length - end <= cfg.absorbTail &&+ !hasBreakBetween(words, end - 1, words.length - 1)+ ) {+ end = words.length;+ }+ if (cfg.splitTail && words.length - end === 1 && end - i > 2) {+ end -= 1;+ }++ const slice = words.slice(i, end);+ const speechEnd = slice[slice.length - 1].end;+ chunks.push({ words: slice, start: slice[0].start, end: speechEnd, displayEnd: speechEnd });+ i = end;+ }++ for (let k = 0; k < chunks.length; k++) {+ const next = chunks[k + 1];+ const hold = next+ ? Math.min(next.start, chunks[k].end + GAP_FILL_MAX_SECONDS)+ : chunks[k].end + LAST_CHUNK_HOLD_SECONDS;+ const capped = clipEnd != null ? Math.min(hold, clipEnd) : hold;+ chunks[k].displayEnd = Math.max(chunks[k].end, capped);+ }++ return chunks;+}++export function activePreviewChunk(+ chunks: PreviewChunk[],+ time: number,+): PreviewChunk | undefined {+ let low = 0;+ let high = chunks.length - 1;++ while (low <= high) {+ const middle = Math.floor((low + high) / 2);+ const chunk = chunks[middle];+ if (time < chunk.start) {+ high = middle - 1;+ } else if (time >= chunk.displayEnd) {+ low = middle + 1;+ } else {+ return chunk;+ }+ }++ return undefined;+}diff --git a/src/ui/client/lib.test.ts b/src/ui/client/lib.test.tsindex 5100f0d..ea28650 100644--- a/src/ui/client/lib.test.ts+++ b/src/ui/client/lib.test.ts@@ -1,5 +1,13 @@import { describe, expect, it } from "vitest";-import { fmt, fmtMs } from "./lib";+import {+ fmt,+ fmtMs,+ findClipResult,+ buildEnergyMap,+ clipKey,+ dropEnergy,+ clampClipIndex,+} from "./lib";describe("fmt", () => {it("formats sub-hour timestamps as m:ss", () => {@@ -27,3 +35,113 @@ describe("fmtMs", () => {expect(fmtMs(4711.25)).toBe("1:18:31.250");});});++describe("findClipResult", () => {+ const clips = [+ { start_second: 10, end_second: 40 },+ { start_second: 120, end_second: 165 },+ { start_second: 640, end_second: 700 },+ ];++ // An agent exporting only clip #3 gets one row back, at clip_index 0. Reading+ // it positionally marked clip #1 as exported with clip #3's file.+ it("lands an agent's single export on the clip it was rendered for", () => {+ const results = [+ { status: "success", output_path: "/out/third.mp4", source_start_second: 640, source_end_second: 700 },+ ];+ expect(findClipResult(results, clips[0], 0)).toBeUndefined();+ expect(findClipResult(results, clips[1], 1)).toBeUndefined();+ expect(findClipResult(results, clips[2], 2)?.output_path).toBe("/out/third.mp4");+ });++ // Parallel renders report as they finish, so results is sparse and out of order.+ it("matches rows that arrived out of order", () => {+ const results = [+ undefined,+ { status: "success", output_path: "/out/b.mp4", source_start_second: 120, source_end_second: 165 },+ ];+ expect(findClipResult(results, clips[0], 0)).toBeUndefined();+ expect(findClipResult(results, clips[1], 1)?.output_path).toBe("/out/b.mp4");+ });++ it("falls back to position only for rows with no bounds", () => {+ const results = [{ status: "success", output_path: "/out/legacy.mp4" }];+ expect(findClipResult(results, clips[0], 0)?.output_path).toBe("/out/legacy.mp4");+ });++ it("tolerates float noise in the bounds", () => {+ const results = [+ { status: "success", output_path: "/out/a.mp4", source_start_second: 10.001, source_end_second: 40 },+ ];+ expect(findClipResult(results, clips[0], 0)?.output_path).toBe("/out/a.mp4");+ });+});++describe("buildEnergyMap", () => {+ const clips = [+ { clip_id: "c1", start_second: 10, end_second: 40 },+ { clip_id: "c2", start_second: 120, end_second: 165 },+ { clip_id: "c3", start_second: 640, end_second: 700 },+ { clip_id: "c4", start_second: 900, end_second: 940 },+ ];++ it("scores each clip on its own identity", () => {+ const map = buildEnergyMap([8.2, 5, 2.5, 7], clips);+ expect(map.c1).toEqual({ score: 8.2, level: "high" });+ expect(map.c2).toEqual({ score: 5, level: "medium" });+ expect(map.c3).toEqual({ score: 2.5, level: "low" });+ });++ // Keyed by position, deleting clip #2 slid every score up one row and left the+ // last row showing a badge for a clip that no longer existed.+ it("keeps scores on their clips after an agent deletes one", () => {+ const map = buildEnergyMap([8.2, 5, 2.5, 7], clips);+ const remaining = clips.filter((c) => c.clip_id !== "c2");+ expect(remaining.map((c) => map[clipKey(c)]?.score)).toEqual([8.2, 2.5, 7]);+ expect(Object.keys(map).filter((k) => !remaining.some((c) => clipKey(c) === k))).toEqual(["c2"]);+ });++ it("keeps scores on their clips after a range edit shifts a later clip", () => {+ const map = buildEnergyMap([8.2, 5, 2.5, 7], clips);+ const edited = { ...clips[1], start_second: 118, end_second: 170 };+ const after = [clips[0], edited, clips[2], clips[3]];+ expect(dropEnergy(map, clips[1])[clipKey(edited)]).toBeUndefined();+ expect(after.map((c) => map[clipKey(c)]?.score)).toEqual([8.2, 5, 2.5, 7]);+ });++ // A session persisted before suggestions carried a clip_id.+ it("falls back to bounds when a clip has no id", () => {+ const legacy = [+ { start_second: 10, end_second: 40 },+ { start_second: 120, end_second: 165 },+ ];+ const map = buildEnergyMap([9, 3], legacy);+ expect(map[clipKey(legacy[0])].score).toBe(9);+ expect(map[clipKey(legacy[1])].score).toBe(3);+ });++ it("ignores scores with no clip and clips with no score", () => {+ expect(buildEnergyMap([7, null, 4], clips.slice(0, 2))).toEqual({+ c1: { score: 7, level: "high" },+ });+ });+});++describe("clampClipIndex", () => {+ // j/k left the cursor past the end when an agent deleted the last clip, so+ // space deselected an index no row owned and the header count lied.+ it("pulls the cursor back onto the last row when the list shrinks", () => {+ expect(clampClipIndex(4, 4)).toBe(3);+ expect(clampClipIndex(9, 1)).toBe(0);+ });++ it("leaves an in-range cursor alone", () => {+ expect(clampClipIndex(2, 5)).toBe(2);+ expect(clampClipIndex(0, 1)).toBe(0);+ });++ it("clears the cursor when there are no clips", () => {+ expect(clampClipIndex(0, 0)).toBeNull();+ expect(clampClipIndex(null, 5)).toBeNull();+ });+});diff --git a/src/ui/client/lib.ts b/src/ui/client/lib.tsindex eee7bbc..32a5375 100644--- a/src/ui/client/lib.ts+++ b/src/ui/client/lib.ts@@ -83,3 +83,92 @@ export function timeAgo(iso: string): string {}export const basename = (p: string) => (p || "").split(/[/\\]/).pop() || "";++// A render result's clip_index counts the clips submitted to the renderer, which+// for an agent-driven export is not the studio's clip order. The server stamps+// every row with the bounds of the clip it rendered; match a result to a clip on+// those instead of on position.+export const clipBoundsKey = (start?: number, end?: number): string | null =>+ typeof start === "number" && typeof end === "number"+ ? `${start.toFixed(2)}:${end.toFixed(2)}`+ : null;++export const resultBoundsKey = (row?: ClipResultRow | null): string | null =>+ row ? clipBoundsKey(row.source_start_second, row.source_end_second) : null;++interface ClipResultRow {+ source_start_second?: number;+ source_end_second?: number;+ [key: string]: unknown;+}++interface ClipIdentity {+ clip_id?: string;+ start_second?: number;+ end_second?: number;+}++// A suggestion's position shifts whenever an agent deletes or inserts a clip, so+// anything the studio computes per clip is keyed by identity instead. Sessions+// persisted before clips carried a clip_id fall back to their bounds, which also+// makes a re-timed clip drop its stale score.+export const clipKey = (clip: ClipIdentity): string =>+ clip.clip_id || clipBoundsKey(clip.start_second, clip.end_second) || "";++type EnergyLevel = "high" | "medium" | "low";+interface EnergyEntry {+ score: number;+ level: EnergyLevel;+}++const energyLevel = (score: number): EnergyLevel =>+ score >= 7 ? "high" : score >= 4 ? "medium" : "low";++/** Maps the backend's positional segment scores onto the clips they were measured for. */+export function buildEnergyMap(+ scores: unknown[],+ clips: ClipIdentity[],+): Record<string, EnergyEntry> {+ const map: Record<string, EnergyEntry> = {};+ scores.forEach((score, i) => {+ const clip = clips[i];+ if (!clip || typeof score !== "number") return;+ const key = clipKey(clip);+ if (key) map[key] = { score, level: energyLevel(score) };+ });+ return map;+}++export function dropEnergy(+ map: Record<string, EnergyEntry>,+ clip: ClipIdentity,+): Record<string, EnergyEntry> {+ const key = clipKey(clip);+ if (!key || !(key in map)) return map;+ const next = { ...map };+ delete next[key];+ return next;+}++/** Keeps the keyboard cursor on a row that exists after the clip list changes. */+export const clampClipIndex = (idx: number | null, length: number): number | null =>+ idx === null || length === 0 ? null : Math.min(idx, length - 1);++/**+ * The result for `clip`, or undefined if it has not been rendered. Rows written+ * before the server stamped bounds (a restored session) carry no key, so they+ * still land by position.+ */+export function findClipResult<T extends ClipResultRow>(+ results: (T | undefined)[],+ clip: { start_second?: number; end_second?: number },+ positionalIdx: number,+): T | undefined {+ const key = clipBoundsKey(clip.start_second, clip.end_second);+ if (key) {+ const keyed = results.find((row) => resultBoundsKey(row) === key);+ if (keyed) return keyed;+ }+ const row = results[positionalIdx];+ return row && !resultBoundsKey(row) ? row : undefined;+}diff --git a/src/ui/client/useDialog.ts b/src/ui/client/useDialog.tsnew file mode 100644index 0000000..4f20726--- /dev/null+++ b/src/ui/client/useDialog.ts@@ -0,0 +1,49 @@+import { useEffect, useRef } from "react";++const FOCUSABLE =+ 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), video[controls], [tabindex]:not([tabindex="-1"])';++export function useDialog(active: boolean, onClose: () => void) {+ const ref = useRef<HTMLDivElement | null>(null);+ const closeRef = useRef(onClose);+ closeRef.current = onClose;++ useEffect(() => {+ if (!active) return;+ const node = ref.current;+ if (!node) return;+ const previous = document.activeElement as HTMLElement | null;+ const focusables = () => Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE));+ if (!node.contains(document.activeElement)) {+ (focusables()[0] || node).focus();+ }+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ closeRef.current();+ return;+ }+ if (e.key !== "Tab") return;+ const els = focusables();+ if (!els.length) return;+ const first = els[0];+ const last = els[els.length - 1];+ const current = document.activeElement;+ const outside = !node.contains(current);+ if (e.shiftKey && (current === first || outside)) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && (current === last || outside)) {+ e.preventDefault();+ first.focus();+ }+ };+ document.addEventListener("keydown", onKey, true);+ return () => {+ document.removeEventListener("keydown", onKey, true);+ previous?.focus?.();+ };+ }, [active]);++ return ref;+}diff --git a/src/ui/public/css/styles.css b/src/ui/public/css/styles.cssindex 06e82f8..75ee434 100644--- a/src/ui/public/css/styles.css+++ b/src/ui/public/css/styles.css@@ -636,7 +636,6 @@ select {}.clip-item:hover { border-color: var(--border-hover); }.clip-item.dimmed { opacity: 0.35; }-.clip-item.active-clip { border-color: rgba(217, 118, 49, 0.3); background: rgba(217, 118, 49, 0.03); }.clip-item.selected { border-color: var(--accent); background: rgba(217, 118, 49, 0.04); }.checkbox {width: 20px; height: 20px; border-radius: 6px;@@ -656,7 +655,6 @@ select {.clip-actions { display: flex; gap: 4px; flex-shrink: 0; }.clip-status { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 11px; font-weight: 700; }.clip-status.pending { border: 1.5px dashed var(--border); }-.clip-status.rendering { border: 2px solid var(--border); border-top-color: var(--accent); animation: spin 0.6s linear infinite; }.clip-status.exported { background: var(--green-subtle); color: var(--green); }.status-dot { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 12px; }.status-dot.ok { background: var(--green-subtle); color: var(--green); }@@ -998,6 +996,27 @@ pre .punct { color: var(--text2); }font-family: 'JetBrains Mono', monospace; font-size: 11.5px;color: var(--accent); border: 1px solid var(--border);}++/* ─── Setup checklist ─── */+.setup-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 14px; }+.setup-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }+.setup-step {+ display: flex; align-items: center; gap: 12px;+ padding: 10px 0; border-top: 1px solid var(--border);+}+.setup-step:first-child { border-top: none; }+.setup-mark {+ width: 20px; height: 20px; border-radius: 50%; flex-shrink: 0;+ border: 1px dashed var(--border); color: var(--green);+ display: flex; align-items: center; justify-content: center;+}+.setup-step.done .setup-mark { border: 1px solid var(--green-border); background: var(--green-subtle); }+.setup-body { flex: 1; min-width: 0; }+.setup-title { font-size: 13px; font-weight: 600; line-height: 1.4; }+.setup-step.done .setup-title { color: var(--text2); }+.setup-desc { font-size: 12px; color: var(--text3); line-height: 1.5; margin-top: 2px; }+.setup-action { flex-shrink: 0; }+.setup-action .btn { text-decoration: none; }.tool-grid { display: grid; gap: 8px; }.tool-item {display: flex; align-items: flex-start; gap: 12px;@@ -1161,6 +1180,8 @@ input[type="range"]::-webkit-slider-thumb {@media (max-width: 640px) {.app { padding: 28px 16px 64px; }.file-grid { grid-template-columns: 1fr; }+ .setup-step { flex-wrap: wrap; }+ .setup-action { padding-left: 32px; }}/* ── Dashboard shell ── */diff --git a/src/ui/web-server.ts b/src/ui/web-server.tsindex 5fb2ca5..ece7d3c 100644--- a/src/ui/web-server.ts+++ b/src/ui/web-server.ts@@ -30,13 +30,17 @@ import { tmpdir } from "os";import { fileURLToPath } from "url";import { v4 as uuidv4 } from "uuid";-import { PythonExecutor } from "../services/python-executor.js";+import { PythonExecutor, terminateProcessTree } from "../services/python-executor.js";import { TranscriptCache } from "../services/transcript-cache.js";import { FileManager } from "../services/file-manager.js";import { AssetManager, inferType, safeName } from "../services/asset-manager.js";import { ClipsHistory } from "../services/clips-history.js";import { KnowledgeBase } from "../services/knowledge-base.js";import { paths, pythonEnv } from "../config/paths.js";+import { webServerPort } from "../config/server.js";+import { writeFileAtomicSync } from "../utils/atomic-file.js";+import { maxClipSeconds, validateClipRange, validateSuggestionRange } from "../utils/clip-validation.js";+import { advanceProgress, tagSubmittedClip, tagSubmittedClips } from "../utils/clip-results.js";import { DEMO_ASSETS_DIR } from "./demo-fixtures.js";import { registerConfigIntegrationRoutes } from "../handlers/integrations.routes.js";import { childLogger } from "../utils/logger.js";@@ -63,7 +67,7 @@ const publicDir = existsSync(join(__dirname, "public", "index.html")): resolve(__dirname, "..", "..", "dist", "ui", "public");const app = express();-const PORT = parseInt(process.env.PORT || "3847");+const PORT = webServerPort;const DEMO = process.env.PODCLI_DEMO === "1";// --- Services ---@@ -94,10 +98,28 @@ interface JobState {result?: unknown;error?: string;createdAt: number;+ finishedAt?: number;+ clip_results?: unknown[];}const jobs = new Map<string, JobState>();+// Sweep terminal jobs so the map doesn't grow forever. Completion isn't+// stamped at the many done/error sites; the sweeper stamps it on first sight,+// so a job survives at least one full retention window after finishing.+const JOB_RETENTION_MS = 30 * 60_000;+setInterval(() => {+ const now = Date.now();+ for (const [id, job] of jobs) {+ if (job.status !== "done" && job.status !== "error") continue;+ if (job.finishedAt === undefined) {+ job.finishedAt = now;+ } else if (now - job.finishedAt > JOB_RETENTION_MS) {+ jobs.delete(id);+ }+ }+}, 60_000).unref();+/** Transcript data stored per file, plus optional face-tracking hints. */type ServerTranscript = TranscriptResult & { face_map?: unknown };@@ -120,6 +142,8 @@ interface UIState {logoPath: string;outroPath: string;introPath: string;+ cleanFillers: boolean;+ onboardingDismissed: boolean;};phase: string;results: unknown[];@@ -154,6 +178,8 @@ function loadPersistedState(): UIState {logoPath: saved.settings?.logoPath || "",outroPath: saved.settings?.outroPath || "",introPath: saved.settings?.introPath || "",+ cleanFillers: saved.settings?.cleanFillers !== false,+ onboardingDismissed: !!saved.settings?.onboardingDismissed,},// Never restore mid-export phasesphase: ["exporting", "parsing", "suggesting"].includes(saved.phase)@@ -186,6 +212,8 @@ function loadPersistedState(): UIState {logoPath: "",outroPath: "",introPath: "",+ cleanFillers: true,+ onboardingDismissed: false,},phase: "idle",results: [],@@ -219,7 +247,7 @@ function rememberSource(realPath: string): void {if (!VIDEO_SOURCE_EXTS.has(extname(realPath).toLowerCase())) return;recentSources = [realPath, ...recentSources.filter((p) => p !== realPath)].slice(0, 40);try {- writeFileSync(sourcesFile, JSON.stringify(recentSources, null, 2), "utf-8");+ writeFileAtomicSync(sourcesFile, JSON.stringify(recentSources, null, 2));} catch {}}@@ -239,7 +267,7 @@ function persistState() {if (saveTimer) clearTimeout(saveTimer);saveTimer = setTimeout(() => {try {- writeFileSync(paths.uiState, JSON.stringify(uiState, null, 2));+ writeFileAtomicSync(paths.uiState, JSON.stringify(uiState, null, 2));} catch (err) {log.warn("Failed to persist UI state to disk", { err: errMsg(err) });}@@ -642,14 +670,18 @@ app.post("/api/download-video", async (req, res) => {"after_move:podcli-filepath:%(filepath)s",url,];- const proc = spawn(paths.pythonPath, args, { env: pythonEnv() });+ // Detached so a kill takes out yt-dlp's ffmpeg children with it.+ const proc = spawn(paths.pythonPath, args, {+ env: pythonEnv(),+ detached: process.platform !== "win32",+ });let stdout = "";let stderr = "";let outputFilePath = "";let settled = false;let responded = false;- const timer = setTimeout(() => proc.kill("SIGTERM"), 3600_000);+ const timer = setTimeout(() => terminateProcessTree(proc), 3600_000);const finish = (action: () => void): void => {if (settled) return;settled = true;@@ -732,7 +764,7 @@ app.post("/api/download-video", async (req, res) => {});});req.on("close", () => {- if (!responded && !settled) proc.kill("SIGTERM");+ if (!responded && !settled) terminateProcessTree(proc);});responded = true;res.json({ job_id: jobId, status: "running" });@@ -1191,6 +1223,7 @@ app.post("/api/batch-clips", async (req, res) => {transcript_words = [],clean_fillers = false,keep_caption_overlay = false,+ format = "vertical",} = req.body;if (!video_path || !existsSync(video_path)) {@@ -1228,7 +1261,7 @@ app.post("/api/batch-clips", async (req, res) => {res.status(400).json({ error: `Clip ${i + 1}: invalid format "${c.format}". Use: vertical, horizontal, square` });return;}- const maxDur = c.format === "horizontal" ? 300 : 180;+ const maxDur = maxClipSeconds(c.format || format);if (dur > maxDur) {res.status(400).json({error: `Clip ${i + 1}: too long (${Math.round(dur)}s). Max ${maxDur}s.`,@@ -1277,6 +1310,7 @@ app.post("/api/batch-clips", async (req, res) => {{video_path,clips: enrichedClips,+ format,transcript_words,output_dir: paths.output,logo_path,@@ -1287,21 +1321,30 @@ app.post("/api/batch-clips", async (req, res) => {face_map: uiState.transcript?.face_map,},(event) => {- job.progress = event.percent;+ const progress = advanceProgress(job, event.percent);job.message = event.message;historyRecorder.recordProgress(event);+ const clipResult = event.clip_result+ ? tagSubmittedClip(event.clip_result, enrichedClips)+ : undefined;+ if (event.stage === "clip_complete" && clipResult) {+ (job.clip_results ??= []).push(clipResult);+ }broadcastSSE("job-update", {jobId,- progress: event.percent,+ progress,message: event.message,+ stage: event.stage,+ clip_result: clipResult,});},).then(async (result) => {+ const data = tagSubmittedClips(result.data, enrichedClips);job.status = "done";job.progress = 100;job.message = "Batch complete!";- job.result = result.data;+ job.result = data;// Record successful clips to historytry {await historyRecorder.recordRemaining(result.data?.results);@@ -1311,7 +1354,7 @@ app.post("/api/batch-clips", async (req, res) => {});}setExportState("done", null);- broadcastSSE("job-complete", { jobId, result: result.data });+ broadcastSSE("job-complete", { jobId, result: data });}).catch((err) => {job.status = "error";@@ -1366,6 +1409,7 @@ app.get("/api/job/:id/stream", (req, res) => {message: current.message,result: current.result,error: current.error,+ clip_results: current.clip_results,})}\n\n`,);@@ -1959,16 +2003,35 @@ app.get("/api/history", async (req, res) => {// share one history writer (preserves unknown fields like Phase 2 metrics).const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "").trim();+const RUN_PY_TIMEOUT_MS = 15 * 60_000;+function runPy(scriptAndArgs: string[]): Promise<{ code: number; stdout: string; stderr: string }> {return new Promise((resolve) => {+ // Detached so a timeout kill takes out the whole process group (ffmpeg etc.).const proc = spawn(paths.pythonPath, scriptAndArgs, {env: pythonEnv({ PODCLI_HOME: paths.home, PODCLI_DATA: paths.dataDir }),+ detached: process.platform !== "win32",});let stdout = "", stderr = "";+ let settled = false;+ const finish = (result: { code: number; stdout: string; stderr: string }) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(result);+ };+ const timer = setTimeout(() => {+ terminateProcessTree(proc);+ finish({+ code: 1,+ stdout,+ stderr: `${stderr}\nTimed out after ${RUN_PY_TIMEOUT_MS / 1000}s`.trim(),+ });+ }, RUN_PY_TIMEOUT_MS);proc.stdout.on("data", (d) => (stdout += d));proc.stderr.on("data", (d) => (stderr += d));- proc.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));- proc.on("error", (e) => resolve({ code: 1, stdout, stderr: String(e) }));+ proc.on("close", (code) => finish({ code: code ?? 1, stdout, stderr }));+ proc.on("error", (e) => finish({ code: 1, stdout, stderr: String(e) }));});}@@ -1989,7 +2052,7 @@ app.patch("/api/clips/:id", async (req, res) => {if (DEMO) { res.json({ ok: true }); return; } // fixtures are read-onlyconst { title, caption_style, thumbnail_config } = req.body || {};const args = ["clips", "edit", req.params.id];- if (title != null) args.push("--title", String(title));+ if (title != null) args.push(`--title=${title}`);if (caption_style != null) args.push("--caption-style", String(caption_style));if (thumbnail_config != null) args.push("--thumbnail-config", JSON.stringify(thumbnail_config));if (args.length === 3) {@@ -2033,8 +2096,10 @@ app.post("/api/clips/:id/thumbnail", async (req, res) => {const tc = clip.thumbnail_config || {};// Standalone thumbnail generation — produces variation PNGs, never touches the clip video.const outDir = join(paths.output, "thumbnails", String(clip.id));+ // Free-text values ride behind "--" (positionals) or as --flag=value so a+ // title starting with "-" can't be parsed as an option.const args = [- "thumbnails", tc.text || clip.title,+ "thumbnails","--output", outDir,"--variations", "3","--json",@@ -2044,8 +2109,9 @@ app.post("/api/clips/:id/thumbnail", async (req, res) => {];if (tc.image_path) args.push("--photo", String(tc.image_path));else if (typeof tc.timestamp === "number") args.push("--timestamp", String(tc.timestamp));- if (tc.line1) args.push("--line1", String(tc.line1));- if (tc.line2) args.push("--line2", String(tc.line2));+ if (tc.line1) args.push(`--line1=${tc.line1}`);+ if (tc.line2) args.push(`--line2=${tc.line2}`);+ args.push("--", tc.text || clip.title);const r = await runCli(args);if (r.code !== 0) {res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "thumbnail failed" });@@ -2099,13 +2165,14 @@ app.get("/api/clips/:id/thumbnail/options", async (req, res) => {const clamp = (v: any, d: number) => Math.min(Math.max(parseInt(String(v)) || d, 1), 8);const outDir = join(paths.output, "thumbnails", String(clip.id), "frames");const r = await runCli([- "thumbnail-options", tc.text || clip.title,+ "thumbnail-options","--output", outDir,"--video", clip.source_video,"--start", String(clip.start_second),"--end", String(clip.end_second),"--texts", String(clamp(req.query.texts, 6)),"--frames", String(clamp(req.query.frames, 6)),+ "--", tc.text || clip.title,]);if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "options failed" }); return; }const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));@@ -2132,10 +2199,11 @@ app.post("/api/clips/:id/thumbnail/render", async (req, res) => {const outDir = join(paths.output, "thumbnails", String(clip.id));await mkdir(outDir, { recursive: true });const out = join(outDir, `thumb_${uuidv4().slice(0, 8)}.png`);- const args = ["thumbnail-render", tc.text || clip.title, "--frame", resolvedFrame, "--output", out];- if (line1) args.push("--line1", String(line1));- if (line2) args.push("--line2", String(line2));+ const args = ["thumbnail-render", "--frame", resolvedFrame, "--output", out];+ if (line1) args.push(`--line1=${line1}`);+ if (line2) args.push(`--line2=${line2}`);if (frame_info) args.push("--frame-info", JSON.stringify(frame_info));+ args.push("--", tc.text || clip.title);const r = await runCli(args);if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "render failed" }); return; }const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));@@ -2177,7 +2245,7 @@ app.post("/api/thumbnail-studio/options", async (req, res) => {if (!title || !String(title).trim()) { res.status(400).json({ error: "title is required" }); return; }const clamp = (v: any, d: number) => Math.min(Math.max(parseInt(String(v)) || d, 1), 8);const args = [- "thumbnail-options", String(title),+ "thumbnail-options","--output", join(thumbStudioDir, "frames"),"--texts", String(clamp(texts, 6)),"--frames", String(clamp(frames, 6)),@@ -2192,6 +2260,7 @@ app.post("/api/thumbnail-studio/options", async (req, res) => {if (start != null && start !== "") args.push("--start", String(Math.max(0, Number(start) || 0)));if (end != null && end !== "") args.push("--end", String(Math.max(0, Number(end) || 0)));}+ args.push("--", String(title));const r = await runCli(args);if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "options failed" }); return; }const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));@@ -2212,10 +2281,11 @@ app.post("/api/thumbnail-studio/render", async (req, res) => {if (!resolvedFrame) { res.status(400).json({ error: "invalid frame" }); return; }await mkdir(thumbStudioDir, { recursive: true });const out = join(thumbStudioDir, `thumb_${uuidv4().slice(0, 8)}.png`);- const args = ["thumbnail-render", String(title), "--frame", resolvedFrame, "--output", out];- if (line1) args.push("--line1", String(line1));- if (line2) args.push("--line2", String(line2));+ const args = ["thumbnail-render", "--frame", resolvedFrame, "--output", out];+ if (line1) args.push(`--line1=${line1}`);+ if (line2) args.push(`--line2=${line2}`);if (frame_info) args.push("--frame-info", JSON.stringify(frame_info));+ args.push("--", String(title));const r = await runCli(args);if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "render failed" }); return; }const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));@@ -2284,7 +2354,7 @@ app.put("/api/youtube/config", (req, res) => {if (client_id !== undefined) yt.client_id = client_id;if (client_secret) yt.client_secret = client_secret;all.youtube = yt;- writeFileSync(paths.integrations, JSON.stringify(all, null, 2) + "\n", "utf-8");+ writeFileAtomicSync(paths.integrations, JSON.stringify(all, null, 2) + "\n");// Holds the OAuth client secret — keep it owner-only (chmod covers the// case where the file already existed with looser perms).try { chmodSync(paths.integrations, 0o600); } catch { /* best effort */ }@@ -2518,7 +2588,7 @@ app.post("/api/clips/:id/davinci", async (req, res) => {return;}const cli = join(paths.backendDir, "services", "integrations", "davinci_resolve", "cli.py");- const r = await runPy([cli, "--source", clip.output_path, "--title", clip.title]);+ const r = await runPy([cli, "--source", clip.output_path, `--title=${clip.title}`]);if (r.code !== 0) {res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "export failed" });return;@@ -2572,7 +2642,7 @@ app.get("/api/corrections", (_req, res) => {app.put("/api/corrections", express.json(), (req, res) => {try {const corrections = req.body || {};- writeFileSync(correctionsPath, JSON.stringify(corrections, null, 2));+ writeFileAtomicSync(correctionsPath, JSON.stringify(corrections, null, 2));res.json({ ok: true, corrections });} catch (err: any) {res.status(500).json({ error: err.message });@@ -2591,7 +2661,7 @@ app.post("/api/corrections/add", express.json(), (req, res) => {corrections = JSON.parse(readFileSync(correctionsPath, "utf-8"));}corrections[wrong] = correct;- writeFileSync(correctionsPath, JSON.stringify(corrections, null, 2));+ writeFileAtomicSync(correctionsPath, JSON.stringify(corrections, null, 2));res.json({ ok: true, corrections });} catch (err: any) {res.status(500).json({ error: err.message });@@ -2605,7 +2675,7 @@ app.delete("/api/corrections/:wrong", (req, res) => {corrections = JSON.parse(readFileSync(correctionsPath, "utf-8"));}delete corrections[req.params.wrong];- writeFileSync(correctionsPath, JSON.stringify(corrections, null, 2));+ writeFileAtomicSync(correctionsPath, JSON.stringify(corrections, null, 2));res.json({ ok: true, corrections });} catch (err: any) {res.status(500).json({ error: err.message });@@ -2626,6 +2696,15 @@ app.get("/api/knowledge/dir", (_req, res) => {res.json({ path: paths.knowledge });});+// Must stay ahead of the :filename routes, which would otherwise claim "init".+app.post("/api/knowledge/init", async (_req, res) => {+ try {+ res.json(await knowledgeBase.initFromTemplates());+ } catch (err: unknown) {+ res.status(500).json({ error: errMsg(err) });+ }+});+// Knowledge file upload (drag & drop .md files) — must be before :filename routesconst knowledgeUpload = multer({storage: multer.diskStorage({@@ -2697,6 +2776,39 @@ app.delete("/api/knowledge/:filename", async (req, res) => {}});+// --- Onboarding readiness ---+app.get("/api/onboarding", async (_req, res) => {+ const knowledge = await knowledgeBase+ .status()+ .catch(() => ({ templates: [], present: [], filled: [], missing: [] }));+ const assets = await assetManager.list().catch(() => []);+ const clips = await clipsHistory.load().catch(() => []);++ let aiCli = false;+ try {+ const result = await executor.execute<{ available?: boolean }>("ai_cli_status", {});+ aiCli = !!result.data?.available;+ } catch {+ // A failed probe reads the same as no CLI installed.+ }++ res.json({+ knowledge: {+ total: knowledge.templates.length,+ present: knowledge.present.length,+ filled: knowledge.filled,+ missing: knowledge.missing,+ },+ assets: {+ count: assets.length,+ branding: assets.some((a) => a.type === "logo" || a.type === "outro"),+ },+ aiCli: { available: aiCli },+ clips: { count: clips.length },+ dismissed: !!uiState.settings.onboardingDismissed,+ });+});+// --- Prompt Builder (shared by /api/generate-prompt and /api/mcp-hints) ---function getStateContext() {@@ -2928,7 +3040,11 @@ app.post("/api/claude-suggest", async (req, res) => {...uiState.suggestions.map((s) => ({ start_second: s.start_second, end_second: s.end_second, title: s.title })),];+ // The backend derives laughter/reaction anchors from the audio, so it needs+ // the source video, not just the segments.const params: Record<string, unknown> = { segments: segs, top_n, existing_clips };+ const suggestVideo = uiState.filePath || uiState.videoPath;+ if (suggestVideo) params.video_path = suggestVideo;if (min_duration) params.min_duration = min_duration;if (max_duration) params.max_duration = max_duration;const result = await executor.execute<{ clips?: SuggestedClip[] }>(@@ -3322,28 +3438,125 @@ app.post("/api/ui-state", (req, res) => {uiState.settings.outroPath = body.settings.outroPath;if (body.settings.introPath !== undefined)uiState.settings.introPath = body.settings.introPath;+ if (body.settings.cleanFillers !== undefined)+ uiState.settings.cleanFillers = body.settings.cleanFillers !== false;+ if (body.settings.onboardingDismissed !== undefined)+ uiState.settings.onboardingDismissed = !!body.settings.onboardingDismissed;}uiState.lastUpdated = Date.now();persistState();- // Broadcast to UI when changes come from MCP (not from UI itself)+ // Broadcast to UI when changes come from MCP (not from UI itself).+ // Send the stored (server-enriched) values, not the raw request body, so+ // clients see keep_segments etc.; energyData rides along so unrelated syncs+ // don't wipe computed energy client-side.if (source !== "ui") {broadcastSSE("state-sync", {- ...(body.videoPath !== undefined && { videoPath: body.videoPath }),- ...(body.filePath !== undefined && { filePath: body.filePath }),- ...(body.suggestions !== undefined && { suggestions: body.suggestions }),+ ...(body.videoPath !== undefined && { videoPath: uiState.videoPath }),+ ...(body.filePath !== undefined && { filePath: uiState.filePath }),+ ...(body.suggestions !== undefined && { suggestions: uiState.suggestions }),...(body.deselectedIndices !== undefined && {- deselectedIndices: body.deselectedIndices,+ deselectedIndices: uiState.deselectedIndices,}),- ...(body.phase !== undefined && { phase: body.phase }),- ...(body.transcript !== undefined && { transcript: body.transcript }),- ...(body.settings && { settings: body.settings }),+ ...(body.phase !== undefined && { phase: uiState.phase }),+ ...(body.transcript !== undefined && { transcript: uiState.transcript }),+ ...(body.settings && { settings: uiState.settings }),+ energyData: uiState.energyData,});}res.json({ ok: true });});+// Mirrors clipKey() in the studio client: energy scores are keyed by clip+// identity, not by position, so they survive a suggestion being spliced out.+function dropEnergy(clip: SuggestedClip): void {+ const key =+ clip.clip_id ||+ `${clip.start_second.toFixed(2)}:${clip.end_second.toFixed(2)}`;+ delete uiState.energyData[key];+}++/**+ * POST /api/suggestions/modify — mutate one suggestion in-place on the server.+ * Replaces the read-modify-replace cycle MCP tools used, which lost concurrent+ * edits between the GET and the wholesale POST.+ * Body: { action: "update" | "delete" | "toggle", index? | clip_id?, updates?, selected? }+ */+app.post("/api/suggestions/modify", (req, res) => {+ const { action = "update", clip_id, updates, selected } = req.body || {};+ let index = typeof req.body?.index === "number" ? req.body.index : -1;+ if (index === -1 && clip_id) {+ index = uiState.suggestions.findIndex((s) => s.clip_id === clip_id);+ }+ if (index < 0 || index >= uiState.suggestions.length) {+ res.status(404).json({ error: "Clip not found", total: uiState.suggestions.length });+ return;+ }++ let clip: SuggestedClip;+ if (action === "delete") {+ [clip] = uiState.suggestions.splice(index, 1);+ uiState.deselectedIndices = uiState.deselectedIndices+ .filter((i) => i !== index)+ .map((i) => (i > index ? i - 1 : i));+ dropEnergy(clip);+ } else if (action === "toggle") {+ if (typeof selected !== "boolean") {+ res.status(400).json({ error: "selected must be a boolean for action 'toggle'" });+ return;+ }+ if (selected) {+ uiState.deselectedIndices = uiState.deselectedIndices.filter((i) => i !== index);+ } else if (!uiState.deselectedIndices.includes(index)) {+ uiState.deselectedIndices = [...uiState.deselectedIndices, index];+ }+ clip = uiState.suggestions[index];+ } else if (action === "update") {+ const upd = updates || {};+ clip = uiState.suggestions[index];+ const nextStart = typeof upd.start_second === "number" ? upd.start_second : clip.start_second;+ const nextEnd = typeof upd.end_second === "number" ? upd.end_second : clip.end_second;+ const rangeError = validateSuggestionRange(nextStart, nextEnd);+ if (rangeError) {+ res.status(400).json({ error: rangeError });+ return;+ }+ // The energy score was measured over the old range.+ if (nextStart !== clip.start_second || nextEnd !== clip.end_second) dropEnergy(clip);+ if (typeof upd.title === "string") clip.title = upd.title;+ clip.start_second = nextStart;+ clip.end_second = nextEnd;+ if (typeof upd.reasoning === "string") clip.reasoning = upd.reasoning;+ if (typeof upd.preview_text === "string") clip.preview_text = upd.preview_text;+ if (typeof upd.suggested_caption_style === "string") {+ clip.suggested_caption_style = upd.suggested_caption_style;+ }+ clip.duration = Math.round((clip.end_second - clip.start_second) * 10) / 10;+ const fmtTime = (s: number) =>+ `${Math.floor(s / 60)}:${Math.floor(s % 60).toString().padStart(2, "0")}`;+ clip.timestamp_display = `${fmtTime(clip.start_second)} → ${fmtTime(clip.end_second)}`;+ } else {+ res.status(400).json({ error: `Unknown action: ${action}` });+ return;+ }++ uiState.lastUpdated = Date.now();+ persistState();+ broadcastSSE("state-sync", {+ suggestions: uiState.suggestions,+ deselectedIndices: uiState.deselectedIndices,+ energyData: uiState.energyData,+ });+ res.json({+ ok: true,+ index,+ clip,+ total: uiState.suggestions.length,+ selectedCount: uiState.suggestions.length - uiState.deselectedIndices.length,+ });+});+/*** POST /api/mcp/export — MCP triggers export using current UI state*/@@ -3371,6 +3584,13 @@ app.post("/api/mcp/export", async (req, res) => {const format =req.body.format || uiState.settings.format || "vertical";const allowAssFallback = req.body.allow_ass_fallback === true;+ // An agent that says nothing about fillers gets the studio's toggle, so an+ // export it triggers matches what the user set up there.+ const cleanFillers =+ req.body.clean_fillers !== undefined+ ? req.body.clean_fillers !== false+ : uiState.settings.cleanFillers !== false;+ const keepCaptionOverlay = req.body.keep_caption_overlay === true;if (!videoPath || !existsSync(videoPath)) {res.status(400).json({ error: "Video file not found" });@@ -3380,6 +3600,14 @@ app.post("/api/mcp/export", async (req, res) => {res.status(400).json({ error: "No clips to export" });return;}+ for (let i = 0; i < clips.length; i++) {+ const c = clips[i];+ const rangeError = validateClipRange(c.start_second, c.end_second, c.format || format);+ if (rangeError) {+ res.status(400).json({ error: `Clip ${i + 1}: ${rangeError}` });+ return;+ }+ }await fileManager.ensureDirectories();@@ -3424,7 +3652,7 @@ app.post("/api/mcp/export", async (req, res) => {logoPath,outroPath,introPath,- cleanFillers: req.body.clean_fillers === true,+ cleanFillers,});// Broadcast to UI so it can track progress@@ -3444,24 +3672,35 @@ app.post("/api/mcp/export", async (req, res) => {logo_path: logoPath,outro_path: outroPath,intro_path: introPath,+ clean_fillers: cleanFillers,+ keep_caption_overlay: keepCaptionOverlay,face_map: uiState.transcript?.face_map,},(event) => {- job.progress = event.percent;+ const progress = advanceProgress(job, event.percent);job.message = event.message;historyRecorder.recordProgress(event);+ const clipResult = event.clip_result+ ? tagSubmittedClip(event.clip_result, styledClips)+ : undefined;+ if (event.stage === "clip_complete" && clipResult) {+ (job.clip_results ??= []).push(clipResult);+ }broadcastSSE("job-update", {jobId,- progress: event.percent,+ progress,message: event.message,+ stage: event.stage,+ clip_result: clipResult,});},).then(async (result) => {+ const data = tagSubmittedClips(result.data, styledClips);job.status = "done";job.progress = 100;job.message = "Export complete!";- job.result = result.data;+ job.result = data;// Record clips to historytry {await historyRecorder.recordRemaining(result.data?.results);@@ -3471,7 +3710,7 @@ app.post("/api/mcp/export", async (req, res) => {});}setExportState("done", null);- broadcastSSE("job-complete", { jobId, result: result.data });+ broadcastSSE("job-complete", { jobId, result: data });}).catch((err) => {job.status = "error";@@ -3513,8 +3752,10 @@ async function main() {// SPA fallback: client-side routes (/, /episode, /clip/:id) resolve to the// built index.html. Registered last so it never shadows /api or static assets.+ // root: the install path can contain a dot segment (a global npm install under+ // ~/.nvm, say), and sendFile's dotfile rule would 404 the whole app.app.get(/^(?!\/api\/).*/, (_req, res) => {- res.sendFile(join(publicDir, "index.html"));+ res.sendFile("index.html", { root: publicDir });});// Bind to loopback by default — the studio serves local files (clips, assets,@@ -3525,7 +3766,7 @@ async function main() {});server.on("error", (err: NodeJS.ErrnoException) => {if (err.code === "EADDRINUSE") {- log.error(`Port ${PORT} is already in use — is the studio already running? Set PORT to use another.`);+ log.error(`Port ${PORT} is already in use — is the studio already running? Set PODCLI_PORT to use another.`);} else {log.error("Web server failed to start", { err: err.message });}diff --git a/src/utils/atomic-file.test.ts b/src/utils/atomic-file.test.tsnew file mode 100644index 0000000..67885e9--- /dev/null+++ b/src/utils/atomic-file.test.ts@@ -0,0 +1,42 @@+import { describe, it, expect } from "vitest";+import { mkdtempSync, readFileSync, readdirSync, existsSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";+import { writeFileAtomic, writeFileAtomicSync } from "./atomic-file.js";++const dir = mkdtempSync(join(tmpdir(), "podcli-atomic-"));++describe("atomic-file", () => {+ it("writes a new file synchronously", () => {+ const p = join(dir, "sync.json");+ writeFileAtomicSync(p, '{"a":1}');+ expect(readFileSync(p, "utf-8")).toBe('{"a":1}');+ });++ it("replaces an existing file synchronously", () => {+ const p = join(dir, "replace.json");+ writeFileAtomicSync(p, "old");+ writeFileAtomicSync(p, "new");+ expect(readFileSync(p, "utf-8")).toBe("new");+ });++ it("writes asynchronously", async () => {+ const p = join(dir, "async.json");+ await writeFileAtomic(p, "async-data");+ expect(readFileSync(p, "utf-8")).toBe("async-data");+ });++ it("leaves no temp files behind", async () => {+ const p = join(dir, "clean.json");+ writeFileAtomicSync(p, "1");+ await writeFileAtomic(p, "2");+ expect(readdirSync(dir).filter((f) => f.endsWith(".tmp"))).toEqual([]);+ });++ it("cleans up the temp file when the rename target is invalid", async () => {+ const target = join(dir, "missing-dir", "x.json");+ await expect(writeFileAtomic(target, "data")).rejects.toThrow();+ expect(existsSync(target)).toBe(false);+ expect(readdirSync(dir).filter((f) => f.endsWith(".tmp"))).toEqual([]);+ });+});diff --git a/src/utils/atomic-file.ts b/src/utils/atomic-file.tsnew file mode 100644index 0000000..557d8e9--- /dev/null+++ b/src/utils/atomic-file.ts@@ -0,0 +1,33 @@+import { writeFileSync, renameSync, rmSync } from "fs";+import { writeFile, rename, rm } from "fs/promises";+import { randomUUID } from "crypto";++// Write to a temp file and atomically rename so a crash or a concurrent+// reader never sees a half-written file.+function tmpPathFor(filePath: string): string {+ return `${filePath}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;+}++export function writeFileAtomicSync(filePath: string, data: string): void {+ const tmp = tmpPathFor(filePath);+ try {+ writeFileSync(tmp, data, "utf-8");+ renameSync(tmp, filePath);+ } catch (err) {+ try {+ rmSync(tmp, { force: true });+ } catch {}+ throw err;+ }+}++export async function writeFileAtomic(filePath: string, data: string): Promise<void> {+ const tmp = tmpPathFor(filePath);+ try {+ await writeFile(tmp, data, "utf-8");+ await rename(tmp, filePath);+ } catch (err) {+ await rm(tmp, { force: true }).catch(() => {});+ throw err;+ }+}diff --git a/src/utils/clip-results.test.ts b/src/utils/clip-results.test.tsnew file mode 100644index 0000000..18cf730--- /dev/null+++ b/src/utils/clip-results.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import { advanceProgress, tagSubmittedClip, tagSubmittedClips } from "./clip-results.js";+import type { BatchClipsResult } from "../models/index.js";++const specs = [+ { start_second: 120, end_second: 165 },+ { start_second: 640, end_second: 700 },+];++describe("tagSubmittedClip", () => {+ it("stamps the bounds of the clip that was submitted at that index", () => {+ const row = tagSubmittedClip(+ { clip_index: 1, status: "success", output_path: "/out/b.mp4" },+ specs,+ );+ expect(row.source_start_second).toBe(640);+ expect(row.source_end_second).toBe(700);+ });++ // The renderer trims weak openings, so the row's own start_second is the+ // rendered start, not the requested one.+ it("keeps the submitted bounds even when the render moved start_second", () => {+ const row = tagSubmittedClip(+ { clip_index: 0, status: "success", start_second: 123.4, end_second: 165 },+ specs,+ );+ expect(row.start_second).toBe(123.4);+ expect(row.source_start_second).toBe(120);+ });++ it("leaves rows alone when there is no matching spec", () => {+ expect(tagSubmittedClip({ status: "success" }, specs).source_start_second).toBeUndefined();+ expect(tagSubmittedClip({ clip_index: 9, status: "success" }, specs).source_start_second).toBeUndefined();+ expect(tagSubmittedClip({ clip_index: 0, status: "success" }).source_start_second).toBeUndefined();+ });++ it("stamps error rows too", () => {+ const row = tagSubmittedClip(+ { clip_index: 1, status: "error", error: "ffmpeg died" },+ specs,+ );+ expect(row.source_start_second).toBe(640);+ });+});++describe("tagSubmittedClips", () => {+ it("stamps every row of the final result", () => {+ const data: BatchClipsResult = {+ total_clips: 2,+ successful_clips: 1,+ results: [+ { clip_index: 0, status: "success", output_path: "/out/a.mp4" },+ { clip_index: 1, status: "error", error: "boom" },+ ],+ };+ const tagged = tagSubmittedClips(data, specs);+ expect(tagged?.results.map((r) => r.source_start_second)).toEqual([120, 640]);+ });++ it("passes undefined data through", () => {+ expect(tagSubmittedClips(undefined, specs)).toBeUndefined();+ });+});++describe("advanceProgress", () => {+ // Parallel workers each report their own share, so percentages arrive out of order.+ it("never lets progress run backwards", () => {+ const job = { progress: 0 };+ expect(advanceProgress(job, 50)).toBe(50);+ expect(advanceProgress(job, 12)).toBe(50);+ expect(advanceProgress(job, 75)).toBe(75);+ expect(job.progress).toBe(75);+ });+});diff --git a/src/utils/clip-results.ts b/src/utils/clip-results.tsnew file mode 100644index 0000000..2624d9b--- /dev/null+++ b/src/utils/clip-results.ts@@ -0,0 +1,42 @@+import type { BatchClipsResult } from "../models/index.js";++type ClipResultRow = BatchClipsResult["results"][number];+export type ClipBounds = { start_second: number; end_second: number };++// Python numbers its result rows by position in the clips array it was handed,+// which for an agent-driven export is not the studio's clip order. Stamp each row+// with the bounds of the clip that was submitted for it so the client can match a+// result to its own clip instead of trusting the index. The rendered start_second+// can't stand in for that: the renderer trims weak openings and reports the+// trimmed value.+export function tagSubmittedClip(+ row: ClipResultRow,+ clipSpecs?: ClipBounds[],+): ClipResultRow {+ const spec =+ typeof row.clip_index === "number" ? clipSpecs?.[row.clip_index] : undefined;+ if (!spec) return row;+ return {+ ...row,+ source_start_second: spec.start_second,+ source_end_second: spec.end_second,+ };+}++export function tagSubmittedClips(+ data: BatchClipsResult | undefined,+ clipSpecs?: ClipBounds[],+): BatchClipsResult | undefined {+ if (!data?.results) return data;+ return {+ ...data,+ results: data.results.map((row) => tagSubmittedClip(row, clipSpecs)),+ };+}++// Clips render in parallel, so each worker reports its own share of the batch and+// the percentages arrive out of order. Only ever move the bar forward.+export function advanceProgress(job: { progress: number }, percent: number): number {+ if (typeof percent === "number" && percent > job.progress) job.progress = percent;+ return job.progress;+}diff --git a/src/utils/clip-validation.test.ts b/src/utils/clip-validation.test.tsnew file mode 100644index 0000000..e1ef765--- /dev/null+++ b/src/utils/clip-validation.test.ts@@ -0,0 +1,54 @@+import { describe, it, expect } from "vitest";+import { validateClipRange, validateSuggestionRange, maxClipSeconds } from "./clip-validation.js";++describe("validateClipRange", () => {+ it("accepts a normal vertical clip", () => {+ expect(validateClipRange(10, 40)).toBeNull();+ });++ it("rejects non-numbers", () => {+ expect(validateClipRange("10" as unknown, 40)).toMatch(/must be numbers/);+ expect(validateClipRange(10, NaN)).toMatch(/must be numbers/);+ expect(validateClipRange(undefined, undefined)).toMatch(/must be numbers/);+ });++ it("rejects negative start", () => {+ expect(validateClipRange(-1, 20)).toMatch(/>= 0/);+ });++ it("rejects end <= start", () => {+ expect(validateClipRange(30, 30)).toMatch(/greater than start_second/);+ expect(validateClipRange(30, 10)).toMatch(/greater than start_second/);+ });++ it("caps vertical clips at 180s and horizontal at 300s", () => {+ expect(validateClipRange(0, 180)).toBeNull();+ expect(validateClipRange(0, 181)).toMatch(/Max 180 seconds/);+ expect(validateClipRange(0, 300, "horizontal")).toBeNull();+ expect(validateClipRange(0, 301, "horizontal")).toMatch(/Max 300 seconds/);+ });++ it("maxClipSeconds matches the range check", () => {+ expect(maxClipSeconds()).toBe(180);+ expect(maxClipSeconds("vertical")).toBe(180);+ expect(maxClipSeconds("horizontal")).toBe(300);+ });+});++describe("validateSuggestionRange", () => {+ it("accepts ranges longer than render limits", () => {+ expect(validateSuggestionRange(0, 400)).toBeNull();+ });++ it("rejects end <= start", () => {+ expect(validateSuggestionRange(50, 50)).toMatch(/greater than start_second/);+ });++ it("rejects absurdly long ranges", () => {+ expect(validateSuggestionRange(0, 601)).toMatch(/Max 600 seconds/);+ });++ it("rejects non-numbers", () => {+ expect(validateSuggestionRange(null, 10)).toMatch(/must be numbers/);+ });+});diff --git a/src/utils/clip-validation.ts b/src/utils/clip-validation.tsnew file mode 100644index 0000000..82e0810--- /dev/null+++ b/src/utils/clip-validation.ts@@ -0,0 +1,47 @@+export function maxClipSeconds(format?: string): number {+ return format === "horizontal" ? 300 : 180;+}++/** Returns an error message, or null when the range is renderable. */+export function validateClipRange(+ start: unknown,+ end: unknown,+ format?: string,+): string | null {+ if (+ typeof start !== "number" ||+ !Number.isFinite(start) ||+ typeof end !== "number" ||+ !Number.isFinite(end)+ ) {+ return "start_second and end_second must be numbers";+ }+ if (start < 0) return "start_second must be >= 0";+ if (end <= start) return "end_second must be greater than start_second";+ const maxDur = maxClipSeconds(format);+ if (end - start > maxDur) {+ return `Clip too long (${Math.round(end - start)}s). Max ${maxDur} seconds.`;+ }+ return null;+}++// Suggestions aren't bound to a format yet, so allow up to the longest+// renderable duration plus trim headroom.+const MAX_SUGGESTION_SECONDS = 600;++export function validateSuggestionRange(start: unknown, end: unknown): string | null {+ if (+ typeof start !== "number" ||+ !Number.isFinite(start) ||+ typeof end !== "number" ||+ !Number.isFinite(end)+ ) {+ return "start_second and end_second must be numbers";+ }+ if (start < 0) return "start_second must be >= 0";+ if (end <= start) return "end_second must be greater than start_second";+ if (end - start > MAX_SUGGESTION_SECONDS) {+ return `Suggested range too long (${Math.round(end - start)}s). Max ${MAX_SUGGESTION_SECONDS} seconds.`;+ }+ return null;+}diff --git a/tests/parity/golden/branded.ass.expected b/tests/parity/golden/branded.ass.expectedindex 3181376..01725ed 100644--- a/tests/parity/golden/branded.ass.expected+++ b/tests/parity/golden/branded.ass.expected@@ -12,41 +12,23 @@ Style: BrandedNormal,Arial,80,&H00FFFFFF,&H00FFFFFF,&H90000000,&H00000000,-1,0,0[Events]Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text+Dialogue: 1,0:00:00.00,0:00:01.05,BrandedNormal,,0,0,0,,{\an5\pos(320,1380)}The+Dialogue: 1,0:00:00.00,0:00:01.05,BrandedNormal,,0,0,0,,{\an5\pos(520,1380)}james+Dialogue: 1,0:00:00.00,0:00:01.05,BrandedNormal,,0,0,0,,{\an5\pos(740,1380)}webbDialogue: 0,0:00:00.00,0:00:00.34,BrandedNormal,,0,0,0,,{\an7\pos(240,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 145 0 b 153 0 160 7 160 15 l 160 85 b 160 93 153 100 145 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:00.00,0:00:00.34,BrandedNormal,,0,0,0,,{\an5\pos(320,1380)}The-Dialogue: 1,0:00:00.00,0:00:00.34,BrandedNormal,,0,0,0,,{\an5\pos(520,1380)}james-Dialogue: 1,0:00:00.00,0:00:00.34,BrandedNormal,,0,0,0,,{\an5\pos(740,1380)}webbDialogue: 0,0:00:00.34,0:00:00.72,BrandedNormal,,0,0,0,,{\an7\pos(400,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 225 0 b 233 0 240 7 240 15 l 240 85 b 240 93 233 100 225 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:00.34,0:00:00.72,BrandedNormal,,0,0,0,,{\an5\pos(320,1380)}The-Dialogue: 1,0:00:00.34,0:00:00.72,BrandedNormal,,0,0,0,,{\an5\pos(520,1380)}james-Dialogue: 1,0:00:00.34,0:00:00.72,BrandedNormal,,0,0,0,,{\an5\pos(740,1380)}webbDialogue: 0,0:00:00.72,0:00:01.05,BrandedNormal,,0,0,0,,{\an7\pos(640,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 185 0 b 193 0 200 7 200 15 l 200 85 b 200 93 193 100 185 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:00.72,0:00:01.05,BrandedNormal,,0,0,0,,{\an5\pos(320,1380)}The-Dialogue: 1,0:00:00.72,0:00:01.05,BrandedNormal,,0,0,0,,{\an5\pos(520,1380)}james-Dialogue: 1,0:00:00.72,0:00:01.05,BrandedNormal,,0,0,0,,{\an5\pos(740,1380)}webb+Dialogue: 1,0:00:01.05,0:00:02.40,BrandedNormal,,0,0,0,,{\an5\pos(360,1380)}Telescope+Dialogue: 1,0:00:01.05,0:00:02.40,BrandedNormal,,0,0,0,,{\an5\pos(660,1380)}cost+Dialogue: 1,0:00:01.05,0:00:02.40,BrandedNormal,,0,0,0,,{\an5\pos(840,1380)}$10Dialogue: 0,0:00:01.05,0:00:01.62,BrandedNormal,,0,0,0,,{\an7\pos(160,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 385 0 b 393 0 400 7 400 15 l 400 85 b 400 93 393 100 385 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:01.05,0:00:01.62,BrandedNormal,,0,0,0,,{\an5\pos(360,1380)}Telescope-Dialogue: 1,0:00:01.05,0:00:01.62,BrandedNormal,,0,0,0,,{\an5\pos(660,1380)}cost-Dialogue: 1,0:00:01.05,0:00:01.62,BrandedNormal,,0,0,0,,{\an5\pos(840,1380)}$10Dialogue: 0,0:00:01.62,0:00:01.95,BrandedNormal,,0,0,0,,{\an7\pos(560,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 185 0 b 193 0 200 7 200 15 l 200 85 b 200 93 193 100 185 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:01.62,0:00:01.95,BrandedNormal,,0,0,0,,{\an5\pos(360,1380)}Telescope-Dialogue: 1,0:00:01.62,0:00:01.95,BrandedNormal,,0,0,0,,{\an5\pos(660,1380)}cost-Dialogue: 1,0:00:01.62,0:00:01.95,BrandedNormal,,0,0,0,,{\an5\pos(840,1380)}$10Dialogue: 0,0:00:01.95,0:00:02.40,BrandedNormal,,0,0,0,,{\an7\pos(760,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 145 0 b 153 0 160 7 160 15 l 160 85 b 160 93 153 100 145 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:01.95,0:00:02.40,BrandedNormal,,0,0,0,,{\an5\pos(360,1380)}Telescope-Dialogue: 1,0:00:01.95,0:00:02.40,BrandedNormal,,0,0,0,,{\an5\pos(660,1380)}cost-Dialogue: 1,0:00:01.95,0:00:02.40,BrandedNormal,,0,0,0,,{\an5\pos(840,1380)}$10-Dialogue: 0,0:00:02.40,0:00:03.10,BrandedNormal,,0,0,0,,{\an7\pos(120,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 345 0 b 353 0 360 7 360 15 l 360 85 b 360 93 353 100 345 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:02.40,0:00:03.10,BrandedNormal,,0,0,0,,{\an5\pos(300,1380)}Billion.-Dialogue: 1,0:00:02.40,0:00:03.10,BrandedNormal,,0,0,0,,{\an5\pos(620,1380)}wasn't-Dialogue: 1,0:00:02.40,0:00:03.10,BrandedNormal,,0,0,0,,{\an5\pos(860,1380)}that-Dialogue: 0,0:00:03.10,0:00:03.55,BrandedNormal,,0,0,0,,{\an7\pos(480,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 265 0 b 273 0 280 7 280 15 l 280 85 b 280 93 273 100 265 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:03.10,0:00:03.55,BrandedNormal,,0,0,0,,{\an5\pos(300,1380)}Billion.-Dialogue: 1,0:00:03.10,0:00:03.55,BrandedNormal,,0,0,0,,{\an5\pos(620,1380)}wasn't-Dialogue: 1,0:00:03.10,0:00:03.55,BrandedNormal,,0,0,0,,{\an5\pos(860,1380)}that-Dialogue: 0,0:00:03.55,0:00:03.60,BrandedNormal,,0,0,0,,{\an7\pos(760,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 185 0 b 193 0 200 7 200 15 l 200 85 b 200 93 193 100 185 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:03.55,0:00:03.60,BrandedNormal,,0,0,0,,{\an5\pos(300,1380)}Billion.-Dialogue: 1,0:00:03.55,0:00:03.60,BrandedNormal,,0,0,0,,{\an5\pos(620,1380)}wasn't-Dialogue: 1,0:00:03.55,0:00:03.60,BrandedNormal,,0,0,0,,{\an5\pos(860,1380)}that-Dialogue: 0,0:00:03.55,0:00:04.20,BrandedNormal,,0,0,0,,{\an7\pos(320,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 425 0 b 433 0 440 7 440 15 l 440 85 b 440 93 433 100 425 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}-Dialogue: 1,0:00:03.55,0:00:04.20,BrandedNormal,,0,0,0,,{\an5\pos(540,1380)}Expensive?+Dialogue: 1,0:00:02.40,0:00:03.10,BrandedNormal,,0,0,0,,{\an5\pos(540,1380)}Billion.+Dialogue: 0,0:00:02.40,0:00:03.10,BrandedNormal,,0,0,0,,{\an7\pos(360,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 345 0 b 353 0 360 7 360 15 l 360 85 b 360 93 353 100 345 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}+Dialogue: 1,0:00:03.10,0:00:04.20,BrandedNormal,,0,0,0,,{\an5\pos(220,1380)}Wasn't+Dialogue: 1,0:00:03.10,0:00:04.20,BrandedNormal,,0,0,0,,{\an5\pos(460,1380)}that+Dialogue: 1,0:00:03.10,0:00:04.20,BrandedNormal,,0,0,0,,{\an5\pos(780,1380)}expensive?+Dialogue: 0,0:00:03.10,0:00:03.55,BrandedNormal,,0,0,0,,{\an7\pos(80,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 265 0 b 273 0 280 7 280 15 l 280 85 b 280 93 273 100 265 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}+Dialogue: 0,0:00:03.55,0:00:03.65,BrandedNormal,,0,0,0,,{\an7\pos(360,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 185 0 b 193 0 200 7 200 15 l 200 85 b 200 93 193 100 185 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}+Dialogue: 0,0:00:03.55,0:00:04.20,BrandedNormal,,0,0,0,,{\an7\pos(560,1330)\p1\c&H00000000&\bord0\shad0\1a&HFF&\t(0,80,\1a&H30&)}m 15 0 l 425 0 b 433 0 440 7 440 15 l 440 85 b 440 93 433 100 425 100 l 15 100 b 7 100 0 93 0 85 l 0 15 b 0 7 7 0 15 0{\p0}diff --git a/tests/parity/golden/hormozi.ass.expected b/tests/parity/golden/hormozi.ass.expectedindex 2092e44..b1a4c2d 100644--- a/tests/parity/golden/hormozi.ass.expected+++ b/tests/parity/golden/hormozi.ass.expected@@ -14,5 +14,5 @@ Style: Default,Arial,80,&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, TextDialogue: 0,0:00:00.00,0:00:01.05,Default,,0,0,0,,{\c&H0000FFFF\2c&H00FFFFFF}{\kf34}THE {\kf37}JAMES {\kf33}WEBBDialogue: 0,0:00:01.05,0:00:02.40,Default,,0,0,0,,{\c&H0000FFFF\2c&H00FFFFFF}{\kf57}TELESCOPE {\kf32}COST {\kf44}$10-Dialogue: 0,0:00:02.40,0:00:03.60,Default,,0,0,0,,{\c&H0000FFFF\2c&H00FFFFFF}{\kf55}BILLION. {\kf44}WASN'T {\kf4}THAT-Dialogue: 0,0:00:03.55,0:00:04.20,Default,,0,0,0,,{\c&H0000FFFF\2c&H00FFFFFF}{\kf65}EXPENSIVE?+Dialogue: 0,0:00:02.40,0:00:03.10,Default,,0,0,0,,{\c&H0000FFFF\2c&H00FFFFFF}{\kf55}BILLION.+Dialogue: 0,0:00:03.10,0:00:04.20,Default,,0,0,0,,{\c&H0000FFFF\2c&H00FFFFFF}{\kf44}WASN'T {\kf4}THAT {\kf65}EXPENSIVE?diff --git a/tests/parity/golden/karaoke.ass.expected b/tests/parity/golden/karaoke.ass.expectedindex c7d5337..067f6e8 100644--- a/tests/parity/golden/karaoke.ass.expected+++ b/tests/parity/golden/karaoke.ass.expected@@ -13,4 +13,5 @@ Style: Default,Arial,60,&H00808080,&H00808080,&H00000000,&H80000000,0,0,0,0,100,[Events]Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, TextDialogue: 0,0:00:00.00,0:00:01.95,Default,,0,0,0,,{\c&H00FFFFFF}{\2c&H00808080}{\kf34}The {\kf37}James {\kf33}Webb {\kf57}telescope {\kf32}cost-Dialogue: 0,0:00:01.95,0:00:04.20,Default,,0,0,0,,{\c&H00FFFFFF}{\2c&H00808080}{\kf44}$10 {\kf55}billion. {\kf44}Wasn't {\kf4}that {\kf65}expensive?+Dialogue: 0,0:00:01.95,0:00:03.10,Default,,0,0,0,,{\c&H00FFFFFF}{\2c&H00808080}{\kf44}$10 {\kf55}billion.+Dialogue: 0,0:00:03.10,0:00:04.20,Default,,0,0,0,,{\c&H00FFFFFF}{\2c&H00808080}{\kf44}Wasn't {\kf4}that {\kf65}expensive?diff --git a/tests/parity/golden/subtle.ass.expected b/tests/parity/golden/subtle.ass.expectedindex 85a143d..93dc0ba 100644--- a/tests/parity/golden/subtle.ass.expected+++ b/tests/parity/golden/subtle.ass.expected@@ -13,4 +13,5 @@ Style: Default,Arial,52,&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,0,0,0,0,100,[Events]Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, TextDialogue: 0,0:00:00.00,0:00:01.95,Default,,0,0,0,,The James Webb telescope cost-Dialogue: 0,0:00:01.95,0:00:04.20,Default,,0,0,0,,$10 billion. Wasn't that expensive?+Dialogue: 0,0:00:01.95,0:00:03.10,Default,,0,0,0,,$10 billion.+Dialogue: 0,0:00:03.10,0:00:04.20,Default,,0,0,0,,Wasn't that expensive?diff --git a/tests/test_ai_fallback.py b/tests/test_ai_fallback.pyindex 5282845..f54a70f 100644--- a/tests/test_ai_fallback.py+++ b/tests/test_ai_fallback.py@@ -181,7 +181,7 @@ class AIFallbackTests(unittest.TestCase):calls = []- def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, timeout=300, error_sink=None):+ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, timeout=300, error_sink=None, reaction_times=None):calls.append({"start": segments[0]["start"],"end": segments[-1]["end"],diff --git a/tests/test_audio_analyzer.py b/tests/test_audio_analyzer.pyindex d8a2d02..97c1784 100644--- a/tests/test_audio_analyzer.py+++ b/tests/test_audio_analyzer.py@@ -2,7 +2,9 @@import osimport sys+import tempfileimport unittest+from unittest import mockROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))BACKEND_ROOT = os.path.join(ROOT, "backend")@@ -10,6 +12,7 @@ if BACKEND_ROOT not in sys.path:sys.path.insert(0, BACKEND_ROOT)from services import audio_analyzer as aa+from services import audio_extractclass ComputeEnergyScoresTests(unittest.TestCase):@@ -83,5 +86,54 @@ class ComputeEnergyScoresTests(unittest.TestCase):self.assertEqual(len(scores), 1)++class ExtractAudioEnergyCommandTests(unittest.TestCase):+ def _run(self, wav_path=None):+ with mock.patch.object(aa, "proc_run", return_value=mock.Mock(returncode=0, stdout="", stderr="")) as mocked, \+ mock.patch.object(aa, "_fallback_energy", return_value=[]):+ aa.extract_audio_energy("/video.mp4", wav_path=wav_path)+ return mocked.call_args.args[0]++ def test_window_is_pinned_with_asetnsamples(self):+ cmd = self._run()+ af = cmd[cmd.index("-af") + 1]+ self.assertIn("asetnsamples=n=16000", af)+ self.assertIn("astats=metadata=1:reset=1", af)++ def test_uses_shared_wav_when_provided(self):+ fd, wav = tempfile.mkstemp(suffix=".wav")+ os.close(fd)+ try:+ cmd = self._run(wav_path=wav)+ self.assertIn(wav, cmd)+ self.assertNotIn("/video.mp4", cmd)+ finally:+ os.unlink(wav)++ def test_missing_wav_falls_back_to_video(self):+ cmd = self._run(wav_path="/no/such.wav")+ self.assertIn("/video.mp4", cmd)+++class ExtractWavCleanupTests(unittest.TestCase):+ def test_failed_extraction_removes_internally_created_wav(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ wav_path = os.path.join(tmpdir, "failed.wav")+ fd = os.open(wav_path, os.O_CREAT | os.O_RDWR)+ with mock.patch.object(+ audio_extract.tempfile,+ "mkstemp",+ return_value=(fd, wav_path),+ ), mock.patch.object(+ audio_extract,+ "proc_run",+ return_value=mock.Mock(returncode=1, stderr="ffmpeg failed"),+ ):+ with self.assertRaisesRegex(RuntimeError, "ffmpeg failed"):+ audio_extract.extract_wav_16k_mono("/video.mp4")++ self.assertFalse(os.path.exists(wav_path))++if __name__ == "__main__":unittest.main()diff --git a/tests/test_audio_events.py b/tests/test_audio_events.pyindex cea4e63..e3998b1 100644--- a/tests/test_audio_events.py+++ b/tests/test_audio_events.py@@ -56,6 +56,26 @@ class ComputeEventScoresTests(unittest.TestCase):self.assertEqual(scores[0], 0.0)+class DominantReactionTests(unittest.TestCase):+ def test_names_the_loudest_channel_in_range(self):+ events = [_event(3, laughter=0.2, cheering=0.8)]+ self.assertEqual(ae.dominant_reaction(events, 0, 10), "cheering")++ def test_ignores_frames_outside_the_range(self):+ events = [_event(30, laughter=0.9)]+ self.assertIsNone(ae.dominant_reaction(events, 0, 10))++ def test_speech_only_range_has_no_reaction(self):+ events = [_event(3, speech=1.0)]+ self.assertIsNone(ae.dominant_reaction(events, 0, 10))+++class ReactionTimesTests(unittest.TestCase):+ def test_only_frames_above_threshold(self):+ events = [_event(1, laughter=0.05), _event(2, cheering=0.4)]+ self.assertEqual(ae.reaction_times(events), [2])++class ProfileTests(unittest.TestCase):def test_default_is_podcast_and_llm_sourced(self):p = profiles.get_profile(None)@@ -76,5 +96,48 @@ class ProfileTests(unittest.TestCase):self.assertEqual(max(w, key=w.get), "transcript_semantic")++class WaveformFromSharedWavTests(unittest.TestCase):+ def test_reads_pre_extracted_wav_directly(self):+ import struct+ import tempfile+ import wave as wave_mod++ fd, wav_path = tempfile.mkstemp(suffix=".wav")+ os.close(fd)+ try:+ with wave_mod.open(wav_path, "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(16000)+ w.writeframes(struct.pack("<4h", 0, 16384, -16384, 0))++ waveform = ae._read_waveform_16k_mono("/nonexistent.mp4", wav_path=wav_path)+ self.assertIsNotNone(waveform)+ self.assertEqual(len(waveform), 4)+ self.assertAlmostEqual(float(waveform[1]), 0.5, places=3)+ finally:+ os.unlink(wav_path)++ def test_missing_wav_falls_back_to_extraction_path(self):+ from unittest import mock++ with mock.patch.object(ae, "proc_run", return_value=mock.Mock(returncode=1, stderr="")):+ waveform = ae._read_waveform_16k_mono("/nonexistent.mp4", wav_path="/no/such/file.wav")+ self.assertIsNone(waveform)++ def test_corrupt_wav_from_ffmpeg_returns_none(self):+ from unittest import mock++ def fake_run(cmd, **kwargs):+ # ffmpeg "succeeds" but leaves a WAV that wave.open cannot parse.+ with open(cmd[cmd.index("wav") + 1], "wb") as f:+ f.write(b"not a wav")+ return mock.Mock(returncode=0, stderr="")++ with mock.patch.object(ae, "proc_run", side_effect=fake_run):+ self.assertIsNone(ae._read_waveform_16k_mono("/nonexistent.mp4"))++if __name__ == "__main__":unittest.main()diff --git a/tests/test_batch_render.py b/tests/test_batch_render.pynew file mode 100644index 0000000..446d3b9--- /dev/null+++ b/tests/test_batch_render.py@@ -0,0 +1,111 @@+"""Tests for backend.main batch clip rendering — worker pool sizing, result+ordering, and clip_complete events for both outcomes."""++import os+import sys+import unittest+from unittest import mock++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++import main as backend_main+++def _clean_env():+ return {k: v for k, v in os.environ.items() if k != "PODCLI_RENDER_CONCURRENCY"}+++class RenderConcurrencyTests(unittest.TestCase):+ def test_env_override_wins(self):+ with mock.patch.dict(os.environ, {"PODCLI_RENDER_CONCURRENCY": "4"}):+ self.assertEqual(backend_main._render_concurrency(), 4)++ def test_env_override_floors_at_one(self):+ with mock.patch.dict(os.environ, {"PODCLI_RENDER_CONCURRENCY": "0"}):+ self.assertEqual(backend_main._render_concurrency(), 1)++ def test_invalid_env_falls_back_to_cpu_rule(self):+ with mock.patch.dict(os.environ, {"PODCLI_RENDER_CONCURRENCY": "junk"}), \+ mock.patch.object(backend_main.os, "cpu_count", return_value=16):+ self.assertEqual(backend_main._render_concurrency(), 2)++ def test_two_workers_on_big_machines(self):+ with mock.patch.dict(os.environ, _clean_env(), clear=True), \+ mock.patch.object(backend_main.os, "cpu_count", return_value=8):+ self.assertEqual(backend_main._render_concurrency(), 2)++ def test_one_worker_on_small_machines(self):+ with mock.patch.dict(os.environ, _clean_env(), clear=True), \+ mock.patch.object(backend_main.os, "cpu_count", return_value=4):+ self.assertEqual(backend_main._render_concurrency(), 1)+++class HandleBatchClipsTests(unittest.TestCase):+ def _run_batch(self, concurrency, fail_index=None, n=4):+ clips = [+ {"start_second": float(i * 100), "end_second": float(i * 100 + 30), "title": f"clip_{i}"}+ for i in range(n)+ ]+ params = {"video_path": "/video.mp4", "clips": clips}++ def fake_generate_clip(**kwargs):+ title = kwargs["title"]+ idx = int(title.rsplit("_", 1)[1])+ if fail_index is not None and idx == fail_index:+ raise RuntimeError("render exploded")+ return {+ "output_path": f"/out/{title}.mp4",+ "duration": 30.0,+ "file_size_mb": 1.0,+ "title": title,+ }++ progress_events = []+ results_holder = {}++ def capture_result(task_id, status, data=None, error=None):+ results_holder["status"] = status+ results_holder["data"] = data++ with mock.patch.dict(os.environ, {"PODCLI_RENDER_CONCURRENCY": str(concurrency)}), \+ mock.patch("services.clip_generator.generate_clip", side_effect=fake_generate_clip), \+ mock.patch.object(backend_main, "emit_progress",+ side_effect=lambda *a, **kw: progress_events.append((a, kw))), \+ mock.patch.object(backend_main, "emit_result", side_effect=capture_result):+ backend_main.handle_batch_clips("task-1", params)++ return results_holder, progress_events++ def test_results_preserve_clip_order(self):+ holder, _ = self._run_batch(concurrency=2)+ rows = holder["data"]["results"]+ self.assertEqual([r["clip_index"] for r in rows], [0, 1, 2, 3])+ self.assertEqual(holder["data"]["successful_clips"], 4)++ def test_sequential_path_matches(self):+ holder, _ = self._run_batch(concurrency=1)+ rows = holder["data"]["results"]+ self.assertEqual([r["clip_index"] for r in rows], [0, 1, 2, 3])++ def test_failed_clip_recorded_in_place(self):+ holder, _ = self._run_batch(concurrency=2, fail_index=2)+ rows = holder["data"]["results"]+ self.assertEqual(rows[2]["status"], "error")+ self.assertIn("render exploded", rows[2]["error"])+ self.assertEqual(rows[2]["start_second"], 200.0)+ self.assertEqual(holder["data"]["successful_clips"], 3)++ def test_clip_complete_emitted_for_success_and_failure(self):+ _, events = self._run_batch(concurrency=2, fail_index=1)+ complete = [kw["clip_result"] for a, kw in events if a[1] == "clip_complete"]+ self.assertEqual(len(complete), 4)+ by_index = {r["clip_index"]: r for r in complete}+ self.assertEqual(by_index[1]["status"], "error")+ self.assertEqual(by_index[0]["status"], "success")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_caption_renderer.py b/tests/test_caption_renderer.pynew file mode 100644index 0000000..fa130c4--- /dev/null+++ b/tests/test_caption_renderer.py@@ -0,0 +1,102 @@+"""Tests for backend.services.caption_renderer chunking and event volume."""++import os+import sys+import unittest++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++from services import caption_renderer as cr+from config.caption_styles import get_style+++def _word(text, start, end, speaker=None):+ return {"word": text, "start": start, "end": end, "speaker": speaker}+++def _flowing_words(texts, start=0.0, dur=0.3, speaker=None):+ words = []+ t = start+ for text in texts:+ words.append(_word(text, t, t + dur, speaker))+ t += dur+ return words+++class ChunkWordsTests(unittest.TestCase):+ def test_splits_on_word_count(self):+ words = _flowing_words(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"])+ chunks = cr._chunk_words(words, 4)+ self.assertEqual([len(c) for c in chunks], [4, 4, 2])++ def test_breaks_after_terminal_punctuation(self):+ words = _flowing_words(["That", "was", "wild.", "Then", "we", "left"])+ chunks = cr._chunk_words(words, 6)+ self.assertEqual([len(c) for c in chunks], [3, 3])+ self.assertEqual(chunks[0][-1]["word"], "wild.")++ def test_breaks_on_question_and_exclamation(self):+ words = _flowing_words(["Really?", "Yes!", "Okay"])+ chunks = cr._chunk_words(words, 6)+ self.assertEqual([len(c) for c in chunks], [1, 1, 1])++ def test_breaks_on_long_gap(self):+ words = [+ _word("before", 0.0, 0.3),+ _word("pause", 0.3, 0.6),+ _word("after", 1.6, 1.9), # 1.0s gap+ ]+ chunks = cr._chunk_words(words, 6)+ self.assertEqual([len(c) for c in chunks], [2, 1])++ def test_short_gap_does_not_break(self):+ words = [+ _word("quick", 0.0, 0.3),+ _word("pause", 0.9, 1.2), # 0.6s gap+ ]+ chunks = cr._chunk_words(words, 6)+ self.assertEqual([len(c) for c in chunks], [2])++ def test_breaks_on_speaker_change(self):+ words = (+ _flowing_words(["so", "anyway"], start=0.0, speaker="SPEAKER_00")+ + _flowing_words(["totally", "agree"], start=0.6, speaker="SPEAKER_01")+ )+ chunks = cr._chunk_words(words, 6)+ self.assertEqual([len(c) for c in chunks], [2, 2])+ self.assertEqual(chunks[1][0]["word"], "totally")++ def test_missing_speaker_labels_do_not_break(self):+ words = _flowing_words(["one", "two", "three"])+ self.assertEqual(len(cr._chunk_words(words, 6)), 1)++ def test_empty_words(self):+ self.assertEqual(cr._chunk_words([], 4), [])+++class BrandedEventVolumeTests(unittest.TestCase):+ def test_events_are_linear_in_word_count(self):+ style = get_style("branded")+ chunk_size = style.get("words_per_chunk", 6)+ words = _flowing_words(["word"] * chunk_size)+ content = cr._render_branded(words, style, 0.0)+ dialogue_count = content.count("Dialogue:")+ # One text event per word for the chunk span + one pill per word.+ self.assertEqual(dialogue_count, 2 * chunk_size)++ def test_text_events_span_the_whole_chunk(self):+ style = get_style("branded")+ words = _flowing_words(["alpha", "beta", "gamma"])+ content = cr._render_branded(words, style, 0.0)+ layer1 = [l for l in content.splitlines() if l.startswith("Dialogue: 1,")]+ starts = {l.split(",")[1] for l in layer1}+ ends = {l.split(",")[2] for l in layer1}+ self.assertEqual(len(starts), 1)+ self.assertEqual(len(ends), 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_claude_suggest_helpers.py b/tests/test_claude_suggest_helpers.pyindex 705b9f5..0e0246a 100644--- a/tests/test_claude_suggest_helpers.py+++ b/tests/test_claude_suggest_helpers.py@@ -188,5 +188,76 @@ class SliceSegmentsTests(unittest.TestCase):self.assertEqual(cs._slice_segments_for_range(segments, 0, 50), [])++class ReactionAnchorPromptTests(unittest.TestCase):+ def test_empty_or_none_returns_empty(self):+ self.assertEqual(cs._format_reaction_anchors(None), "")+ self.assertEqual(cs._format_reaction_anchors([]), "")++ def test_anchors_are_sorted_deduped_and_formatted(self):+ block = cs._format_reaction_anchors([120.34, 12.31, 12.34])+ self.assertIn("AUDIENCE REACTION ANCHORS", block)+ self.assertIn("12.3s", block)+ self.assertIn("120.3s", block)+ self.assertEqual(block.count("12.3s, 120.3s"), 1) # deduped and ascending++ def test_anchor_count_is_capped(self):+ import re+ block = cs._format_reaction_anchors([float(t) for t in range(200)])+ self.assertEqual(len(re.findall(r"\d+\.\ds", block)), cs.MAX_REACTION_ANCHORS)+++class BlendSignalScoresTests(unittest.TestCase):+ def _clips(self):+ return [+ {"start_second": 0.0, "end_second": 10.0, "score": 16, "reasons": ["hot_take"]},+ {"start_second": 100.0, "end_second": 120.0, "score": 12, "reasons": []},+ ]++ def _events(self):+ return [+ {"time": 5.0, "laughter": 0.5, "cheering": 0.0, "screaming": 0.0, "speech": 0.2},+ ]++ def test_no_signals_is_a_noop(self):+ clips = self._clips()+ out = cs.blend_signal_scores(clips, energy_data=None, events_data=None)+ self.assertEqual(out[0]["score"], 16)+ self.assertNotIn("signal_boost", out[0])++ def test_reaction_peak_boosts_only_covering_clip(self):+ clips = cs.blend_signal_scores(self._clips(), events_data=self._events())+ self.assertGreater(clips[0]["score"], 16)+ self.assertEqual(clips[1]["score"], 12)+ self.assertNotIn("signal_boost", clips[1])++ def test_ai_score_stays_primary(self):+ # Even a maxed-out reaction+energy signal adds at most 3 points.+ clips = [{"start_second": 0.0, "end_second": 10.0, "score": 12}]+ events = [{"time": 5.0, "laughter": 1.0, "cheering": 0.0, "screaming": 0.0, "speech": 0.0}]+ energy = [{"time": float(t), "rms_db": -30.0} for t in range(0, 60)] + [{"time": 5.0, "rms_db": 0.0}]+ out = cs.blend_signal_scores(clips, energy_data=energy, events_data=events)+ self.assertLessEqual(out[0]["score"], 15.0)++ def test_deterministic(self):+ a = cs.blend_signal_scores(self._clips(), events_data=self._events())+ b = cs.blend_signal_scores(self._clips(), events_data=self._events())+ self.assertEqual(a, b)++ def test_order_preserved(self):+ clips = cs.blend_signal_scores(self._clips(), events_data=self._events())+ self.assertEqual([c["start_second"] for c in clips], [0.0, 100.0])++ def test_strong_laugh_tagged_in_reasons(self):+ clips = cs.blend_signal_scores(self._clips(), events_data=self._events())+ self.assertIn("laughter", clips[0]["reasons"])++ def test_crowd_cheer_is_not_tagged_as_laughter(self):+ events = [{"time": 5.0, "laughter": 0.0, "cheering": 0.5, "screaming": 0.0, "speech": 0.2}]+ clips = cs.blend_signal_scores(self._clips(), events_data=events)+ self.assertIn("cheering", clips[0]["reasons"])+ self.assertNotIn("laughter", clips[0]["reasons"])++if __name__ == "__main__":unittest.main()diff --git a/tests/test_cli.py b/tests/test_cli.pynew file mode 100644index 0000000..16e1a7e--- /dev/null+++ b/tests/test_cli.py@@ -0,0 +1,157 @@+import argparse+import json+import os+import sys+import tempfile+import unittest+from unittest import mock+++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++import cli as cli_mod+++FACE_MAP = {+ "is_split_screen": True,+ "is_mixed_layout": True,+ "clusters": [{"center_x": 1148}, {"center_x": 2949}],+}++SRT = """1+00:00:00,000 --> 00:00:04,000+Hello and welcome to the show.++2+00:00:04,500 --> 00:00:08,000+Today we talk about split screens.+"""+++def _process_args(video_path, transcript_path, output_dir):+ return argparse.Namespace(+ video=video_path,+ transcript=transcript_path,+ top=1,+ output=output_dir,+ preset=None,+ engine=None,+ assemblyai_api_key=None,+ fast=False,+ thumbnails=False,+ caption_style=None,+ crop=None,+ format=None,+ profile=None,+ logo=None,+ outro=None,+ no_outro=True,+ intro=None,+ time_adjust=None,+ no_energy=True,+ no_speakers=False,+ no_cache=True,+ no_resume=True,+ quality=None,+ allow_ass_fallback=False,+ review_each=False,+ post_review=False,+ )+++class CliTranscriptTests(unittest.TestCase):+ def _run_process(self, transcript_text, cached_transcript=None):+ """Run cmd_process with --transcript and return the generate_clip mock."""+ clip = {+ "title": "Test clip",+ "start_second": 0.0,+ "end_second": 0.5,+ "duration": 0.5,+ }++ with tempfile.TemporaryDirectory() as temp_dir:+ video_path = os.path.join(temp_dir, "episode.mp4")+ transcript_path = os.path.join(temp_dir, "transcript")+ output_dir = os.path.join(temp_dir, "clips")+ with open(video_path, "wb") as video_file:+ video_file.write(b"video")+ with open(transcript_path, "w", encoding="utf-8") as transcript_file:+ transcript_file.write(transcript_text)++ generated = {+ "output_path": os.path.join(output_dir, "test-clip.mp4"),+ "file_size_mb": 1.0,+ }++ with (+ mock.patch.object(cli_mod, "kb_is_empty", return_value=False),+ mock.patch(+ "services.encoder.get_encoder_info",+ return_value={"best": "mock", "system": "test"},+ ),+ mock.patch("services.asset_store.default_intro", return_value=None),+ mock.patch("services.corrections.apply_corrections"),+ mock.patch(+ "services.claude_suggest._find_ai_cli",+ return_value=(None, None),+ ),+ mock.patch(+ "services.transcript_packer.load_cached_transcript_for_video",+ return_value=cached_transcript,+ ),+ mock.patch.object(cli_mod, "_suggest_clips", return_value=[clip]),+ mock.patch.object(cli_mod, "_review_clips", return_value=[clip]),+ mock.patch.object(+ cli_mod, "_should_enter_post_render_loop", return_value=False+ ),+ mock.patch(+ "services.clip_generator.generate_clip",+ return_value=generated,+ ) as generate_clip,+ ):+ cli_mod.cmd_process(_process_args(video_path, transcript_path, output_dir))++ generate_clip.assert_called_once()+ return generate_clip++ def test_json_transcript_face_map_reaches_clip_generator(self):+ payload = {+ "words": [{"word": "hello", "start": 0.0, "end": 0.5}],+ "segments": [{"start": 0.0, "end": 0.5, "text": "hello"}],+ "face_map": FACE_MAP,+ }++ generate_clip = self._run_process(json.dumps(payload))++ self.assertEqual(generate_clip.call_args.kwargs["face_map"], FACE_MAP)++ def test_srt_transcript_recovers_cached_face_map(self):+ generate_clip = self._run_process(+ SRT, cached_transcript={"words": [], "segments": [], "face_map": FACE_MAP}+ )++ self.assertEqual(generate_clip.call_args.kwargs["face_map"], FACE_MAP)++ def test_srt_transcript_without_cache_degrades_to_no_face_map(self):+ generate_clip = self._run_process(SRT, cached_transcript=None)++ self.assertIsNone(generate_clip.call_args.kwargs["face_map"])++ def test_json_transcript_face_map_wins_over_cache(self):+ payload = {+ "words": [{"word": "hello", "start": 0.0, "end": 0.5}],+ "segments": [{"start": 0.0, "end": 0.5, "text": "hello"}],+ "face_map": FACE_MAP,+ }+ stale = {"words": [], "segments": [], "face_map": {"is_split_screen": False}}++ generate_clip = self._run_process(json.dumps(payload), cached_transcript=stale)++ self.assertEqual(generate_clip.call_args.kwargs["face_map"], FACE_MAP)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_cli_helpers.py b/tests/test_cli_helpers.pynew file mode 100644index 0000000..047f67a--- /dev/null+++ b/tests/test_cli_helpers.py@@ -0,0 +1,57 @@+"""Tests for backend.cli helpers: the shared WAV cache and Studio port resolution."""++import os+import sys+import tempfile+import unittest+from unittest import mock++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++import cli as cli_mod+from services import audio_extract+++class SharedWavTests(unittest.TestCase):+ def test_successful_extraction_is_reused(self):+ fd, wav_path = tempfile.mkstemp(suffix=".wav")+ os.close(fd)+ try:+ with mock.patch.object(+ audio_extract, "extract_wav_16k_mono", return_value=wav_path+ ) as extract:+ shared = cli_mod._SharedWav("/video.mp4")+ self.assertEqual(shared.get(), wav_path)+ self.assertEqual(shared.get(), wav_path)+ self.assertEqual(extract.call_count, 1)+ finally:+ if os.path.exists(wav_path):+ os.unlink(wav_path)++ def test_failed_extraction_is_attempted_once(self):+ with mock.patch.object(+ audio_extract, "extract_wav_16k_mono", side_effect=RuntimeError("decode failed")+ ) as extract:+ shared = cli_mod._SharedWav("/video.mp4")+ for _ in range(4):+ self.assertIsNone(shared.get())++ self.assertEqual(extract.call_count, 1)+ self.assertIsInstance(shared.error, RuntimeError)++ def test_empty_result_is_treated_as_failure(self):+ with mock.patch.object(+ audio_extract, "extract_wav_16k_mono", return_value=None+ ) as extract:+ shared = cli_mod._SharedWav("/video.mp4")+ self.assertIsNone(shared.get())+ self.assertIsNone(shared.get())++ self.assertEqual(extract.call_count, 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_clip_generator.py b/tests/test_clip_generator.pyindex 814d414..2aca949 100644--- a/tests/test_clip_generator.py+++ b/tests/test_clip_generator.py@@ -1,8 +1,11 @@import os+import shutilimport subprocessimport sysimport tempfile+import threadingimport unittest+from concurrent.futures import ThreadPoolExecutorfrom unittest import mock@@ -158,5 +161,108 @@ class ClipGeneratorTests(unittest.TestCase):self.assertEqual(replace_mock.call_count, 2)++class TransitionAutofixGatingTests(unittest.TestCase):+ def test_multi_segment_cut_can_jump(self):+ self.assertTrue(cg._reframe_can_jump(+ reframe=True, crop_strategy="face",+ keep_segments=[{"start": 0, "end": 5}, {"start": 8, "end": 12}],+ ))++ def test_non_reframe_format_cannot_jump(self):+ self.assertFalse(cg._reframe_can_jump(reframe=False, crop_strategy="face"))++ def test_center_crop_cannot_jump(self):+ self.assertFalse(cg._reframe_can_jump(reframe=True, crop_strategy="center"))++ def test_face_follow_can_jump_without_speaker_labels(self):+ # whisper.cpp (the default engine) skips diarization, so the tracker+ # still snaps between faces with every word unlabeled.+ self.assertTrue(cg._reframe_can_jump(reframe=True, crop_strategy="face"))++ def test_speaker_strategies_can_jump(self):+ self.assertTrue(cg._reframe_can_jump(reframe=True, crop_strategy="speaker"))+ self.assertTrue(cg._reframe_can_jump(reframe=True, crop_strategy="speaker-hardcut"))++ def test_manual_crop_jumps_only_with_multiple_keyframes(self):+ self.assertFalse(cg._reframe_can_jump(+ reframe=True, crop_strategy="manual", crop_keyframes=[{"t": 0, "x_pct": 50}],+ ))+ self.assertTrue(cg._reframe_can_jump(+ reframe=True, crop_strategy="manual",+ crop_keyframes=[{"t": 0, "x_pct": 20}, {"t": 3, "x_pct": 80}],+ ))++ def test_default_engine_face_crop_runs_autofix(self):+ env = {k: v for k, v in os.environ.items() if k != "PODCLI_TRANSITION_AUTOFIX_PASSES"}+ with mock.patch.dict(os.environ, env, clear=True):+ passes = cg._transition_autofix_passes(+ cg._reframe_can_jump(reframe=True, crop_strategy="face", crop_keyframes=None)+ )+ self.assertEqual(passes, 2)++ def test_default_passes_gated_by_jump_potential(self):+ env = {k: v for k, v in os.environ.items() if k != "PODCLI_TRANSITION_AUTOFIX_PASSES"}+ with mock.patch.dict(os.environ, env, clear=True):+ self.assertEqual(cg._transition_autofix_passes(True), 2)+ self.assertEqual(cg._transition_autofix_passes(False), 0)++ def test_env_override_wins(self):+ with mock.patch.dict(os.environ, {"PODCLI_TRANSITION_AUTOFIX_PASSES": "1"}):+ self.assertEqual(cg._transition_autofix_passes(False), 1)+ self.assertEqual(cg._transition_autofix_passes(True), 1)+ with mock.patch.dict(os.environ, {"PODCLI_TRANSITION_AUTOFIX_PASSES": "0"}):+ self.assertEqual(cg._transition_autofix_passes(True), 0)++ def test_env_override_is_clamped_and_validated(self):+ with mock.patch.dict(os.environ, {"PODCLI_TRANSITION_AUTOFIX_PASSES": "9"}):+ self.assertEqual(cg._transition_autofix_passes(False), 2)+ with mock.patch.dict(os.environ, {"PODCLI_TRANSITION_AUTOFIX_PASSES": "junk"}):+ self.assertEqual(cg._transition_autofix_passes(True), 2)+++class OutputPathReservationTests(unittest.TestCase):+ def setUp(self):+ self.tmpdir = tempfile.mkdtemp(prefix="podcli-output-test-")+ cg._reserved_output_paths.clear()+ self.addCleanup(cg._reserved_output_paths.clear)+ self.addCleanup(shutil.rmtree, self.tmpdir, ignore_errors=True)++ def test_duplicate_title_gets_a_suffix(self):+ first = cg._reserve_output_path(self.tmpdir, "same_title_short", ".mp4")+ second = cg._reserve_output_path(self.tmpdir, "same_title_short", ".mp4")+ third = cg._reserve_output_path(self.tmpdir, "same_title_short", ".mp4")+ self.assertEqual(os.path.basename(first), "same_title_short.mp4")+ self.assertEqual(os.path.basename(second), "same_title_short-2.mp4")+ self.assertEqual(os.path.basename(third), "same_title_short-3.mp4")++ def test_concurrent_renders_of_one_title_never_share_a_file(self):+ barrier = threading.Barrier(8)++ def render(i):+ barrier.wait()+ path = cg._reserve_output_path(self.tmpdir, "duplicate_short", ".mp4")+ with open(path, "w", encoding="utf-8") as f:+ f.write(f"clip-{i}")+ return path++ with ThreadPoolExecutor(max_workers=8) as pool:+ paths = list(pool.map(render, range(8)))++ self.assertEqual(len(set(paths)), 8)+ contents = []+ for p in paths:+ self.assertTrue(os.path.exists(p))+ with open(p, encoding="utf-8") as f:+ contents.append(f.read())+ self.assertEqual(len(set(contents)), 8)++ def test_sidecar_paths_inherit_the_unique_stem(self):+ cg._reserve_output_path(self.tmpdir, "same_title_short", ".mp4")+ second = cg._reserve_output_path(self.tmpdir, "same_title_short", ".mp4")+ base, _ = os.path.splitext(second)+ self.assertTrue(base.endswith("same_title_short-2"))++if __name__ == "__main__":unittest.main()diff --git a/tests/test_first_run_setup.py b/tests/test_first_run_setup.pynew file mode 100644index 0000000..ebd766e--- /dev/null+++ b/tests/test_first_run_setup.py@@ -0,0 +1,245 @@+import os+import sys+import tempfile+import unittest+from unittest import mock++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++import cli as cli_mod+from services import knowledge_base as kb++ANSWERS = {+ "show_name": "Deep Tech Weekly",+ "hosts": "Nika, Sandro",+ "audience": "Founders building hard tech",+ "language": "English",+ "format": "Interview, 60 min, weekly",+ "voice": "blunt, curious, technical",+}+++class RenderTests(unittest.TestCase):+ def test_brand_identity_carries_every_answer(self):+ out = cli_mod._render_brand_identity(ANSWERS)+ self.assertIn("- Name: Deep Tech Weekly", out)+ self.assertIn("- Nika", out)+ self.assertIn("- Sandro", out)+ self.assertIn("Founders building hard tech", out)+ self.assertIn("- Language: English", out)+ self.assertIn("- Format: Interview, 60 min, weekly", out)++ def test_voice_file_carries_voice_and_hosts(self):+ out = cli_mod._render_voice_and_tone(ANSWERS)+ self.assertIn("blunt, curious, technical", out)+ self.assertIn("Nika and Sandro", out)+ self.assertIn("Banned words", out)++ def test_missing_hosts_do_not_break_rendering(self):+ answers = dict(ANSWERS, hosts="")+ self.assertIn("Deep Tech Weekly", cli_mod._render_brand_identity(answers))+ self.assertIn("a host", cli_mod._render_voice_and_tone(answers))+++class GatingTests(unittest.TestCase):+ def setUp(self):+ self.home = tempfile.TemporaryDirectory()+ self.addCleanup(self.home.cleanup)+ patcher = mock.patch.dict(+ cli_mod.paths,+ {"home": self.home.name, "knowledge": os.path.join(self.home.name, "knowledge")},+ )+ patcher.start()+ self.addCleanup(patcher.stop)+ env = mock.patch.dict(os.environ, {}, clear=False)+ env.start()+ self.addCleanup(env.stop)+ os.environ.pop("PODCLI_NO_ONBOARDING", None)++ def test_needs_onboarding_on_a_fresh_tty(self):+ with mock.patch.object(sys.stdin, "isatty", return_value=True), \+ mock.patch.object(sys.stdout, "isatty", return_value=True):+ self.assertTrue(cli_mod._needs_onboarding())++ def test_non_tty_never_onboards(self):+ with mock.patch.object(sys.stdin, "isatty", return_value=False), \+ mock.patch.object(sys.stdout, "isatty", return_value=True):+ self.assertFalse(cli_mod._needs_onboarding())++ def test_marker_stops_the_wizard(self):+ cli_mod._mark_onboarded()+ self.assertTrue(os.path.exists(os.path.join(self.home.name, ".onboarded")))+ with mock.patch.object(sys.stdin, "isatty", return_value=True), \+ mock.patch.object(sys.stdout, "isatty", return_value=True):+ self.assertFalse(cli_mod._needs_onboarding())++ def test_env_opt_out(self):+ with mock.patch.dict(os.environ, {"PODCLI_NO_ONBOARDING": "1"}), \+ mock.patch.object(sys.stdin, "isatty", return_value=True), \+ mock.patch.object(sys.stdout, "isatty", return_value=True):+ self.assertFalse(cli_mod._needs_onboarding())++ def test_existing_knowledge_base_skips_the_wizard_and_marks_it_done(self):+ kb_dir = os.path.join(self.home.name, "knowledge")+ os.makedirs(kb_dir)+ with open(os.path.join(kb_dir, "01-brand-identity.md"), "w", encoding="utf-8") as f:+ f.write("# Brand identity\n\n- Name: Deep Tech Weekly\n")++ with mock.patch.object(cli_mod, "cmd_knowledge") as init:+ cli_mod._first_run_setup()++ init.assert_not_called()+ self.assertTrue(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_readme_only_knowledge_base_still_runs_the_wizard(self):+ kb_dir = os.path.join(self.home.name, "knowledge")+ os.makedirs(kb_dir)+ with open(os.path.join(kb_dir, "README.md"), "w", encoding="utf-8") as f:+ f.write("# Knowledge base\n")+ self.assertTrue(kb.is_empty(kb_dir))++ def test_cancelling_the_wizard_fails_instead_of_silently_skipping_the_command(self):+ with mock.patch.object(sys, "argv", ["podcli", "info"]), \+ mock.patch.object(cli_mod, "_auto_migrate_cli"), \+ mock.patch.object(cli_mod, "_needs_onboarding", return_value=True), \+ mock.patch.object(cli_mod, "_first_run_setup", return_value=False) as setup, \+ mock.patch.object(cli_mod, "cmd_info") as info:+ with self.assertRaises(SystemExit) as exit_ctx:+ cli_mod.main()++ self.assertEqual(exit_ctx.exception.code, 130)+ setup.assert_called_once_with()+ info.assert_not_called()++ def test_completed_wizard_dispatches_the_requested_command(self):+ with mock.patch.object(sys, "argv", ["podcli", "info"]), \+ mock.patch.object(cli_mod, "_auto_migrate_cli"), \+ mock.patch.object(cli_mod, "_needs_onboarding", return_value=True), \+ mock.patch.object(cli_mod, "_first_run_setup", return_value=True), \+ mock.patch.object(cli_mod, "cmd_info") as info:+ cli_mod.main()++ info.assert_called_once()+++CTRL_D = object()+++def _reply(value):+ def ask():+ if value is CTRL_D:+ raise EOFError+ return value+ return ask+++def _answering(confirm, answers, choice):+ """Drive questionary through a wizard run without a terminal."""+ replies = iter(answers)+ return [+ mock.patch("questionary.confirm", return_value=mock.Mock(ask=_reply(confirm))),+ mock.patch("questionary.text", side_effect=lambda *a, **k: mock.Mock(ask=_reply(next(replies)))),+ mock.patch("questionary.select", return_value=mock.Mock(ask=_reply(choice))),+ ]+++class WizardRunTests(unittest.TestCase):+ def setUp(self):+ self.home = tempfile.TemporaryDirectory()+ self.addCleanup(self.home.cleanup)+ self.kb_dir = os.path.join(self.home.name, "knowledge")+ patcher = mock.patch.dict(+ cli_mod.paths, {"home": self.home.name, "knowledge": self.kb_dir}+ )+ patcher.start()+ self.addCleanup(patcher.stop)++ def _run(self, confirm=True, answers=None, choice="later"):+ answers = answers if answers is not None else [+ ANSWERS["show_name"], ANSWERS["hosts"], ANSWERS["audience"],+ ANSWERS["language"], ANSWERS["format"], ANSWERS["voice"],+ ]+ patches = _answering(confirm, answers, choice)+ for p in patches:+ p.start()+ try:+ return cli_mod._first_run_setup()+ finally:+ for p in patches:+ p.stop()++ def test_wizard_writes_answers_and_the_remaining_templates(self):+ result = self._run()++ self.assertTrue(result)+ created = sorted(os.listdir(self.kb_dir))+ self.assertEqual(len(created), 14)++ with open(os.path.join(self.kb_dir, "01-brand-identity.md"), encoding="utf-8") as f:+ brand = f.read()+ self.assertIn("Deep Tech Weekly", brand)+ self.assertFalse(kb.is_unfilled_template(brand, "01-brand-identity.md"))++ context = kb.load_kb_context([("01-brand-identity.md", 4000)], self.kb_dir)+ self.assertIn("Deep Tech Weekly", context)+ self.assertTrue(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_declining_marks_it_done_and_writes_nothing(self):+ result = self._run(confirm=False)++ self.assertTrue(result)+ self.assertFalse(os.path.isdir(self.kb_dir))+ self.assertTrue(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_empty_show_name_writes_nothing(self):+ result = self._run(answers=["", "", "", "", "", ""])++ self.assertTrue(result)+ self.assertFalse(os.path.isdir(self.kb_dir))+ self.assertTrue(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_cancelling_setup_confirmation_returns_false(self):+ result = self._run(confirm=None)++ self.assertFalse(result)+ self.assertFalse(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_cancelling_a_setup_question_returns_false(self):+ result = self._run(answers=[ANSWERS["show_name"], None])++ self.assertFalse(result)+ self.assertFalse(os.path.isdir(self.kb_dir))+ self.assertFalse(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_cancelling_next_step_returns_false(self):+ result = self._run(choice=None)++ self.assertFalse(result)+ self.assertTrue(os.path.isdir(self.kb_dir))+ self.assertFalse(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_eof_at_the_confirmation_declines_without_crashing(self):+ result = self._run(confirm=CTRL_D)++ self.assertTrue(result)+ self.assertFalse(os.path.isdir(self.kb_dir))+ self.assertTrue(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_eof_mid_wizard_cancels_without_crashing(self):+ result = self._run(answers=[ANSWERS["show_name"], CTRL_D])++ self.assertFalse(result)+ self.assertFalse(os.path.exists(os.path.join(self.home.name, ".onboarded")))++ def test_eof_at_the_next_step_cancels_without_crashing(self):+ result = self._run(choice=CTRL_D)++ self.assertFalse(result)+ self.assertFalse(os.path.exists(os.path.join(self.home.name, ".onboarded")))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_knowledge_context.py b/tests/test_knowledge_context.pynew file mode 100644index 0000000..0583d05--- /dev/null+++ b/tests/test_knowledge_context.py@@ -0,0 +1,194 @@+import io+import os+import sys+import tempfile+import unittest+from contextlib import redirect_stderr++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++from services import knowledge_base as kb++TEMPLATE_DIR = os.path.join(BACKEND_ROOT, "templates", "knowledge")++# Every file the clip-scoring and title/description prompts inline.+PROMPT_TEMPLATES = [+ "00-master-instructions.md",+ "01-brand-identity.md",+ "02-voice-and-tone.md",+ "04-shorts-creation-guide.md",+ "05-title-formulas.md",+ "06-descriptions-template.md",+ "07-thumbnail-guide.md",+ "08-topics-themes.md",+ "11-inspiration-channels.md",+ "12-quick-reference.md",+]++FILLED_BRAND_IDENTITY = """# Brand identity++## Show++- Name: Deep Tech Weekly+- One-line positioning: For founders building hard tech, the messy parts nobody posts about.+- Format: Interview, 60 minutes, weekly on Thursday.+- Language: English, some Georgian slang from the hosts.++## Hosts++| Host | Role | Voice in one line |+|------|------|-------------------|+| Nika | Host | Asks the blunt question everyone else skips |+| Sandro | Co-host | Pushes back with numbers |++## Audience++- Who watches: 25-40, founders and engineers, mostly pre-seed to Series A.+- Why they watch: they want the operator detail, not the keynote version.+- Where they watch: YouTube long-form, Shorts, and TikTok.++## Promise++Every episode should leave the viewer with one decision they can make differently on Monday.++## What this show is not++We do not do news recaps and we do not do guest promo hours.+"""++FILLED_QUICK_REFERENCE = """# Quick reference++## Links++- Show: youtube.com/@deeptechweekly+- Website: deeptechweekly.com++## Boilerplate++- Guest intro line: "This week [guest] joins us to break down what actually shipped."+- Sponsor disclosure: "This episode is sponsored by Acme."++## Hashtag sets++- Default: #startups #deeptech #founders+"""+++class UnfilledTemplateTests(unittest.TestCase):+ def test_shipped_templates_are_detected_as_unfilled(self):+ for name in PROMPT_TEMPLATES:+ with open(os.path.join(TEMPLATE_DIR, name), encoding="utf-8") as f:+ content = f.read()+ with self.subTest(template=name):+ self.assertTrue(kb.is_unfilled_template(content, name))++ def test_every_shipped_template_is_unfilled_by_identity(self):+ for name in sorted(os.listdir(TEMPLATE_DIR)):+ with open(os.path.join(TEMPLATE_DIR, name), encoding="utf-8") as f:+ content = f.read()+ with self.subTest(template=name):+ self.assertTrue(kb.is_unfilled_template(content, name))++ def test_barely_touched_template_is_still_unfilled(self):+ with open(os.path.join(TEMPLATE_DIR, "01-brand-identity.md"), encoding="utf-8") as f:+ content = f.read().replace("[Show name]", "Deep Tech Weekly")+ self.assertTrue(kb.is_unfilled_template(content, "01-brand-identity.md"))+ self.assertTrue(kb.is_unfilled_template(content))++ def test_filled_files_are_kept(self):+ self.assertFalse(kb.is_unfilled_template(FILLED_BRAND_IDENTITY, "01-brand-identity.md"))+ self.assertFalse(kb.is_unfilled_template(FILLED_QUICK_REFERENCE, "12-quick-reference.md"))++ def test_filled_file_keeps_a_few_legitimate_brackets(self):+ content = FILLED_QUICK_REFERENCE + "\n- Chapter marker: [00:00] intro\n- Guest tag: [guest]\n"+ self.assertFalse(kb.is_unfilled_template(content, "12-quick-reference.md"))++ def test_empty_file_is_unfilled(self):+ self.assertTrue(kb.is_unfilled_template(" \n\n", "01-brand-identity.md"))++ def test_wizard_output_is_not_flagged_as_a_template(self):+ import cli as cli_mod++ answers = {+ "show_name": "Deep Tech Weekly",+ "hosts": "Nika, Sandro",+ "audience": "Founders building hard tech",+ "language": "English",+ "format": "Interview, 60 min, weekly",+ "voice": "blunt, curious, technical",+ }+ self.assertFalse(+ kb.is_unfilled_template(cli_mod._render_brand_identity(answers), "01-brand-identity.md")+ )+ self.assertFalse(+ kb.is_unfilled_template(cli_mod._render_voice_and_tone(answers), "02-voice-and-tone.md")+ )+++class LoadContextTests(unittest.TestCase):+ def test_unfilled_templates_never_reach_the_prompt(self):+ with tempfile.TemporaryDirectory() as kb_dir:+ for name in ("01-brand-identity.md", "02-voice-and-tone.md"):+ with open(os.path.join(TEMPLATE_DIR, name), encoding="utf-8") as src:+ with open(os.path.join(kb_dir, name), "w", encoding="utf-8") as dst:+ dst.write(src.read())+ context = kb.load_kb_context(+ [("01-brand-identity.md", 4000), ("02-voice-and-tone.md", 4000)], kb_dir+ )+ self.assertEqual(context, "")++ def test_filled_file_is_inlined_and_truncated(self):+ with tempfile.TemporaryDirectory() as kb_dir:+ with open(os.path.join(kb_dir, "01-brand-identity.md"), "w", encoding="utf-8") as f:+ f.write(FILLED_BRAND_IDENTITY)+ context = kb.load_kb_context([("01-brand-identity.md", 4000)], kb_dir)+ self.assertIn("--- 01-brand-identity.md ---", context)+ self.assertIn("Deep Tech Weekly", context)++ short = kb.load_kb_context([("01-brand-identity.md", 20)], kb_dir)+ self.assertLess(len(short), len(context))++ def test_missing_dir_yields_no_context(self):+ self.assertEqual(kb.load_kb_context([("01-brand-identity.md", 100)], "/nope/nowhere"), "")+++class EmptinessTests(unittest.TestCase):+ def test_readme_only_counts_as_empty(self):+ with tempfile.TemporaryDirectory() as kb_dir:+ with open(os.path.join(kb_dir, "README.md"), "w", encoding="utf-8") as f:+ f.write("# Knowledge base\n")+ self.assertEqual(kb.kb_files(kb_dir), [])+ self.assertTrue(kb.is_empty(kb_dir))++ with open(os.path.join(kb_dir, "01-brand-identity.md"), "w", encoding="utf-8") as f:+ f.write(FILLED_BRAND_IDENTITY)+ self.assertEqual(kb.kb_files(kb_dir), ["01-brand-identity.md"])+ self.assertFalse(kb.is_empty(kb_dir))++ def test_missing_dir_is_empty(self):+ self.assertTrue(kb.is_empty("/nope/nowhere"))+++class WarningTests(unittest.TestCase):+ def setUp(self):+ kb._warned = False++ def tearDown(self):+ kb._warned = False++ def test_warns_once_per_run(self):+ buf = io.StringIO()+ with redirect_stderr(buf):+ kb.warn_missing_context("clip scoring")+ kb.warn_missing_context("clip scoring")+ out = buf.getvalue()+ self.assertEqual(out.count("Warning:"), 1)+ self.assertIn("clip scoring", out)+ self.assertIn("podcli knowledge init", out)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_knowledge_init.py b/tests/test_knowledge_init.pynew file mode 100644index 0000000..1e99a38--- /dev/null+++ b/tests/test_knowledge_init.py@@ -0,0 +1,50 @@+import os+import subprocess+import sys+import tempfile+import unittest++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))++TEMPLATE_DIR = os.path.join(ROOT, "backend", "templates", "knowledge")+EXPECTED = [f"{i:02d}" for i in range(14)]+++def run_init(home):+ env = dict(os.environ, PODCLI_HOME=home)+ return subprocess.run(+ [sys.executable, os.path.join(ROOT, "backend", "cli.py"), "knowledge", "init"],+ capture_output=True,+ text=True,+ env=env,+ timeout=60,+ )+++class KnowledgeInitTests(unittest.TestCase):+ def test_templates_ship_all_fourteen_files(self):+ names = sorted(os.listdir(TEMPLATE_DIR))+ self.assertEqual([n[:2] for n in names], EXPECTED)++ def test_init_creates_templates_and_never_overwrites(self):+ with tempfile.TemporaryDirectory() as home:+ result = run_init(home)+ self.assertEqual(result.returncode, 0, result.stderr)+ kb_dir = os.path.join(home, "knowledge")+ created = sorted(os.listdir(kb_dir))+ self.assertEqual(len(created), 14)++ marker = os.path.join(kb_dir, "01-brand-identity.md")+ with open(marker, "w", encoding="utf-8") as f:+ f.write("user content")+ os.remove(os.path.join(kb_dir, "13-learnings.md"))++ result = run_init(home)+ self.assertEqual(result.returncode, 0, result.stderr)+ with open(marker, encoding="utf-8") as f:+ self.assertEqual(f.read(), "user content")+ self.assertIn("1 created, 13 kept", result.stdout + result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_saliency.py b/tests/test_saliency.pyindex 8ed1e3f..9ab6d96 100644--- a/tests/test_saliency.py+++ b/tests/test_saliency.py@@ -159,5 +159,54 @@ class PooledTests(unittest.TestCase):self.assertEqual(len(pooled), 3)++class PrecomputedProfilesTests(unittest.TestCase):+ def test_precomputed_energy_and_events_skip_extraction(self):+ energy = [+ {"time": float(t), "rms_db": -5.0 if 28 <= t <= 32 else -30.0}+ for t in range(120)+ ]+ events = [{"time": 30.0, "laughter": 0.5, "cheering": 0.0, "screaming": 0.0, "speech": 0.0}]++ def _boom(*args, **kwargs):+ raise AssertionError("source audio must not be re-extracted")++ orig_energy, orig_events = sal.extract_audio_energy, sal.extract_audio_events+ sal.extract_audio_energy, sal.extract_audio_events = _boom, _boom+ try:+ clips = sal.detect_highlights(+ "/nonexistent.mp4",+ profile_name="party",+ energy_data=energy,+ events_data=events,+ min_dur=8.0,+ max_dur=30.0,+ )+ finally:+ sal.extract_audio_energy, sal.extract_audio_events = orig_energy, orig_events++ self.assertTrue(clips)+ self.assertTrue(any("reaction" in c["reasons"] for c in clips))++ def test_empty_events_list_counts_as_precomputed(self):+ energy = [{"time": float(t), "rms_db": -30.0} for t in range(60)]++ def _boom(*args, **kwargs):+ raise AssertionError("events must not be re-extracted")++ orig_events = sal.extract_audio_events+ sal.extract_audio_events = _boom+ try:+ clips = sal.detect_highlights(+ "/nonexistent.mp4",+ profile_name="party",+ energy_data=energy,+ events_data=[],+ )+ finally:+ sal.extract_audio_events = orig_events+ self.assertIsInstance(clips, list)++if __name__ == "__main__":unittest.main()diff --git a/tests/test_server_port.py b/tests/test_server_port.pynew file mode 100644index 0000000..1944764--- /dev/null+++ b/tests/test_server_port.py@@ -0,0 +1,41 @@+"""Studio port resolution — must stay identical to src/config/server.ts."""++import os+import re+import sys+import unittest++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++from config.server import DEFAULT_PORT, resolve_web_server_port, web_server_url+++class WebServerPortTests(unittest.TestCase):+ def test_defaults_to_3847(self):+ self.assertEqual(DEFAULT_PORT, 3847)+ self.assertEqual(resolve_web_server_port({}), 3847)++ def test_reads_podcli_port_first(self):+ self.assertEqual(resolve_web_server_port({"PODCLI_PORT": "4000", "PORT": "5000"}), 4000)++ def test_falls_back_to_port(self):+ self.assertEqual(resolve_web_server_port({"PORT": "5000"}), 5000)++ def test_rejects_garbage_and_out_of_range(self):+ for raw in ("banana", "", "0", "70000", "-1"):+ self.assertEqual(resolve_web_server_port({"PORT": raw}), 3847, raw)++ def test_url_uses_resolved_port(self):+ self.assertEqual(web_server_url({"PODCLI_PORT": "4000"}), "http://localhost:4000")++ def test_typescript_resolver_agrees(self):+ ts = open(os.path.join(ROOT, "src", "config", "server.ts"), encoding="utf-8").read()+ self.assertIn("env.PODCLI_PORT || env.PORT", ts)+ self.assertTrue(re.search(r":\s*3847\s*;", ts))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_speaker_assignment.py b/tests/test_speaker_assignment.pynew file mode 100644index 0000000..76fe50f--- /dev/null+++ b/tests/test_speaker_assignment.py@@ -0,0 +1,61 @@+"""Tests for backend.services.speaker_detection word/segment assignment."""++import os+import sys+import unittest++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++from services.speaker_detection import assign_speakers_to_words+++class AssignSpeakersToWordsTests(unittest.TestCase):+ def test_no_diarization_data_assigns_none(self):+ words = [{"word": "hi", "start": 0.0, "end": 0.4}]+ out = assign_speakers_to_words(words, [])+ self.assertIsNone(out[0]["speaker"])++ def test_word_inside_single_segment(self):+ words = [{"word": "hi", "start": 1.0, "end": 1.4}]+ segments = [{"speaker": "SPEAKER_00", "start": 0.0, "end": 5.0}]+ out = assign_speakers_to_words(words, segments)+ self.assertEqual(out[0]["speaker"], "SPEAKER_00")++ def test_boundary_word_gets_max_overlap_speaker_not_first_match(self):+ # Word straddles a turn boundary: A covers 0.1s, B covers 0.5s.+ words = [{"word": "yeah", "start": 10.0, "end": 10.6}]+ segments = [+ {"speaker": "SPEAKER_00", "start": 9.0, "end": 10.1},+ {"speaker": "SPEAKER_01", "start": 10.1, "end": 12.0},+ ]+ out = assign_speakers_to_words(words, segments)+ self.assertEqual(out[0]["speaker"], "SPEAKER_01")++ def test_split_segments_of_same_speaker_accumulate(self):+ words = [{"word": "so", "start": 10.0, "end": 11.0}]+ segments = [+ {"speaker": "SPEAKER_00", "start": 10.0, "end": 10.3},+ {"speaker": "SPEAKER_01", "start": 10.3, "end": 10.7},+ {"speaker": "SPEAKER_00", "start": 10.7, "end": 11.0},+ ]+ out = assign_speakers_to_words(words, segments)+ self.assertEqual(out[0]["speaker"], "SPEAKER_00")++ def test_zero_length_word_falls_back_to_midpoint(self):+ words = [{"word": "uh", "start": 10.5, "end": 10.5}]+ segments = [{"speaker": "SPEAKER_01", "start": 10.0, "end": 11.0}]+ out = assign_speakers_to_words(words, segments)+ self.assertEqual(out[0]["speaker"], "SPEAKER_01")++ def test_word_outside_all_segments_is_none(self):+ words = [{"word": "hm", "start": 50.0, "end": 50.4}]+ segments = [{"speaker": "SPEAKER_00", "start": 0.0, "end": 10.0}]+ out = assign_speakers_to_words(words, segments)+ self.assertIsNone(out[0]["speaker"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_suggest_handler.py b/tests/test_suggest_handler.pynew file mode 100644index 0000000..4c577d2--- /dev/null+++ b/tests/test_suggest_handler.py@@ -0,0 +1,117 @@+"""Tests for backend.main's AI suggestion handler."""++import os+import sys+import unittest+from unittest import mock++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+BACKEND_ROOT = os.path.join(ROOT, "backend")+if BACKEND_ROOT not in sys.path:+ sys.path.insert(0, BACKEND_ROOT)++import main as backend_main+from services import claude_suggest++SEGMENTS = [{"start": 0.0, "end": 10.0, "text": "hello"}]+ENERGY_DATA = [{"time": float(t), "rms_db": -30.0} for t in range(31)] + [+ {"time": 25.0, "rms_db": 0.0}+]+EVENTS_DATA = [{+ "time": 25.0,+ "laughter": 1.0,+ "cheering": 0.0,+ "screaming": 0.0,+ "speech": 0.0,+}]+CLIPS = [+ {"title": "first", "start_second": 0, "end_second": 10, "score": 15},+ {"title": "second", "start_second": 10, "end_second": 20, "score": 14},+ {"title": "reaction", "start_second": 20, "end_second": 30, "score": 13},+]+++class SuggestReactionTimesTests(unittest.TestCase):+ def _run(self, params, clips=None):+ captured = {}+ emitted = {}++ def fake_suggest(**kwargs):+ captured.update(kwargs)+ return clips or [{"title": "clip", "start_second": 0, "end_second": 30}]++ def fake_emit_result(task_id, status, data=None, error=None):+ emitted.update({"task_id": task_id, "status": status, "data": data, "error": error})++ with mock.patch.object(claude_suggest, "suggest_initial_with_claude", fake_suggest), \+ mock.patch.object(claude_suggest, "_find_ai_cli_candidates", return_value=["claude"]), \+ mock.patch.object(backend_main, "emit_result", fake_emit_result), \+ mock.patch.object(backend_main, "emit_progress"):+ backend_main.handle_suggest_clips("task-1", params)+ return captured, emitted++ def test_reaction_times_are_forwarded(self):+ captured, _ = self._run({+ "segments": SEGMENTS,+ "reaction_times": [12.5, 40.0],+ })+ self.assertEqual(captured["reaction_times"], [12.5, 40.0])++ def test_cached_signals_are_reused_without_decoding(self):+ with mock.patch(+ "services.signal_cache.load_signals",+ return_value={"energy_data": ENERGY_DATA, "events_data": EVENTS_DATA},+ ), \+ mock.patch("services.audio_analyzer.extract_audio_energy") as extract_energy, \+ mock.patch("services.audio_events.extract_audio_events") as extract_events, \+ mock.patch.object(backend_main.os.path, "exists", return_value=True):+ captured, emitted = self._run(+ {"segments": SEGMENTS, "video_path": "/video.mp4", "top_n": 2},+ clips=[dict(c) for c in CLIPS],+ )++ extract_energy.assert_not_called()+ extract_events.assert_not_called()+ self.assertEqual(captured["reaction_times"], [25.0])+ self.assertEqual(captured["top_n"], 4)+ self.assertEqual(+ [clip["title"] for clip in emitted["data"]["clips"]],+ ["first", "reaction"],+ )+ self.assertGreater(emitted["data"]["clips"][1]["signal_boost"], 2)++ def test_uncached_signals_are_extracted_once_from_a_shared_wav(self):+ with mock.patch("services.signal_cache.load_signals", return_value={}), \+ mock.patch("services.signal_cache.save_signals") as save_signals, \+ mock.patch(+ "services.audio_extract.extract_wav_16k_mono", return_value="/tmp/shared.wav"+ ) as extract_wav, \+ mock.patch(+ "services.audio_analyzer.extract_audio_energy", return_value=ENERGY_DATA+ ) as extract_energy, \+ mock.patch(+ "services.audio_events.extract_audio_events", return_value=EVENTS_DATA+ ) as extract_events, \+ mock.patch("services.audio_events.is_available", return_value=True), \+ mock.patch.object(backend_main.os.path, "exists", return_value=True), \+ mock.patch.object(backend_main.os, "unlink"):+ captured, _ = self._run(+ {"segments": SEGMENTS, "video_path": "/video.mp4", "top_n": 2},+ clips=[dict(c) for c in CLIPS],+ )++ extract_wav.assert_called_once_with("/video.mp4")+ extract_energy.assert_called_once_with("/video.mp4", wav_path="/tmp/shared.wav")+ extract_events.assert_called_once_with("/video.mp4", wav_path="/tmp/shared.wav")+ save_signals.assert_called_once_with(+ "/video.mp4", energy_data=ENERGY_DATA, events_data=EVENTS_DATA+ )+ self.assertEqual(captured["reaction_times"], [25.0])++ def test_missing_video_and_anchors_pass_none(self):+ captured, _ = self._run({"segments": SEGMENTS})+ self.assertIsNone(captured["reaction_times"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_video_cut.py b/tests/test_video_cut.pyindex d6a30c8..d9ea007 100644--- a/tests/test_video_cut.py+++ b/tests/test_video_cut.py@@ -1,11 +1,13 @@"""Tests for backend.services.video_cut.-Mocks proc_run so no actual ffmpeg process is spawned. Verifies the-command shapes, the single-segment shortcut path, and cleanup of-temporary concat artifacts.+Command shapes, the single-segment shortcut path and concat cleanup are+checked against a mocked proc_run. Cut accuracy is checked against real+ffmpeg on a synthetic clip with a known GOP structure."""import os+import shutil+import subprocessimport sysimport tempfileimport unittest@@ -94,7 +96,6 @@ class CutMultiSegmentTests(unittest.TestCase):self.assertFalse(os.path.exists(os.path.join(tmpdir, f"_part_{i}.mp4")))self.assertFalse(os.path.exists(os.path.join(tmpdir, "_concat_parts.txt")))finally:- import shutilshutil.rmtree(tmpdir, ignore_errors=True)def test_multi_segment_cleans_up_on_failure(self):@@ -118,7 +119,6 @@ class CutMultiSegmentTests(unittest.TestCase):for i in range(2):self.assertFalse(os.path.exists(os.path.join(tmpdir, f"_part_{i}.mp4")))finally:- import shutilshutil.rmtree(tmpdir, ignore_errors=True)@@ -129,5 +129,89 @@ class ReExportTests(unittest.TestCase):self.assertIs(vp.cut_multi_segment, video_cut.cut_multi_segment)++class NoStreamCopyTests(unittest.TestCase):+ def test_cut_always_re_encodes(self):+ with mock.patch.object(video_cut, "proc_run", return_value=_ok()) as mocked:+ video_cut.cut_segment("/in.mp4", "/out.mp4", 3.98, 6.0)++ self.assertEqual(mocked.call_count, 1)+ joined = " ".join(mocked.call_args.args[0])+ self.assertIn("libx264", joined)+ self.assertNotIn("-c copy", joined)+ self.assertNotIn("ffprobe", joined)+++ shutil.which("ffmpeg") and shutil.which("ffprobe"), "ffmpeg/ffprobe not installed"+)+class CutContentAccuracyTests(unittest.TestCase):+ """Cut off the keyframe grid of a known 2s GOP and check the content that+ lands at t=0, not just the clip's duration."""++ COLORS = ["red", "green", "blue", "yellow", "cyan", "magenta", "white", "gray"]+ RGB = {+ "red": (255, 0, 0), "green": (0, 128, 0), "blue": (0, 0, 255),+ "yellow": (255, 255, 0), "cyan": (0, 255, 255), "magenta": (255, 0, 255),+ "white": (255, 255, 255), "gray": (128, 128, 128),+ }++ @classmethod+ def setUpClass(cls):+ cls.tmpdir = tempfile.mkdtemp(prefix="podcli-gop-test-")+ cls.src = os.path.join(cls.tmpdir, "src.mp4")+ cmd = ["ffmpeg", "-y", "-loglevel", "error"]+ for color in cls.COLORS:+ cmd += ["-f", "lavfi", "-i", f"color=c={color}:s=64x64:r=25:d=1"]+ cmd += [+ "-filter_complex", f"concat=n={len(cls.COLORS)}:v=1:a=0",+ "-c:v", "libx264", "-pix_fmt", "yuv420p",+ "-g", "50", "-keyint_min", "50", "-sc_threshold", "0",+ cls.src,+ ]+ subprocess.run(cmd, check=True, capture_output=True)++ @classmethod+ def tearDownClass(cls):+ shutil.rmtree(cls.tmpdir, ignore_errors=True)++ def _first_frame_rgb(self, path):+ raw = subprocess.run(+ ["ffmpeg", "-loglevel", "error", "-i", path, "-frames:v", "1",+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],+ check=True, capture_output=True,+ ).stdout+ px = list(raw)+ n = len(px) // 3+ return tuple(round(sum(px[c::3]) / n) for c in range(3))++ def _assert_frame_is(self, path, color):+ got = self._first_frame_rgb(path)+ want = self.RGB[color]+ for got_c, want_c in zip(got, want):+ self.assertLessEqual(+ abs(got_c - want_c), 24,+ f"first frame {got} is not {color} {want}",+ )++ def test_cut_just_before_a_keyframe_starts_at_the_requested_second(self):+ # Keyframes land on 0/2/4/6. A cut at 3.9 must open on second 3+ # (yellow), never on the keyframe-2 content (blue) that a stream copy+ # would seek back to.+ out = os.path.join(self.tmpdir, "cut_off_grid.mp4")+ video_cut.cut_segment(self.src, out, 3.9, 6.0)+ self._assert_frame_is(out, "yellow")++ def test_cut_mid_gop_starts_at_the_requested_second(self):+ out = os.path.join(self.tmpdir, "cut_mid_gop.mp4")+ video_cut.cut_segment(self.src, out, 5.5, 7.0)+ self._assert_frame_is(out, "magenta")++ def test_cut_on_a_keyframe_starts_at_the_requested_second(self):+ out = os.path.join(self.tmpdir, "cut_on_kf.mp4")+ video_cut.cut_segment(self.src, out, 4.0, 5.0)+ self._assert_frame_is(out, "cyan")++if __name__ == "__main__":unittest.main()diff --git a/tests/test_video_processor_helpers.py b/tests/test_video_processor_helpers.pyindex 4e83a77..151bead 100644--- a/tests/test_video_processor_helpers.py+++ b/tests/test_video_processor_helpers.py@@ -137,5 +137,46 @@ class AssignFaceTracksTests(unittest.TestCase):self.assertEqual(frame0_ids, frame1_ids)++class FaceSampleIndicesTests(unittest.TestCase):+ def _reference_indices(self, total_frames, fps):+ """The stepping the old cap.set() sampling loop used."""+ sample_step = max(1, int(fps / 10))+ dense_end = int(fps * 0.5)+ semi_dense_end = int(fps * 1.0)+ semi_dense_step = max(1, sample_step // 2)+ indices = []+ idx = 0+ while idx < total_frames:+ indices.append(idx)+ if idx < dense_end:+ idx += 1+ elif idx < semi_dense_end:+ idx += semi_dense_step+ else:+ idx += sample_step+ return indices++ def test_matches_seek_loop_progression_at_30fps(self):+ self.assertEqual(vp._face_sample_indices(300, 30.0), self._reference_indices(300, 30.0))++ def test_matches_seek_loop_progression_at_60fps(self):+ self.assertEqual(vp._face_sample_indices(600, 60.0), self._reference_indices(600, 60.0))++ def test_dense_start_then_sparse(self):+ indices = vp._face_sample_indices(900, 30.0)+ self.assertEqual(indices[:15], list(range(15)))+ steps = {b - a for a, b in zip(indices, indices[1:]) if a >= 30}+ self.assertEqual(steps, {3})++ def test_strictly_increasing_and_bounded(self):+ indices = vp._face_sample_indices(100, 24.0)+ self.assertEqual(indices, sorted(set(indices)))+ self.assertLess(indices[-1], 100)++ def test_empty_video(self):+ self.assertEqual(vp._face_sample_indices(0, 30.0), [])++if __name__ == "__main__":unittest.main()