Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.0.1): the Update that reported success on stale code
mrbizarro3ff1a33dcb3e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 38acab1..58061d9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -513,6 +513,23 @@ and each is cheap enough that "I forgot" is not a reason.| `./ltx-2-mlx/env/bin/python3.11 scripts/assert_registry.py` | `MODEL_VERSIONS`, `required_files.json`, pack paths, the text-encoder seam, deep-verify sources | a generation that resolves another generation's weights or text encoder — the two bugs that shipped silently on 2026-08-12, neither of which raised anything || `./ltx-2-mlx/env/bin/python3.11 scripts/assert_schedules.py` | `make_job`, any `*_steps` default, a new render mode, a pin move | a job dict that asks a checkpoint to PAD a fixed sigma table — the class that let Colorize/Restore/Ingredients/Control/HDR burn 218 s and die on "cannot thin a 9-point schedule (8 steps) up to 10 steps" || `./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py` | the vendored pin, any package reinstall | a bypassed codec patch — v3.8.1 shipped silent 4:2:0 for a whole release because this ran eleven steps too late and never executed |+| `./ltx-2-mlx/env/bin/python3.11 test_character_roundtrip.py` | character defaults, the Characters submit, Load Params, `_CHARACTER_QUALITY_RESOLUTION` | a job the panel can render but cannot reload — the two surfaces disagreeing on the strength pair, a Draft render reopening as Pro because Load Params never learned the new canvas, or a voice strength that is submitted and then silently dropped on restore |++**Why that last one is a different kind of gate.** Every other row is+structural — dispatch length, step ordering, pin text, schema — and not one of+them could have caught the Character contract drifting, because the defect only+exists in the *round trip*: payload → sidecar → Load Params → payload. An+external review found three of those at once in v4.0.++**And it EXECUTES the panel's JavaScript.** Its first version asserted the+contract by grepping `mlx_ltx_panel.py` for the calls it hoped were there; all+twelve tests passed while the live loader was still broken and the slider+displayed a different number from the one being submitted. A test that passes+by finding strings is worse than no test, because it also reports the area as+covered. `scripts/extract_panel_js.py` pulls the real functions and the real+markup out of the panel and the suite runs them in node against a DOM shim.+Extraction *raises* on a renamed function, so coverage cannot quietly decay+back to grepping. If you add a field a sidecar records, assert it there.**The codec rule, stated correctly.** It has been passed around as *"`grep -rnlibx264` in the vendored tree must return exactly one hit"*, and read literallydiff --git a/README.md b/README.mdindex 6abbce5..76cf178 100644--- a/README.md+++ b/README.md@@ -13,11 +13,11 @@</p>-> **Current release: v4.0.0.** LTX-2.5 is the engine Phosphene renders with — the first native Mac build of it, and the generation a fresh install now downloads. A live preview of the frame being made, a Stop early that saves the wait, trained characters in about two and a half minutes, and the five control modes fixed. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).+> **Current release: v4.0.1.** A point release: the Update button now fails loudly instead of reporting success on stale code, and it stops deleting files it should have left alone. The HQ tier gains the live preview it had been promising, the storyboard planner keeps your characters looking like themselves and your premise on screen, and every install offer is resolved against the generation you actually have. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).## Overview-Phosphene is a local generative-media panel for Apple Silicon. It runs [LTX-Video 2.5](https://github.com/Lightricks/LTX-Video) (MLX port) for joint audio-and-video synthesis, [Qwen-Image-Edit-2509](https://huggingface.co/Qwen/Qwen-Image-Edit-2509) (with a Lightning 4-step fast tier) for stills, and ships an in-panel LoRA training pipeline for character identity (face + optional voice from a single dataset). Everything runs on-device: no cloud, no API keys, and no prompt, image, video or filename ever leaves your Mac. It does send anonymous usage counts (version, hardware class, render stats) — every field is listed in [docs/ANALYTICS.md](docs/ANALYTICS.md), and one click in Settings turns it off.+Phosphene is a local generative-media panel for Apple Silicon. It runs **two video engines as peers** — [LTX-Video 2.5](https://github.com/Lightricks/LTX-Video) (MLX port) and [Hailuo H3](https://github.com/MiniMax-AI) (MiniMax-H3 FL2VA) — both doing joint audio-and-video synthesis, plus [Qwen-Image-Edit-2509](https://huggingface.co/Qwen/Qwen-Image-Edit-2509) (with a Lightning 4-step fast tier) for stills, and an in-panel LoRA training pipeline for character identity (face + voice from a single dataset). Everything runs on-device: no cloud, no API keys, and no prompt, image, video or filename ever leaves your Mac. It does send anonymous usage counts (version, hardware class, render stats) — every field is listed in [docs/ANALYTICS.md](docs/ANALYTICS.md), and one click in Settings turns it off.3.0 introduces in-panel character training (face + voice LoRA from one dataset), the Audio-to-Video workflow, the Image Studio tab, hardware capability tiering, and an agentic prompt enhancer driven by the same local Gemma 3 12B used for auto-captioning.@@ -33,11 +33,24 @@ The interface adapts to the machine it runs on. Under 48 GB of unified memory, tText-to-video, image-to-video, and audio-to-video, all delivered as MP4 with joint audio (lip-sync, footsteps, ambience) in a single diffusion pass. Output is 1280×720 after the built-in 2× upscale. Character mode renders against the Q8 dev transformer with a fused character LoRA; the server-side validator refuses Q4 + character to prevent silent identity drift. First/last-frame keyframing and clip extension are available on the Q8 surface, with TeaCache wired through both.+**Two engines, one switcher.** A segmented control in the header picks which engine renders the shot, and the form below re-prices itself for whichever one is selected:++| | [**LTX-Video 2.5**](https://github.com/Lightricks/LTX-Video) | [**Hailuo H3**](https://github.com/MiniMax-AI) (MiniMax-H3 FL2VA) |+|---|---|---|+| **How you get it** | The base install (27.5 GB) | One click in the Pinokio sidebar (75 GB) |+| **Modes** | Text, image, keyframes, extend, audio-to-video, character | Text and image |+| **Character LoRAs** | Yes — trained in-panel, face + voice | Not yet |+| **Memory** | Every tier in the table above; the surface adapts | 64 GB class, or 48 GB with the Q8 DiT pack on disk |+| **Best at** | Breadth: every workflow the panel offers, plus your own trained faces | Dialogue: joint video + spoken lines + sound, from one prompt |+| **Weights licence** | [LTX-2.x Community License](LICENSES/LTX-2.x-Community-License.md) (Lightricks) | MiniMax Community License — territory restrictions apply |++Neither engine is a fallback for the other. If only one is installed, the other appears in the switcher as an offer with its size on it — one click explains what it does and where to get it, and nothing about your existing renders changes when it lands.+### Image Studio<img width="1920" height="843" alt="image" src="https://github.com/user-attachments/assets/8e2f52de-b34c-44cf-9283-df30c4079607" />-Qwen-Image-Edit (Lightning 4-step) is the default image engine. It handles instruction edits ("change the white jacket to red") and multi-subject composition with up to three reference images, generating four candidates per shot in seconds with the Lightning LoRA baked in. It's an optional one-click install (the panel falls back to a lighter mflux model if Qwen isn't installed). Results drop cards into a unified gallery, each with an Animate button that pre-fills the I2V form with the source still.+Qwen-Image-Edit (Lightning 4-step) is the default image engine. It handles instruction edits ("change the white jacket to red") and multi-subject composition with up to three reference images, generating four candidates per shot in seconds with the Lightning LoRA baked in. It's a one-click install; until it lands the panel renders stills on a lighter mflux model. Results drop cards into a unified gallery, each with an Animate button that pre-fills the I2V form with the source still.### Train Characterdiff --git a/VERSION b/VERSIONindex fcdb2e1..1454f6e 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.0.0+4.0.1diff --git a/docs/API.md b/docs/API.mdindex 8188325..8a7a315 100644--- a/docs/API.md+++ b/docs/API.md@@ -34,7 +34,7 @@ Add a job to the panel's queue. Returns immediately; the helper renders it async| `frames` | int | Must satisfy `frames % 8 == 1`. 121 = 5s, 169 = 7s, 241 = 10s. || `frame_rate` | float | Default `24`. LTX is trained at 24 fps; deviation degrades quality. || `character_strength` | float | Default `1.0`. The FACE LoRA's strength, 0–2. |-| `character_voice_strength` | float | Default `1.0`. The VOICE LoRA's strength, 0–2, applied to `<trigger>.audio.safetensors` only. It is a separate number from the face because the face file's audio-branch deltas are noise and are louder than the voice file's signal at equal strength — so running the voice hotter (1.2 is parity, 1.4 is the first setting with real headroom) is what makes it win. The default stays at the graded `1.0`; the hotter rungs are yours to reach for. |+| `character_voice_strength` | float | Default `1.0`. The VOICE LoRA's strength, 0–2, applied to `<trigger>.audio.safetensors` only. It is a separate number from the face because the face file's audio-branch deltas are noise and are louder than the voice file's signal at equal strength. The measurement argues for running it hotter (1.2 is parity, 1.4 has real headroom); a graded A/B said otherwise, and `1.0` won. Raise it in small steps only when a specific voice is being drowned. || `seed` | int or `-1` | `-1` = random. || `quality` | `quick` \| `balanced` \| `standard` \| `high` | **For character LoRA work, use `high`.** `balanced` silently routes >121f clips to the Q4 distilled transformer where current LoRAs lose identity. || `stage1_steps`, `stage2_steps` | int | HQ two-stage pipeline. Validated defaults: `10` / `3`. |@@ -161,13 +161,17 @@ Present while a job runs."pct": 41, "phase": "denoise", "phase_label": "Denoising · step 5 / 10","elapsed_sec": 62, "remaining_sec": 84, "eta_sec": 146,"preview": {- "url": "/file?path=…/live/preview_latest.png&t=1786…", // cache-busted server-side+ "url": "/image?path=…/live/preview_latest.png&t=1786…", // cache-busted server-side+ // /image, NOT /file: the preview lives under STATE_DIR and+ // /file serves OUTPUT only. Writing /file here is what shipped+ // a correct preview to a broken-image glyph in every client."estimate": 4, "total": 12,"meaningful": true, // THE gate — the server decides, the client renders"abortable": true, // meaningful && the runner published an abort sentinel"saves_sec": 182 // remaining_sec at the moment it became abortable},- "preview_url": "/file?path=…" // top-level alias, present only once meaningful+ "preview_url": "/image?path=…" // top-level alias of preview.url, same /image+ // form, present only once meaningful}```diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.mdindex 253a7b9..fc902cc 100644--- a/docs/H3_ENGINE.md+++ b/docs/H3_ENGINE.md@@ -1,10 +1,12 @@# Hailuo H3 — Phosphene's second video engineMiniMax-H3 (FL2VA) takes one prompt and returns **picture, dialogue and sound-generated together**. It ships as an **optional pack**, not part of the base-install: ~75 GB of weights, a 64 GB+ Mac, and a licence with territory-restrictions. LTX stays the default engine and is completely untouched by-any of this.+generated together**. It is a **peer of LTX, not an add-on to it** — but it is+too big to ship in the base install, so it arrives as **its own one-click+install**: ~75 GB of weights, a 64 GB+ Mac, and a licence with territory+restrictions. LTX remains the default engine and is completely untouched by+any of this; whichever engines you have installed sit side by side in the+switcher.---@@ -65,6 +67,20 @@ duplicating 75 GB.| `LTX_H3_DENSE_10S` | unset | re-adds the pre-chaining dense 10 s tier (36 min) for A/B work || `LTX_H3_WIDE_DRAFT` | unset | adds an experimental **512×288 16:9 draft** (~2 min). Off because 0.15 MP is below anything this campaign has measured — see Tiers. |+**Set them in `ENVIRONMENT`, not in your shell.** An `export` in a terminal reaches+only a panel launched from that same terminal, and it is gone the moment Pinokio+restarts the app — which is exactly how a working H3 install "loses" its engine+after a restart, with the weights still on disk and the panel reporting the pack+missing. The `ENVIRONMENT` file at the install root is read on every launch, so+lines there survive restarts and updates:++```+LTX_H3_ROOT=/path/to/minimax-h3-mlx+LTX_H3_MODELS=/path/to/models+```++The `export` form shown further down is for one-off CLI runs, not for the panel.+### Model layout — both shapes work`h3_paths()` tries two roots in order, so no post-download move is ever needed:diff --git a/docs/STATE.md b/docs/STATE.mdindex 27eaa5d..f15410e 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,6 +1,19 @@# Phosphene — project state, history, open work-**Public release: `v4.0.0`** (2026-08-13 — LTX-2.5 becomes the generation the panel serves; see the v4.0 entry below. The narrative in this paragraph stops at v3.1.1 and is kept as history). **The 2.3/2.5 divergence that ran through the v3.8.x line is closed by this release** — LTX-2.5 is the registered default and the vendored port is pinned at the tag `v0.14.19+ltx25.3`. v3.8.x registered 2.3 only and pinned `871694d`, because the 2.5 packs were not publicly downloadable at cut time; they are now. See `CLAUDE.md`'s pin table. The entire v3.0 line shipped — v3.0.0 (Characters / Voice / Image Studio / A2V, May 23) → v3.0.1 (FFLF crash fix) → v3.0.2 (Boost/Turbo accel restored after a 2-month silent regression) → v3.0.3 (HiDream hidden, #15) → v3.0.4 (CivitAI SSL) → v3.0.5 (A2V kwarg signature shim, #5) → v3.0.6 (deep-review hardening) → v3.0.7 (GPU-race fix + /status version surfacing) → **v3.0.8 (ltx-2-mlx v0.14.8 catch-up — codec-only patches, I2V "mosaic"/Metal-watchdog fix #17, ASCII version-skew handshake fix)** → **v3.0.9 (custom I2V Width×height inputs restored for power users; Train-tab dev-transformer Download "unknown install key" fix — form-encoding, reported by @cocktailpeanut)** → **v3.0.10 (model-integrity self-heal — boot scan + `/status.model_integrity` + a one-click Repair banner for corrupt/partial weights, the leading *non-Metal* "mosaic" garbage-decode cause; safetensors header+size check)** → **v3.0.11 (latent helper-handshake hang fixed: `_read_until` mixed `select()` on the raw fd with a buffered `readline()`, so any event the helper emitted *right before* `ready` — a version-skew line, the new runtime fingerprint — got stranded in the TextIOWrapper buffer and the panel hung 120 s → "helper failed to start: None". This is the true root cause behind the mislabeled "⚠️-emoji" handshake break. Now reads the raw fd via `os.read()` into a carry buffer and drains every complete line before re-`select()`-ing. PLUS: every render log self-documents its runtime — mlx/mlx-metal version + Apple chip + macOS — surfaced in `/status`, the `helper ready ·` line, and a standalone `runtime |` line, the exact data needed to triangulate the remaining MLX-numerical "mosaic")** → **v3.0.12 (the REAL mosaic fix + 3 more. The mosaic is NOT a code bug or the missing-upscaler theory (both disproved by local repro — the bare 6-file Q4 set renders byte-identical-clean on M4 Max); it's stale/corrupt weight *content* — right size, wrong bytes — that v3.0.10's header+size check can't see (confirmed: ronyeoh/#18 + claude3d/#5 fixed it only by a fresh full re-download). Added **deep checksum verify vs upstream**: Settings → Model files → "Verify model files (checksum)" / `/models/verify-deep` hashes every weight + compares to HuggingFace's published SHA-256 (proven to match local), mismatches feed the existing one-click Repair re-download. Validated: flipped 16 bytes mid-file → header+size passed, deep-verify caught it. ALSO in v3.0.12: character-LoRA-shows-as-"style-only" fix (#5 — `list_user_loras` recovers trigger+kind from the `_v2` filename when the sidecar is missing); `cgi`→`email` multipart migration (Python-3.13-ready, removes the boot DeprecationWarning, adopted from @ssfeather's PR #22); dynamic 3–8 multi-keyframe UI (adopted from @youngbee12's PR #20, ported clean with the integrity feature preserved + a JS ReferenceError fixed). Folds in v3.0.11's handshake fix + runtime fingerprint.)** → **v3.0.13 (character LoRA fixes, #5 @claude3d: a multi-word/spaced character filename no longer mislabels as style-only — the id regex gated out spaces before the sidecar was read; and the Character tab no longer silently falls back to plain T2V — a UI desync left the avatar's selection ring lit after `character_id` was cleared. Plus an `enhancePrompt` element-id fix. Cherry-picked to prod `ce03139`, release `814dc2d`.)** → **v3.1.0 (Ideogram 4 — open-weight 9.3B text-rendering image model + a visual text-placement canvas that places exact text via normalized-bbox captions. mflux 0.18 `mflux-generate-ideogram4`; gated `ideogram-ai/ideogram-4-fp8` ~26 GB, needs a HF Read token + license. Fixed the gated-download 401 that would have hit EVERY user — the panel now exports its configured token to subprocess env via `_sync_hf_token_to_env` so a stale `hf auth login` cache can't shadow it; proven clean-room. Validated end-to-end: 8-text-element field-guide poster rendered clean, every label placed per its bbox.)** → **v3.1.1 (Ideogram output-card buttons hotfix, reported by Mr Bizarro: an Ideogram image's prompt is a caption JSON, which broke every output surface that fed it into a plain box / inline onclick — the Recent-list Animate button was worked-but-dead because apostrophes/&/< in the caption terminated the single-quoted onclick. Display-layer fix: `_displayPromptFor` derives `high_level_description`, `escapeHtml` the onclick args, friendly `_imgEngineLabel`, and `loadParams` restores an Ideogram image into the visual canvas instead of dumping JSON. `params.prompt` stays the caption JSON; renders unaffected. Validated live.)** All validated end-to-end on the dev panel (deep-verify corrupt-detect + repair, /loras, byte-identical upload, multi-keyframe render, FFLF regression). See §4 for the full version history. The May-17 Codex C+ UI restructure (capability tiers, Q4 surface, Character as 5th mode pill, accel kill, HQ-speed move) and the Train-tab / LoRA-chrome work that followed are all baseline now, folded into v3.0.x. There is no `v2.0.6` tag.+**Public release: `v4.0.1`** (2026-08-14 — the point release the external review earned: a transactional updater, a storyboard planner that obeys its own laws, live preview on the HQ tier, and every offer resolved against the generation actually installed; see the v4.0.1 entry below. The narrative in this paragraph stops at v3.1.1 and is kept as history). **The 2.3/2.5 divergence that ran through the v3.8.x line was closed by v4.0.0** — LTX-2.5 is the registered default and the vendored port is pinned at the tag `v0.14.19+ltx25.3`. v3.8.x registered 2.3 only and pinned `871694d`, because the 2.5 packs were not publicly downloadable at cut time; they are now. See `CLAUDE.md`'s pin table. The entire v3.0 line shipped — v3.0.0 (Characters / Voice / Image Studio / A2V, May 23) → v3.0.1 (FFLF crash fix) → v3.0.2 (Boost/Turbo accel restored after a 2-month silent regression) → v3.0.3 (HiDream hidden, #15) → v3.0.4 (CivitAI SSL) → v3.0.5 (A2V kwarg signature shim, #5) → v3.0.6 (deep-review hardening) → v3.0.7 (GPU-race fix + /status version surfacing) → **v3.0.8 (ltx-2-mlx v0.14.8 catch-up — codec-only patches, I2V "mosaic"/Metal-watchdog fix #17, ASCII version-skew handshake fix)** → **v3.0.9 (custom I2V Width×height inputs restored for power users; Train-tab dev-transformer Download "unknown install key" fix — form-encoding, reported by @cocktailpeanut)** → **v3.0.10 (model-integrity self-heal — boot scan + `/status.model_integrity` + a one-click Repair banner for corrupt/partial weights, the leading *non-Metal* "mosaic" garbage-decode cause; safetensors header+size check)** → **v3.0.11 (latent helper-handshake hang fixed: `_read_until` mixed `select()` on the raw fd with a buffered `readline()`, so any event the helper emitted *right before* `ready` — a version-skew line, the new runtime fingerprint — got stranded in the TextIOWrapper buffer and the panel hung 120 s → "helper failed to start: None". This is the true root cause behind the mislabeled "⚠️-emoji" handshake break. Now reads the raw fd via `os.read()` into a carry buffer and drains every complete line before re-`select()`-ing. PLUS: every render log self-documents its runtime — mlx/mlx-metal version + Apple chip + macOS — surfaced in `/status`, the `helper ready ·` line, and a standalone `runtime |` line, the exact data needed to triangulate the remaining MLX-numerical "mosaic")** → **v3.0.12 (the REAL mosaic fix + 3 more. The mosaic is NOT a code bug or the missing-upscaler theory (both disproved by local repro — the bare 6-file Q4 set renders byte-identical-clean on M4 Max); it's stale/corrupt weight *content* — right size, wrong bytes — that v3.0.10's header+size check can't see (confirmed: ronyeoh/#18 + claude3d/#5 fixed it only by a fresh full re-download). Added **deep checksum verify vs upstream**: Settings → Model files → "Verify model files (checksum)" / `/models/verify-deep` hashes every weight + compares to HuggingFace's published SHA-256 (proven to match local), mismatches feed the existing one-click Repair re-download. Validated: flipped 16 bytes mid-file → header+size passed, deep-verify caught it. ALSO in v3.0.12: character-LoRA-shows-as-"style-only" fix (#5 — `list_user_loras` recovers trigger+kind from the `_v2` filename when the sidecar is missing); `cgi`→`email` multipart migration (Python-3.13-ready, removes the boot DeprecationWarning, adopted from @ssfeather's PR #22); dynamic 3–8 multi-keyframe UI (adopted from @youngbee12's PR #20, ported clean with the integrity feature preserved + a JS ReferenceError fixed). Folds in v3.0.11's handshake fix + runtime fingerprint.)** → **v3.0.13 (character LoRA fixes, #5 @claude3d: a multi-word/spaced character filename no longer mislabels as style-only — the id regex gated out spaces before the sidecar was read; and the Character tab no longer silently falls back to plain T2V — a UI desync left the avatar's selection ring lit after `character_id` was cleared. Plus an `enhancePrompt` element-id fix. Cherry-picked to prod `ce03139`, release `814dc2d`.)** → **v3.1.0 (Ideogram 4 — open-weight 9.3B text-rendering image model + a visual text-placement canvas that places exact text via normalized-bbox captions. mflux 0.18 `mflux-generate-ideogram4`; gated `ideogram-ai/ideogram-4-fp8` ~26 GB, needs a HF Read token + license. Fixed the gated-download 401 that would have hit EVERY user — the panel now exports its configured token to subprocess env via `_sync_hf_token_to_env` so a stale `hf auth login` cache can't shadow it; proven clean-room. Validated end-to-end: 8-text-element field-guide poster rendered clean, every label placed per its bbox.)** → **v3.1.1 (Ideogram output-card buttons hotfix, reported by Mr Bizarro: an Ideogram image's prompt is a caption JSON, which broke every output surface that fed it into a plain box / inline onclick — the Recent-list Animate button was worked-but-dead because apostrophes/&/< in the caption terminated the single-quoted onclick. Display-layer fix: `_displayPromptFor` derives `high_level_description`, `escapeHtml` the onclick args, friendly `_imgEngineLabel`, and `loadParams` restores an Ideogram image into the visual canvas instead of dumping JSON. `params.prompt` stays the caption JSON; renders unaffected. Validated live.)** All validated end-to-end on the dev panel (deep-verify corrupt-detect + repair, /loras, byte-identical upload, multi-keyframe render, FFLF regression). See §4 for the full version history. The May-17 Codex C+ UI restructure (capability tiers, Q4 surface, Character as 5th mode pill, accel kill, HQ-speed move) and the Train-tab / LoRA-chrome work that followed are all baseline now, folded into v3.0.x. There is no `v2.0.6` tag.++> **🩹 2026-08-14 — v4.0.1: the point release an external review earned.** Four review rounds over the v4.0.0 tree, each one probing the code rather than reading it. Nothing here is a new feature; every line is a thing v4.0.0 got wrong.+>+> - **THE UPDATER IS TRANSACTIONAL, AND IT WAS NOT.** The fetch result was ignored and every pull failure went to `git reset --hard $UPSTREAM` — a LOCAL tracking ref, so when the fetch was the thing that failed, the reset landed on the stale commit already checked out, exited 0, and `post_update.sh` then ran against the old tree. Update reported success and nothing had changed. Now: a failed fetch is fatal, divergence is PROVEN by `git rev-list --count $U..HEAD` rather than inferred from whatever made the merge fail, a dirty worktree stops the run instead of being destroyed, and an untracked file that upstream now tracks is named and refused rather than deleted as an "obstruction". Measured on real repositories: offline → exit 1, HEAD unmoved · fast-forward → converges · dirty tracked file → edit preserved · untracked collision → path named, file intact.+> - **The Update also never repaired the known-broken transformers.** `install.js` had promised since 2026-07-10 that "uv downgrades an already-installed 5.13.0 on the next Update"; nothing in the update path ever constrained transformers, so that sentence was false for a month and an install stuck on 5.13.0 could click Update, watch it succeed, and still not render a frame. `post_update.sh` step 2b is a fatal `require` on the same uv resolve as the mlx trio. Proven in a throwaway venv seeded with the broken version.+> - **The HQ tier never had a live preview at all.** `high.preview_every=2` promised a lane `generate_hq` never wired, on both sides — and `_build_live_preview` raised into its own never-fatal `except` and returned `None`, so the one component whose job is to stop things silently not happening was silently not happening. Real HQ render: 14 PNGs published every-2. The byte-identity invariant holds on the new lane — preview ON and OFF give the same sha256.+> - **The storyboard planner's laws are composable now.** Law enforcement ran first and premise repair ran last, so a repair could hand back a shot with the premise restored AND an unwritten speech act attached, under a warning saying the premise was back. Re-rolls spliced their fix into the ORIGINAL plan, so fixing shot 2 threw away shot 1's fix. And the appearance law generalised itself into never naming a species at all — the owner's "humanoid animals" film came back with twelve shots of ordinary humans. Fixed as a class: a repair that breaks a law is rejected, the final invariant scan runs after the LAST mutation whichever pass made it, every premise term is required (capped by a presence budget — a five-species brief cannot fill a two-shot film), and a degraded plan says `degraded` out loud instead of returning `ok: true`.+> - **Characters: displayed = submitted = restored.** The two surfaces generated different jobs for the same character (face 0.8 here, 1.0 there, voice never submitted at all), Load Params knew only the retired 736×416 so every Draft reopened as Pro, and the voice was never restored. One contract now, and the gate EXECUTES the panel's own JavaScript against a DOM shim — `scripts/extract_panel_js.py` pulls the real functions out of the panel and raises on a rename, so coverage cannot decay back to grepping. Its first version passed by string-matching while the live loader was broken.+> - **Readiness is declared per capability, not per file label.** `kind: "base"` had come to mean both "fetched on a fresh install" and "the panel cannot render without it". Gemma 3 is the first and not the second, so a half-downloaded PLANNER model hid Start on an install that renders perfectly. `required_files.json` now declares what `render` / `enhance` / `characters` / `high_tier` / `live_preview` / `h3` each need, and both the panel and `pinokio.js` read it.+> - **Every offer follows the generation actually installed.** A 2.3-pinned install was offered the 30 GB 2.5 Q8 pack it does not load; the H3 entry disagreed with the panel about split model roots and offered a 75 GB install for weights already on disk; the missing-decoder notice fired over H3 renders, image jobs and training runs with an Install link for a decoder they never use. All three resolve the active version — `pinokio.js` reads `LTX_MODEL_VERSION` out of the `ENVIRONMENT` file the launcher sources.+> - **Copy and store listing.** The Pinokio store listing still said LTX 2.3 three weeks after 2.5 shipped. H3 is described as a peer of LTX everywhere rather than a lesser tier, a missing engine is an offer rather than a downgrade, and `docs/H3_ENGINE.md` says to put persistent overrides in `ENVIRONMENT` — the shell `export` that "loses" a working H3 install on the next restart.+>+> **Known-remaining, carried to v4.0.2** (round-4 review, all narrow, all with fixes in progress): the updater's obstruction set matches exact untracked leaf paths, so a parent-directory collision or a gitignored file (`ENVIRONMENT`) can still be cleared by a legitimate reset after genuine divergence; the Character gate duplicates the submit expressions rather than executing that half; and an LTX-2.3 Q8 click still receives the 2.5 pack's size and name in its notification text (the download itself is correct).> **🎬 2026-08-13 — v4.0 INTEGRATION: LTX-2.5 becomes the generation the panel SERVES, not just the one it loads.** The registry has carried 2.5 since 2026-08-12 and the weights have been mirrored since the same day; what was missing was the product. The panel still called the engine "LTX-2.3", still priced tiers with two hand-rolled subtitle writers printing 2.3-era minutes, still offered a duration one lane silently rounded away, and had no way to say "you can have the good tier, it costs 29.5 GB, here is the button." The FROM-ZERO gate — a fresh Pinokio install rendering one clip — was the last blocker before public promote, and it passed.>@@ -9,7 +22,7 @@> - **The anti-mosaic preflight had been DEAD since 2.5 became the default** (`_canonical_layout()` compared MODEL_ID against the *active* generation's q4 path). The guard written after the June-2026 rainbow-mosaic investigation was itself switched off in the field. Fixed and proven with the bug's own repro — withhold `spatial_upscaler_x2_v1_1.safetensors` and the refusal names the file — plus a **pre-render** layer that disables Generate before Gemma loads instead of failing 30 s in.> - **The 7-second lie, and the three other duration tables behind it.** A shot set to 7 s on H3 snapped to 5 s (124 frames) while the select still read "7 s" and the estimate agreed with the select. Every menu now reads the engine's own table; an off-axis board round-trips with `7 s · nearest 5s`, and H3's 15 s is reachable for the first time.> - **2.5 characters were routed onto an ungraded pipeline, and then could not render at all.** `balanced_q8_fast` (a 2.3 speed optimisation, no version gate) rerouted Balanced → `high`, which demanded the 29.5 GB HQ add-on; and the panel's LoRA-fusion patch built its DiT from `LTXModel()` **defaults**, so every 2.5 render with a LoRA attached died on `Received 1 parameters not in model: keyframes_abs_pos_embedding`. Both fixed; characters now render q8 + distilled — the recipe every graded 2.5 clip ran — proven end to end **with the add-on withheld from disk**, clean identity at frame 60.-> - **The voice gets its own strength — and the shipped default is the graded `1.0`.** The face file's audio-branch deltas are noise and at equal strength they are LOUDER than the voice file's signal (median ‖D‖ 1.45 vs 1.10), so running the voice hotter is what makes it win: parity is 1.2, 1.4 is the first rung with real headroom. The SPLIT CONTROL ships and the help-dot explains the mechanism, but the **default stays at 1.0/1.0 — the pair every graded clip was rendered at and passed on.** 1.4 was the pre-release default and no ear had passed it; a default nobody has listened to is not a default. Raise it when one says so. `character_voice_strength` is asserted into `params` in the same commit that adds it — the allowlist trap, closed with a test rather than a hope.+> - **The voice gets its own strength, and the graded default is `1.0`.** The face file's audio-branch deltas are noise and at equal strength they are LOUDER than the voice file's signal (median ‖D‖ 1.45 vs 1.10) — which is the argument for giving the voice its own number. The measurement then argued for turning it up (parity 1.2, headroom at 1.4) and **the owner's ear rejected that: 1.0 vs 1.4 graded side by side, verdict "candidate seems less good".** So `1.0/1.0` is the default and it is settled, not provisional. The SPLIT CONTROL ships and the help-dot explains the mechanism; what it no longer does is recommend climbing the ladder. `character_voice_strength` is asserted into `params` in the same commit that adds it — the allowlist trap, closed with a test rather than a hope.> - **Live preview + Stop early.** `--live-preview tae` with the 22 MB decoder now shipping as an ordinary `github-release` registry row. Preview on vs off is **byte-identical** (`79ec11a7…` both) with the preview demonstrably running; an abort exits **75**, writes no mp4, and resolves as `status: "stopped"` — muted card, "Nothing was saved" — not a failure. The `meaningful` gate is server-owned because the rule differs per pipeline (estimate 6 on distilled, 2 on res_2s); a Stop button over a noise field aborts takes that were going to be fine.> - **Settings → Storage**, measured by walking the real directories rather than reading `size_gb`: LTX-2.3 57.8 GB, the High add-on 29.5 GB (sized from its two filenames — a directory walk there deletes the q8 pack), Gemma 3 8.1 GB shown greyed with *why it cannot go*. `/models/remove` refuses the active model, an in-flight folder and an unregistered key, and never takes a path from the client.> - **Both foundation defects closed**: `assert_registry` is **113 passed, 0 failed, 0 known defects pinned** — the first honestly green run since the markers went in.diff --git a/install.js b/install.jsindex 8e4ac64..41fa9be 100644--- a/install.js+++ b/install.js@@ -273,8 +273,15 @@ module.exports = {// '__module__'": the Gemma text-encoder load silently no-ops ("done in// 0.0s") → downstream "Model not loaded. Call load() first." Known-good:// 5.7.0 (our validated build) and 5.12.x. Cap it on the SAME resolve as- // mlx-lm so the constraint sticks (uv downgrades an already-installed- // 5.13.0 on the next Update). Diagnosed by @saved-j + @xandreau.+ // mlx-lm so the constraint sticks. Diagnosed by @saved-j + @xandreau.+ //+ // The Update path enforces this too — scripts/post_update.sh step 2b,+ // a `require` (fatal) step. That sentence used to live here as "uv+ // downgrades an already-installed 5.13.0 on the next Update" and was+ // simply false for a month: nothing in the update path constrained+ // transformers at all, so an existing 5.13.0 survived every Update and+ // the install stayed unable to generate anything. A promise about+ // another file now names the step that keeps it."uv pip install --python env/bin/python 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1' 'transformers>=5.0.0,<5.13.0'",// Y3 — Train Character ships in 3.0. Without ltx-trainer-mlx in// the venv, the trainer subprocess fails at `import yaml` becausediff --git a/install_h3.js b/install_h3.jsindex 546f174..ef83923 100644--- a/install_h3.js+++ b/install_h3.js@@ -45,7 +45,7 @@ module.exports = {{method: "notify",params: {- html: "<b>Installing Hailuo H3 (optional, ~75 GB).</b><br>A second video engine that generates picture, dialogue and sound together. Needs a 64 GB+ Apple Silicon Mac. MiniMax Community License — territory restrictions apply. Resumable if interrupted."+ html: "<b>Installing Hailuo H3 (second video engine, ~75 GB).</b><br>Generates picture, dialogue and sound together, and sits beside LTX in the engine switcher. Needs a 64 GB+ Apple Silicon Mac. MiniMax Community License — territory restrictions apply. Resumable if interrupted."}},diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 43a6632..d36ce77 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -3768,15 +3768,140 @@ def base_missing() -> list[str]:the panel doesn't false-positive against a working manual install."""if not str(MODEL_ID).startswith("/"):return []- out = []- for r in _repos():- if r.get("kind") != "base":+ return capability_missing("render")+++def _capabilities() -> dict:+ return _REQUIRED.get("capabilities") or {}+++def capability_repo_keys(name: str, version_id: str | None = None) -> list[str]:+ """Which repos a capability needs, for the ACTIVE generation.++ `render` is declared per version because which packs render is exactly what a+ generation IS: on ltx25 that is q4_25 + gemma4_25, and Gemma 3 is not in the list.+ """+ cap = _capabilities().get(name) or {}+ by_version = cap.get("repos_by_version")+ if by_version:+ vid = version_id or ACTIVE_MODEL_VERSION+ keys = by_version.get(vid)+ if keys is None:+ keys = by_version.get(cap.get("default_version") or "") or []+ return list(keys)+ return list(cap.get("repos") or [])+++def capability_missing(name: str, version_id: str | None = None) -> list[str]:+ """Files this capability is missing, as `<local_dir>/<file>` — [] when it works.++ ONE QUESTION PER CAPABILITY. `kind: "base"` had come to mean both "fetched on a+ fresh install" and "the panel cannot render without it", and those are different+ questions with different answers: Gemma 3 is fetched on every install and the active+ 2.5 generation does not render with it, so a half-downloaded planner model was+ reporting the RENDERER incomplete and hiding Start. The preview decoder had the same+ bug one commit earlier. Asking per capability is what stops the next one.+ """+ by_key = {r.get("key"): r for r in _repos()}+ out: list[str] = []+ for key in capability_repo_keys(name, version_id):+ repo = by_key.get(key)+ if not repo:continue- for fname in _repo_missing(r):- out.append(f"{r['local_dir']}/{fname}")+ for fname in _repo_effective_missing(repo):+ out.append(f"{repo['local_dir']}/{fname}")++ # PATHS, VENVS AND MODEL TREES COUNT TOO. This evaluated `repos` only and+ # silently returned [] for anything declared with the other three keys — so+ # the H3 capability reported ok:true on a machine where h3_paths() correctly+ # said not_installed. A capability that answers "fine" for a component set it+ # never looked at is worse than no capability, because the whole point of the+ # declaration was to stop two consumers disagreeing.+ cap = _capabilities().get(name) or {}+ for rel in cap.get("paths") or ():+ if not (ROOT / rel).exists():+ out.append(rel)+ venv_any = cap.get("venv_any") or ()+ if venv_any and not any(_venv_python_resolves(ROOT / rel) for rel in venv_any):+ out.append(venv_any[0] + " (no resolvable interpreter)")+ roots, models = cap.get("model_roots") or (), cap.get("models") or ()+ if models:+ for root in roots or ("",):+ base = ROOT / root if root else ROOT+ missing = [m for m in models if not (base / m).is_file()]+ if not missing:+ break+ else:+ missing = []+ for m in models:+ if not any((ROOT / r / m).is_file() for r in (roots or ("",))):+ missing.append(m)+ out.extend(missing)return out+def _venv_python_resolves(path: Path) -> bool:+ """A venv entry counts only when it is an interpreter that still resolves.++ `bin/activate` existing proves nothing: uv creates bin/python as a symlink+ chain into a shared managed interpreter, and installing another pack can+ move it — leaving activate in place beside a dangling python. That is the+ v3.4.0 "installed other packs and Hailuo H3 vanished" report. `.exists()`+ follows symlinks, so a broken chain is definitively false.+ """+ try:+ return path.exists() and path.name != "activate"+ except OSError:+ return False+++def capability_state(name: str, version_id: str | None = None) -> dict:+ """{ok, blocking, label, missing[]} — what the UI renders and the gate reads."""+ cap = _capabilities().get(name) or {}+ missing = capability_missing(name, version_id)+ return {+ "ok": not missing,+ "blocking": bool(cap.get("blocking")),+ "label": cap.get("label") or name,+ "engines": list(cap.get("engines") or []),+ "missing": missing,+ }+++def capabilities_state(version_id: str | None = None) -> dict:+ return {name: capability_state(name, version_id)+ for name in _capabilities() if not name.startswith("_")}+++def _repo_effective_missing(repo: dict) -> list[str]:+ """THE answer to "what is this repo missing" — the one /models already gives.++ There were two answers and they disagreed on a live install: /models reported all 11+ repos complete and model_integrity ok/42, while /status reported a base file missing,+ so the panel showed "Base models needed before you can render (1 files left)" over a+ perfectly working install and never stopped.++ The gap was not staleness, it was two different questions. repo_status_list() resolves+ each repo through the REGISTRY when it backs a registered pack (so a pack an env var+ moved, or one that shares a directory with another, is checked where it actually+ lives) and falls back to the HF CACHE when the local dir is short (what manual and dev+ installs use). base_missing() did neither: it walked ROOT/local_dir and believed it.++ Now both call this, so the blocker card and the Models modal cannot contradict each+ other again — the card is a rendering of the modal's answer, not a second opinion.+ """+ quant = _quant_for_repo_key(repo.get("key"))+ local_missing = pack_missing_files(quant) if quant else _repo_missing(repo)+ if not local_missing:+ return []+ total = len(repo.get("files", []))+ cache_missing = _repo_missing_in_cache(repo)+ if cache_missing is not None:+ if (total - len(cache_missing)) > (total - len(local_missing)):+ return cache_missing+ return local_missing++def pack_missing_files(quant: str, version_id: str | None = None) -> list[str]:"""Files missing for ONE pack of ONE model version (bare filenames).@@ -4113,6 +4238,9 @@ def repo_status_list() -> list[dict]:# model version gets its own answer instead of inheriting 2.3's._quant = _quant_for_repo_key(r.get("key"))local_missing = pack_missing_files(_quant) if _quant else _repo_missing(r)+ # NOTE: _repo_effective_missing() above collapses this same local+cache choice+ # into one call for /status. This loop keeps the expanded form because it also+ # needs `where`/`location`/`present` for the row — same rule, more outputs.total = len(r.get("files", []))local_present = total - len(local_missing)@@ -6333,9 +6461,12 @@ LTX_VOICE_STRENGTH_HELP = ("they both land at nearly full strength. The face file was trained on still ""images, so the marks it leaves on the audio side carry no voice — but they ""are still there, and at equal strength they are louder than the voice "- "file's. Running the voice a little hotter than the face is what makes it "- "win. 1.4 is the first setting with real headroom; 1.2 is about even. Below "- "1.0 the voice is mostly the face file's noise.")+ "file's. That is why the voice gets its own number instead of sharing the "+ "face's. 1.0 is where it sits, and it is the setting that won the listening "+ "test: a hotter voice was graded side by side against it and came out worse. "+ "Raising it is here if you want it, but go in small steps, and only when a "+ "particular voice is being drowned rather than as a general improvement. "+ "Below 1.0 the voice is mostly the face file's noise.")# Why a trained character needs the Q8 pack.## "Same render time either way" is MEASURED, not assumed: 1024x576x121,@@ -7324,6 +7455,26 @@ def live_preview_enabled() -> bool:return str(get_settings().get("live_preview", "on")).lower() != "off"+def live_preview_state() -> dict:+ """WHY there is no preview, not just that there isn't one.++ Two very different absences were indistinguishable to the client, and both+ rendered as nothing at all: the user switched it off (fine, they know), or the+ 22 MB decoder is missing (they have no idea, and a feature the release+ announced is silently not happening). An install that predates v4.0 and updates+ without the decoder step is exactly the second case.++ `reason` is what the UI is allowed to say out loud.+ """+ if not TAE_CHECKPOINT.is_file():+ return {"on": False, "reason": "missing_decoder",+ "note": "Live preview is off because its 22 MB decoder isn't "+ "installed — Settings → Models → Live-preview decoder."}+ if str(get_settings().get("live_preview", "on")).lower() == "off":+ return {"on": False, "reason": "off", "note": ""}+ return {"on": True, "reason": None, "note": ""}++def live_preview_dir(job_id: str) -> Path:"""Per-job scratch for the preview contract: status.json, the PNGs and theABORT sentinel. Per JOB, not per panel, so a stale sentinel from a previous@@ -7498,6 +7649,14 @@ def ltx_tiers_payload() -> dict:"q8_character": LTX_Q8_CHARACTER_HELP,"preview": LTX_PREVIEW_HELP,},+ # Why the preview is absent, so the Now card can say it instead of+ # showing nothing and letting the user conclude the feature is broken.+ "preview_state": live_preview_state(),+ # Per-capability readiness, from required_files.json → capabilities.+ # The client reads THIS rather than re-deriving what needs what: the+ # notice above uses `live_preview.engines` to know which jobs it is+ # even about, and `blocking` is the only thing allowed to hard-block.+ "capabilities": capabilities_state(),# The character strip's two chips, and the PIPELINE they submit —# resolved per generation so the markup never owns that rule."character": character_strip_payload(),@@ -13578,16 +13737,17 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# never mattered; at q8 ~90 % of both survives, which is why fixing the# face is what surfaced the voice.#- # So running the voice a little hotter than the face is what makes it- # win. Parity is 1.2; 1.4 is the first setting with real headroom, and- # it is independently where current community guidance for 2.5 puts- # "balanced".+ # That is the MEASUREMENT, and it argued for running the voice hotter:+ # parity is 1.2, and 1.4 was the first rung with real headroom — also+ # where community guidance for 2.5 puts "balanced".#- # THE DEFAULT IS 1.0 ANYWAY, and that is a listening decision, not a- # measurement one. 1.0/1.0 is the pair every graded clip was rendered- # at and passed on; the hotter rungs are real and reachable — the split- # control ships, the help text explains the mechanism — but a default- # nobody has listened to is not a default. Raise it when an ear says so.+ # THE EAR DISAGREED, and the ear is the authority here. 1.0 and 1.4+ # were rendered as a graded pair and the owner rejected 1.4: "candidate+ # seems less good". So the default is 1.0 — the pair every graded clip+ # was rendered at and passed on — and it is not provisional. The split+ # control still ships and the ladder is still reachable; what changed is+ # that the panel no longer recommends climbing it. An SNR argument is a+ # reason to give the voice its own number, not a reason to turn it up.## THE ALLOWLIST TRAP: make_job builds params from named reads, and a# field nobody reads here is dropped with no error — the render@@ -16779,6 +16939,14 @@ def run_job_inner(job: dict) -> None:# see hq_weights()."dev_transformer": hq_weights()["dev_transformer"],"distilled_lora": hq_weights()["distilled_lora"],+ # Live preview, same contract as the t2v branch. This was+ # missing, so High promised preview_every=2 in the quality table+ # and shipped no frames — and the missing-decoder notice then+ # fired on a lane that had never been wired at all. The lane rule+ # (every 2 on res_2s, whose odd ANCHOR estimates come back+ # patchy) is decided in _live_preview_params from the quality+ # cell, so the helper is told the number rather than guessing.+ **_live_preview_params(job, p),"prompt": p["prompt"],"negative_prompt": p.get("negative_prompt", ""),"output_path": str(raw_out),@@ -21008,7 +21176,9 @@ class Handler(BaseHTTPRequestHandler):# This endpoint now does ONLY:# 1. look up the character → resolve face + (optional) audio LoRA# 2. map duration string → frames (5s/7s/10s)- # 3. map quality string → width/height (draft = 736x416, else 1024x576)+ # 3. map the SIZE token → width/height (draft = 704x384, pro = 1024x576;+ # 704x384 because both old sizes were off the 64-grid the two-stage+ # lane snaps to, so the chip advertised a canvas it never delivered)# 4. take the user's prompt verbatim — no prefix, no suffix, no# negative-prompt injection, no framing word# 5. build the same form payload /queue/add accepts and call@@ -21093,11 +21263,11 @@ class Handler(BaseHTTPRequestHandler):# on 2.5 q8 the graded recipe is the face at 1.0.## The voice takes its own number for the reason spelled out in- # make_job: the face file's audio-branch deltas are noise, they are- # louder than the voice file's signal at equal strength, and running- # the voice hotter is what makes it win. It still DEFAULTS to 1.0 —- # the graded pair — because the hotter rungs have not been listened- # to. Same default on both lanes or the two surfaces disagree again.+ # make_job: the face file's audio-branch deltas are noise and are+ # louder than the voice file's signal at equal strength. It defaults+ # to 1.0 — the graded pair, and the arm that won the listening test+ # against a hotter one. Same default on both lanes or the two+ # surfaces disagree again.try:char_strength = float((form.get("character_strength", ["1.0"])[0] or "1.0"))@@ -24101,6 +24271,9 @@ HTML = r"""<!doctype html>layout editor uses, so there is one mechanism for "this surface needsthe stage" rather than two. */body[data-workflow="storyboard"].sb-full .stage-pane > .player-surface { display: none; }+ /* The close control is a storyboard affordance only — see the button's own comment. */+ #sbCollapsePlayerBtn { display: none; }+ body[data-workflow="storyboard"] #sbCollapsePlayerBtn { display: inline-flex; }#sbStage {display: none;@@ -28504,6 +28677,13 @@ HTML = r"""<!doctype html>animation: nowThumbPulse 2.4s ease-in-out infinite;}@keyframes nowThumbPulse { 0%,100% { opacity:.10 } 50% { opacity:.26 } }+ /* The one-line "your decoder is missing" note. Informational, not alarming:+ the render is fine, only the preview of it is absent. */+ .now-preview-missing {+ font-size: 11.5px; color: var(--muted);+ padding: 6px 2px 0; line-height: 1.45;+ }+ .now-preview-missing a { color: var(--accent-bright); }/* ABORTING — frozen on the last frame it managed to show. */.now-thumb.is-aborting img { opacity: .55; }/* Failure-card action row — Retry + Close on the failed Now card.@@ -30361,6 +30541,39 @@ HTML = r"""<!doctype html>border-color: var(--eng-soft, var(--accent));background: var(--eng-dim, var(--accent-dim));}+ /* The repeat-click nudge. Pulses the SEGMENT, in the engine's own accent,+ because the badge beside it is display:none under 1500px — see the+ media query below. */+ @keyframes eng-offer-nudge {+ 0% { box-shadow: 0 0 0 0 var(--eng-soft, var(--accent)); }+ 45% { box-shadow: 0 0 0 5px transparent; }+ 100% { box-shadow: 0 0 0 0 transparent; }+ }+ body > header .eng-seg.offer-nudge {+ animation: eng-offer-nudge 600ms ease-out 2;+ background: var(--eng-dim, var(--accent-dim));+ }+ /* An inline action inside a toast — the way back to the full install card+ after the toast has replaced it. */+ .phos-toast-action {+ color: var(--accent-bright); margin-left: 8px;+ font-weight: 600; white-space: nowrap;+ }+ /* The troubleshooting disclosure inside the install card. Closed by+ default — the paths are for the 1% of installs that half-land. */+ .h3-diag { margin: 0; }+ .h3-diag > summary {+ cursor: pointer; font-size: 12px; color: var(--muted);+ list-style: none; user-select: none;+ }+ .h3-diag > summary::-webkit-details-marker { display: none; }+ .h3-diag > summary::before { content: '▸ '; }+ .h3-diag[open] > summary::before { content: '▾ '; }+ .h3-diag > p {+ margin: 6px 0 0; font-size: 11.5px; color: var(--muted);+ font-family: var(--ph-font-mono); word-break: break-all;+ }+/* Narrow windows: the header is flex-wrap:nowrap + overflow:hidden, andthe status pills already fill it on a laptop. Drop the segment labelsbefore anything gets clipped — the marks and the active tint still@@ -31385,10 +31598,11 @@ HTML = r"""<!doctype html><input type="hidden" name="character_strength" id="characterStrength" value="1.0"><!-- The VOICE half of a character's strength. A character is two trainedfiles and the face file's audio-branch deltas are noise that is- louder than the voice file's signal at equal strength — so running- the voice hotter is what makes it win, and the split control below is- how you do it. The DEFAULT is the graded pair, 1.0/1.0; the hotter- rungs are an ear's decision, not the shipped starting point.+ louder than the voice file's signal at equal strength — which is why+ the voice gets its own number, not why it should be turned up. The+ default is the graded pair, 1.0/1.0, and it beat a hotter arm on the+ owner's ear. The split control below is still there if a particular+ voice is being drowned.MUST be in make_job's named reads or it silently no-ops. --><input type="hidden" name="character_voice_strength" id="characterVoiceStrength" value="1.0">@@ -32988,14 +33202,14 @@ HTML = r"""<!doctype html></div></div>- <!-- Character LoRA strength. Default 0.8 — slightly under 1.0- because the workshop/copper-pipe/gas-lamp prompt content- triggers mesh/sparkle artifacts in the BASE LTX-2.3 model- (confirmed via base-only-no-LoRA test 2026-05-17, see- lora-lab/STATE.md). At 0.8 the identity still locks and- the artifact-prone prompt regions render cleaner. Slider- exposed so users can dial up to 1.0 for max identity, or- down to 0.5 when a prompt triggers the base-model basin. -->+ <!-- Character LoRA strength. THE `value` BELOW IS A PLACEHOLDER: the+ control is painted from window.CHARACTERS.charStrength by+ charactersSyncStrengthControls() on init and on every compose+ open. It used to be a hardcoded 0.8 — a 2.3-era correction for+ mesh/sparkle artifacts in the BASE model — and when the state+ default moved to 1.0 to match the server, the markup did not,+ so an untouched form DISPLAYED 0.80 and SUBMITTED 1.0. Never+ hardcode a value here again; change the state default. --><div class="characters-strength-row"><label for="charactersStrength" class="characters-strength-label">Character LoRA strength@@ -33858,6 +34072,22 @@ HTML = r"""<!doctype html></svg><span class="po-act-label">Animate</span></button>+ <!-- STORYBOARD ONLY. The shot list is the storyboard tab's primary surface and+ the player is a guest on it, so the guest carries the way out — reported by+ cocktailpeanut: "i can't seem to find a way to hide this preview video and+ it's just blocking everything". The Shot list / Player toggle below the+ player already did this, but nobody looks under the thing they want gone;+ the control belongs ON it. CSS keeps this hidden everywhere else, because on+ the Video and Images tabs the player IS the primary surface and a close there+ would orphan the tab. -->+ <button id="sbCollapsePlayerBtn" class="po-act po-act-sbclose" type="button"+ onclick="sbSetStage('list')" title="Hide the preview and show the shot list (Esc)">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" stroke-width="1.5"+ stroke-linecap="round"/>+ </svg>+ <span class="po-act-label">Hide preview</span>+ </button><button id="expandBtn" class="po-act" type="button"onclick="openExpandLightbox()" title="Expand to fullscreen (Esc to close)"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">@@ -34505,7 +34735,11 @@ HTML = r"""<!doctype html>onclick="if(event.target===this) closeH3InstallCard()"><div class="models-card"><div class="models-head">- <h2 id="h3InstallTitle">Hailuo H3 · optional engine</h2>+ <!-- ENGINES ARE PEERS. This read "Hailuo H3 · optional engine", which+ told a user that half the panel's video capability was a side dish.+ A missing engine is an OFFER — the title names the engine and its+ price, and the body says what it does. -->+ <h2 id="h3InstallTitle">Hailuo H3 · 75 GB</h2><button class="ghost-btn" onclick="closeH3InstallCard()">Close</button></div><div class="models-hint" id="h3InstallBody"></div>@@ -37743,7 +37977,11 @@ function trainUpdateAdvancedFields() {// enhance=false, video_skip=1+audio_skip=1) are applied server-side per// docs/API.md. The UI collects prompt (trigger pre-filled) + duration +// quality. Quality maps server-side to resolution + recipe:-// draft → 736x416, ~3:30 wall; high → 1024x576, ~6:00 wall.+// draft → 704x384; pro → 1024x576. Both render on the generation's own+// character recipe (2.5: q8 + distilled), resolved server-side — the chips+// carry a SIZE, never a pipeline. The wall times that used to sit here were+// 2.3-era and the canvas was the retired 736x416; measured 2.5 numbers live+// in LTX_MEASURED_ETA, which is where the UI reads them from.window.CHARACTERS = {list: [], // [{id, name, trigger, pronoun, subject_noun, sample_image_url, ...}]@@ -37751,9 +37989,16 @@ window.CHARACTERS = {duration: '7s', // 5s | 7s | 10s | 15squality: 'pro', // SIZE token: draft | pro. The PIPELINE is the// generation's answer, resolved server-side (§5.6).- // Character LoRA strength (applied to both face_lora and audio_lora).- // Default 0.8 reduces over-trained baked artifacts at small identity cost.- charStrength: 0.8,+ // ONE CHARACTER, ONE PAIR OF STRENGTHS, WHICHEVER SURFACE LAUNCHED IT.+ // These were 0.8 and "applied to both face_lora and audio_lora" — a 2.3-era+ // correction for over-baked quirks at 5000 steps, and a comment that stopped+ // being true when the server split the two files. The server has defaulted+ // face 1.0 / voice 1.0 since; this surface kept sending 0.8 and never sent a+ // voice value at all, so the same character rendered face 0.8 / voice 1.0+ // here and face 1.0 / voice 1.0 from the Manual tab. Same numbers on both+ // lanes or the surfaces disagree again.+ charStrength: 1.0,+ voiceStrength: 1.0,// Reference audio for i2v_clean_audio mode (character lip-syncs to// this clip). Image-to-video deliberately omitted on the Characters// surface per Mr Bizarro 2026-05-16.@@ -37860,6 +38105,7 @@ async function charactersInit() {if (!window.CHARACTERS.initialised) {window.CHARACTERS.initialised = true;charactersRenderChips();+ charactersSyncStrengthControls(); // the slider shows what we will submitcharactersBackToGrid(); // ensure grid state visible}await charactersLoadList();@@ -37962,6 +38208,9 @@ function charactersOpenCompose(id) {const c = (window.CHARACTERS.list || []).find(x => x.id === id);if (!c) return;window.CHARACTERS.selected = c;+ // Every entry to the compose view repaints the strength control from state,+ // so a value restored by Load Params is on screen before the user can submit.+ charactersSyncStrengthControls();// Toggle states.const grid = document.getElementById('charactersGridState');@@ -38108,6 +38357,26 @@ function charactersUpdateStrengthDisplay(val) {if (out) out.textContent = v.toFixed(2);}+// THE CONTROL IS RENDERED FROM THE STATE, NEVER THE OTHER WAY AROUND.+// The slider's `value` was hardcoded in the markup, so when the state default+// moved to 1.0 the two silently disagreed: an untouched form DISPLAYED 0.80 and+// SUBMITTED 1.0. The user reads one number and gets another, and no amount of+// care in the submit path can fix a control that was never told what it holds.+// Called on every entry to the compose view and after Load Params.+function charactersSyncStrengthControls() {+ const v = Number(window.CHARACTERS.charStrength ?? 1.0);+ const slider = document.getElementById('charactersStrength');+ if (slider) {+ // The markup's min/max must not silently clamp the state either.+ const lo = parseFloat(slider.min), hi = parseFloat(slider.max);+ if (isFinite(lo) && v < lo) slider.min = String(v);+ if (isFinite(hi) && v > hi) slider.max = String(v);+ slider.value = String(v);+ }+ const out = document.getElementById('charactersStrengthValue');+ if (out) out.textContent = v.toFixed(2);+}+async function charactersGenerate() {const c = window.CHARACTERS.selected;if (!c) return;@@ -38132,7 +38401,11 @@ async function charactersGenerate() {fd.set('quality', window.CHARACTERS.quality);// Character LoRA strength — passed through so the backend can apply// it to both face_lora and audio_lora at job-build time.- fd.set('character_strength', String(window.CHARACTERS.charStrength || 0.8));+ // BOTH strengths, always. Sending only the face left the voice to the+ // server's default, which meant this surface could not express the pair it+ // was showing and a sidecar could never round-trip it.+ fd.set('character_strength', String(window.CHARACTERS.charStrength ?? 1.0));+ fd.set('character_voice_strength', String(window.CHARACTERS.voiceStrength ?? 1.0));// Reference audio (i2v_clean_audio mode) — optional.if (window.CHARACTERS.audioPath) fd.set('audio', window.CHARACTERS.audioPath);// Extra LoRAs come from the portaled #lorasDetails picker — read@@ -38201,6 +38474,36 @@ function charactersEscapeAttr(s) { return charactersEscapeHtml(s); }// sidecar values. Re-render chips to update .active classes.// 5. Repopulate the prompt textarea with prompt_body verbatim and// refresh the preview.+// ONE RESTORER, BOTH LOAD PATHS. Load Params has two: the Manual path, and+// this Characters branch, which returns early and therefore never reached the+// Manual path's strength restoration at all — so a character clip reloaded+// with BOTH strengths silently back at their defaults. The external review+// found the Manual half fixed and this half untouched, which is exactly what a+// second copy of a rule buys you. There is one copy now.+function _restoreCharacterStrengths(p) {+ const put = (value, inputId) => {+ if (typeof value === 'undefined' || value === null) return;+ const num = parseFloat(value);+ if (Number.isNaN(num)) return;+ const inp = document.getElementById(inputId);+ if (inp) inp.value = num;+ };+ put(p.character_strength, 'characterStrength');+ put(p.character_voice_strength, 'characterVoiceStrength');+ if (typeof _renderCharsAppliedNote === 'function') _renderCharsAppliedNote();+ // The Characters-tab state and its visible slider follow the same numbers,+ // so a clip reopened there shows what it will re-submit.+ if (window.CHARACTERS) {+ const f = parseFloat(p.character_strength);+ const v = parseFloat(p.character_voice_strength);+ if (!Number.isNaN(f)) window.CHARACTERS.charStrength = f;+ if (!Number.isNaN(v)) window.CHARACTERS.voiceStrength = v;+ if (typeof charactersSyncStrengthControls === 'function') {+ charactersSyncStrengthControls();+ }+ }+}+async function charactersLoadParams(p) {// 2026-05-17 — Characters is no longer its own workflow tab. Load Params// on a Characters-origin sidecar restores EVERYTHING into the Manual@@ -38250,10 +38553,16 @@ async function charactersLoadParams(p) {// quality strip's click handler sets quality=high + the right w/h// already; calling _setCharacterQuality bypasses setQuality() so our// exact dims survive.+ // 704×384 IS THE DRAFT CANVAS. This recognised only the retired 736×416, so+ // every Draft render made since the size moved reopened as Pro — Load Params+ // silently changing the shot's geometry, which is the one thing it exists not+ // to do. Both are listed because sidecars written before the move are still+ // on disk and must still round-trip.const sidecarW = parseInt(p.width || '0', 10);const sidecarH = parseInt(p.height || '0', 10);- const isDraft = (sidecarW === 736 && sidecarH === 416)- || (sidecarW === 416 && sidecarH === 736); // vertical draft+ const _draftPairs = [[704, 384], [736, 416]]; // current, then legacy+ const isDraft = _draftPairs.some(([w, h]) =>+ (sidecarW === w && sidecarH === h) || (sidecarW === h && sidecarH === w));const charQualityGroup = document.getElementById('qualityGroupCharacter');if (charQualityGroup) {const sel = isDraft ? '[data-char-quality="draft"]' : '[data-char-quality="pro"]';@@ -38283,6 +38592,9 @@ async function charactersLoadParams(p) {if (wInp && sidecarW > 0) wInp.value = sidecarW;if (hInp && sidecarH > 0) hInp.value = sidecarH;+ // Both strengths — this branch returns before the Manual path's restoration.+ _restoreCharacterStrengths(p);+// Restore frames + duration. Frames is the source of truth for the// render; the duration field is metadata that drives the UI estimate.const sidecarFrames = parseInt(p.frames || '0', 10);@@ -38343,45 +38655,13 @@ async function charactersLoadParams(p) {const formPane = document.querySelector('aside.form-pane');if (formPane) formPane.scrollTop = 0;// Done — early-exit before the old dead-UI code that followed.- return;-- // -------- DEAD CODE BELOW (kept temporarily to avoid bigger diff) --------- // The block below targeted the now-unreachable Characters tab UI.- // Replaced by the Manual-tab restoration above; left in place so the- // diff stays narrow while we validate the new path. Will prune in a- // follow-up.- // eslint-disable-next-line no-unreachable- if (typeof charactersInit === 'function') {- await charactersInit();- }- if (!Array.isArray(window.CHARACTERS.list) || window.CHARACTERS.list.length === 0) {- throw new Error('character list empty after init');- }- charactersOpenCompose(p.character_id);- if (typeof p.duration === 'string' && p.duration) {- window.CHARACTERS.duration = p.duration;- }- if (typeof p.quality_choice === 'string' && p.quality_choice) {- // Legacy sidecars carry a PIPELINE token where the chips now carry a SIZE- // token. Map it to the equivalent canvas rather than replaying it: a clip- // recorded as `high` on 2.5 would otherwise re-request the two-stage HQ- // path and its 29.5 GB add-on — the exact route this tab was moved off.- // Both mean 1024x576, so the canvas the user sees is unchanged.- const _legacySize = { high: 'pro', balanced: 'pro', standard: 'pro',- quick: 'draft', draft: 'draft', pro: 'pro' };- window.CHARACTERS.quality = _legacySize[p.quality_choice] || 'pro';- }- charactersRenderChips();- // Prompt textarea. The verbatim prompt from the sidecar is the- // source of truth; we don't try to re-derive a "body" from it.- // Older sidecars used prompt_body; newer sidecars store the full- // prompt — fall back to the full prompt if prompt_body is empty.- const taOld = document.getElementById('charactersPrompt');- if (taOld) {- taOld.value = (typeof p.prompt_body === 'string' && p.prompt_body)- ? p.prompt_body- : (typeof p.prompt === 'string' ? p.prompt : '');- }+ // The Manual tab IS the character surface now, and the restoration above is+ // the whole of it. What used to follow this point was 37 lines targeting the+ // retired Characters-tab UI, unreachable behind a `return;` and labelled+ // "DEAD CODE BELOW (kept temporarily to avoid bigger diff)". It outlived the+ // follow-up that was meant to prune it and became actively dangerous: it held+ // NEWER-looking quality-mapping logic than the live path above, so the next+ // reader had two plausible implementations and only one that runs. Deleted.}@@ -40455,7 +40735,8 @@ function _engineTooltip(e, st, modeOk) {if (!e.builtin && !st.available) {return st.repairable? name + ' — needs repair; your weights are still on disk. Click for the one-click fix.'- : name + " — isn't installed. Click to see how (" + (e.install_size || '') + ').';+ : name + ' — available to install (' + (e.install_size || '')+ + '). Click to see what it does.';}if (!modeOk) {return name + ' — renders ' + (e.serves_label || 'other modes')@@ -40475,7 +40756,10 @@ function engineSegClick(id) {if (st.announced) return;if (!e.builtin && st.capable && !st.available) {const fn = e.install_card && window[e.install_card];- if (typeof fn === 'function') fn();+ // 'chip' tells the card this click came from the switcher, where a repeat+ // click means "yes, I know" rather than "explain it again". The explicit+ // buttons elsewhere pass nothing and always get the full card.+ if (typeof fn === 'function') fn('chip');return;}if (!e.builtin && !st.capable) return;@@ -41619,8 +41903,20 @@ function updateH3Availability(s) {// Install card — H3 is a Pinokio-script install (clone + venv + ~75 GB of// weights), not an in-panel `hf download`, so the panel explains the one// sidebar click rather than pretending it can do it itself. Same shape the-// Sharp/Qwen optional packs use.-function openH3InstallCard() {+// Sharp/Qwen packs use.+//+// SHOWN ONCE, THEN GET OUT OF THE WAY. Session-scoped: the first click on the+// H3 segment earns the full explainer; every click after that gets the nudge+// below instead. A modal that re-pops identically on every click stops being+// an explanation and becomes a wall — and the one thing a user who just read+// it wants to do is click the engine again.+//+// `source` is 'chip' from the engine switcher and undefined from the explicit+// "How to install" / "How to repair" buttons in the Models list, which must+// ALWAYS open the card: the user asked for it by name there.+let _h3CardSeen = false;+function openH3InstallCard(source) {+ if (source === 'chip' && _h3CardSeen) { _h3NudgeEngineOffer(); return; }const m = document.getElementById('h3InstallModal');const body = document.getElementById('h3InstallBody');if (body) {@@ -41650,10 +41946,12 @@ function openH3InstallCard() {no restart.</p>` : `<p style="margin:0 0 10px">- <b>Hailuo H3</b> is a second video engine: one prompt in, video- <em>and</em> synced dialogue <em>and</em> sound out. It runs fully- locally, alongside LTX — installing it changes nothing about your- existing renders.+ <b>Hailuo H3 is Phosphene's second video engine</b>, a peer of LTX+ rather than an add-on to it: one prompt in, video <em>and</em> synced+ dialogue <em>and</em> sound out, in a single pass. It runs fully+ locally and sits beside LTX in the engine switcher — installing it+ changes nothing about your existing renders, and either engine can+ drive any render you start.</p><p style="margin:0 0 10px;color:var(--muted)">${escapeHtml(H3.size_note || '')}@@ -41661,20 +41959,66 @@ function openH3InstallCard() {<p style="margin:0 0 10px">Install it from Pinokio, not from here: open the <b>Phosphene</b> entryin the Pinokio sidebar and click- <b>“Install Hailuo H3 (optional, ~75 GB)”</b>. The panel picks it up- within a couple of seconds — no restart.+ <b>“Install Hailuo H3 (second video engine, ~75 GB)”</b>. The panel+ picks it up within a couple of seconds — no restart.</p>`;+ // THE DIAGNOSTIC DUMP GOES BEHIND A DISCLOSURE. `missing` is a list of raw+ // absolute paths — indispensable when an install half-lands, and pure+ // noise the other 99% of the time. Printing it under a two-sentence pitch+ // made the offer read like an error report. Kept verbatim, folded shut.body.innerHTML = intro + `- ${missing.length ? `<p style="margin:0;color:var(--muted);font-size:12px">- Currently missing: ${escapeHtml(missing.join('; '))}</p>` : ''}`;+ ${missing.length ? `<details class="h3-diag">+ <summary>Details for troubleshooting</summary>+ <p>Currently missing: ${escapeHtml(missing.join('; '))}</p>+ </details>` : ''}`;}if (m) m.style.display = 'flex';+ _h3CardSeen = true;}function closeH3InstallCard() {const m = document.getElementById('h3InstallModal');if (m) m.style.display = 'none';}+// The lighter affordance, for every click after the first. Two jobs:+//+// 1. POINT AT THE OFFER. Pulse the H3 segment itself, not only its badge —+// the badge is `display:none` under 1500 px (the header runs out of room+// on a laptop long before the desktop does), so a badge-only highlight+// would be an invisible answer to a click on exactly the machines most+// likely to be running this.+// 2. LEAVE A DOOR OPEN. The nudge carries its own link back to the full+// explainer, so dismissing the modal once never costs the user the+// explanation permanently.+//+// Rides the panel's own phosToast rather than a second notification surface —+// the storyboard's engine picker already answers this exact situation with one+// (sbSetEngineMode), and two toasts that look different for the same event is+// how a UI starts feeling assembled rather than designed. The reopen link is+// appended to the element phosToast hands back.+function _h3NudgeEngineOffer() {+ const seg = document.querySelector('.eng-seg[data-engine="h3"]');+ if (seg) {+ seg.classList.remove('offer-nudge');+ void seg.offsetWidth; // restart the animation on a repeat click+ seg.classList.add('offer-nudge');+ setTimeout(() => seg.classList.remove('offer-nudge'), 1200);+ }+ // ONE LINE, and it has to FIT one: .phos-toast-msg is nowrap + ellipsis+ // inside a 480px cap, so a sentence that runs long is not a long toast, it+ // is a truncated one — "…install it from the Phosphene entry i…" was the+ // first draft, and it clipped exactly where the instruction lived.+ const el = phosToast('Hailuo H3 · 75 GB — install from the Pinokio sidebar.',+ { icon: 'ph-info', duration: 5000 });+ if (!el) return;+ const a = document.createElement('a');+ a.href = '#';+ a.className = 'phos-toast-action';+ a.textContent = 'What it is';+ a.onclick = (ev) => { ev.preventDefault(); el.remove(); openH3InstallCard(); };+ el.appendChild(a);+}+// Prompt enhancement via Gemma — wraps the upstream CLI's `enhance`// subcommand. Cold start ~12-15s (Gemma load), warm ~5s. Blocks the UI// during the request (just the button — rest of the form stays usable).@@ -44278,21 +44622,14 @@ async function loadParams() {}} catch (_) {}})();- // Also restore character_strength if recorded (defaults to 1.0).- if (typeof p.character_strength !== 'undefined') {- const sval = parseFloat(p.character_strength);- if (!Number.isNaN(sval)) {- const sInp = document.getElementById('characterStrength');- if (sInp) sInp.value = sval;- const row = document.getElementById('charsStrengthRow');- if (row) {- const range = row.querySelector('input[type="range"]');- const num = row.querySelector('input[type="number"]');- if (range) range.value = sval;- if (num) num.value = sval.toFixed(2);- }- }- }+ // BOTH strengths, because the character has two and the sidecar records+ // two. Only the face was restored here, so a clip rendered with a+ // deliberately hotter or colder voice reopened with the voice silently+ // back at its default — Load Params quietly changing the render it claims+ // to reload. The hidden inputs are the source the strip re-renders from,+ // so setting them and re-rendering restores both sliders and the value the+ // next submit will send.+ _restoreCharacterStrengths(p);// Strip the character's face/audio LoRA paths out of the loras list// so the picker doesn't show duplicate state. The backend will// re-expand on the next submit. We can't read list_characters() from@@ -47320,7 +47657,7 @@ function _renderCharsAppliedNote() {oninput="setCharStrength('voice', this.value)"><output id="charVoiceOut">${voi.toFixed(1)}</output><button type="button" class="help-dot" id="charVoiceHelpBtn" aria-expanded="false"- aria-controls="charVoiceHelpNote" title="Why run the voice hotter?"+ aria-controls="charVoiceHelpNote" title="Why the voice has its own number"onclick="toggleCharVoiceHelp()">?</button></div><div class="h3-winhelp" id="charVoiceHelpNote" hidden></div>@@ -47368,6 +47705,56 @@ function renderNowPreview(s, prog) {const actions = document.getElementById('nowCardActions');if (!box) return;const prev = prog && prog.preview;+ // A MISSING DECODER MUST SAY SO. Without this, a render on an install whose+ // 22 MB decoder never arrived looks identical to one where the user switched+ // the preview off: nothing appears, and a feature the release announced simply+ // does not happen. Only the missing-decoder case speaks — "off" was the user's+ // own choice and needs no announcement.+ const pstate = ((BOOT.ltx || {}).preview_state) || {};+ // SCOPED TO THE JOB IT IS ABOUT. renderNowPreview() runs for EVERY active job,+ // so this condition — "something is running, there is no preview, the decoder+ // is missing" — announced an LTX live-preview failure over H3 renders, image+ // jobs and training runs, complete with an Install link for a decoder those+ // jobs would never have used. The capability declares which engines it serves+ // (required_files.json → capabilities.live_preview.engines) and the running+ // job says which engine it is, so the notice only appears where it is true.+ const capEngines = (((BOOT.ltx || {}).capabilities || {}).live_preview || {}).engines || ['ltx'];+ const _p = ((s.current || {}).params) || {};+ // A POSITIVE MATCH, never a default. `engine || 'ltx'` meant every job that+ // does not carry the field — image jobs never do, it is a video field —+ // counted as LTX and got an LTX live-preview failure notice with an Install+ // link for a decoder they would never use. Missing now means "not LTX".+ const jobEngine = String(_p.engine || '').toLowerCase();+ const jobMode = String(_p.mode || '').toLowerCase();+ // And only the modes that actually run the preview lane. Image and training+ // jobs are not video renders; `preview_every` on the quality cell is the+ // server's own answer for the LTX paths (HQ tiers that never call+ // _live_preview_params say so here) — when the table is absent we do not+ // guess, we stay quiet.+ const _qs = ((BOOT.ltx || {}).qualities) || [];+ const _cell = Array.isArray(_qs)+ ? _qs.find(c => c && c.key === String(_p.quality || ''))+ : _qs[String(_p.quality || '')];+ const laneRuns = _cell ? Number(_cell.preview_every || 0) > 0 : false;+ const previewServesThisJob =+ jobEngine !== '' && capEngines.indexOf(jobEngine) !== -1+ && jobMode !== 'train' && jobMode !== 'image'+ && laneRuns;+ const missingDecoder = s.running && !prev && previewServesThisJob+ && pstate.reason === 'missing_decoder';+ let miss = document.getElementById('nowPreviewMissing');+ if (missingDecoder) {+ if (!miss) {+ miss = document.createElement('div');+ miss.id = 'nowPreviewMissing';+ miss.className = 'now-preview-missing';+ box.parentNode.insertBefore(miss, box.nextSibling);+ }+ miss.innerHTML = escapeHtml(pstate.note || '') ++ ' <a href="#" onclick="event.preventDefault();openModelsModal()">Install it</a>';+ } else if (miss) {+ miss.remove();+ }if (!s.running || !prev) {box.hidden = true;box.className = 'now-thumb';@@ -48564,7 +48951,7 @@ async function refreshModelsModal({ silent = false } = {}) {: '<svg class="ph" aria-hidden="true"><use href="#ph-x-circle"/></svg>';const statusText = ready? `Ready · engine picker unlocked · ${escapeHtml(h3.root || '')}`- : 'Not installed · install from the Pinokio sidebar';+ : 'Available to install · one click in the Pinokio sidebar';const btn = ready? `<button class="ghost" disabled>Installed</button>`: `<button onclick="openH3InstallCard()">How to install</button>`;@@ -48572,8 +48959,8 @@ async function refreshModelsModal({ silent = false } = {}) {<li class="${cls}"><span class="icon">${icon}</span><div class="meta">- <span class="ttl">Hailuo H3 (MiniMax-H3 FL2VA) · <span style="color:var(--muted)">optional</span></span>- <span class="sub">Second video engine — joint video + dialogue + sound</span>+ <span class="ttl">Hailuo H3 (MiniMax-H3 FL2VA) · <span style="color:var(--muted)">second video engine</span></span>+ <span class="sub">A peer of LTX — one prompt in, video + synced dialogue + sound out</span><span class="sub">${statusText} · ${escapeHtml(h3.size_note || '')}</span></div>${btn}@@ -49039,7 +49426,12 @@ let SB = {saveTimer: null,saveInFlight: false,saveAgain: false,- stageMode: 'auto', // 'auto' | 'list' | 'player'+ // 'auto' (the list) | 'list' | 'player'. Restored from the session so a reload does+ // not re-dock a preview the user closed two minutes ago.+ stageMode: (function () {+ try { return sessionStorage.getItem('phos.sb.stageMode') || 'auto'; }+ catch (e) { return 'auto'; }+ })(),primed: false, // brief defaults are read from BOOT once, not per entryboards: [], // /status.storyboards, refreshed by poll()lastUndo: null,@@ -49256,8 +49648,8 @@ function sbEngineChip(id) {|| { id: id, label: (id || 'ltx').toUpperCase(), mark: 'eng-mark-ltx',accent: '', accent_dim: '', accent_soft: '', tagline: '' };const why = id === 'h3'- ? 'Renders on Hailuo H3 — video, dialogue and sound together. The optional pack.'- : 'Renders on LTX — the built-in engine, and the only one that loads a trained character.';+ ? 'Renders on Hailuo H3 — video, dialogue and sound together. A 75 GB install.'+ : 'Renders on LTX — ships with the panel, and the only engine that loads a trained character.';return `<span class="sb-chip sb-chip-engine" data-engine="${escapeHtml(e.id)}"style="--eng-accent:${escapeHtml(e.accent)};--eng-dim:${escapeHtml(e.accent_dim)};--eng-soft:${escapeHtml(e.accent_soft)}"title="${escapeHtml(why)}"><span class="eng-mark"><svg class="ph" aria-hidden="true"><use href="#${escapeHtml(e.mark)}"/></svg></span>${escapeHtml(e.label)}</span>`;@@ -49650,7 +50042,17 @@ function sbSyncStage() {if (!on) full = false;else if (SB.stageMode === 'list') full = true;else if (SB.stageMode === 'player') full = false;- else full = !hasClip;+ // AUTO NO LONGER MEANS "the moment a clip exists, take half the column".+ //+ // It used to read `full = !hasClip`, so the instant the first draft landed the player+ // docked itself over the work — 414 px of a 812 px column, measured, with twelve shots+ // left sharing the remainder. Nobody asked for it: the user was reading the shot list+ // and a render finished. That is the whole of the report.+ //+ // Auto now stays on the list, and the player appears when the user ASKS for a clip+ // (sbOpenShotClip, the per-shot thumbnail). The clip is never hidden — the thumbnail on+ // each shot card is the affordance, and it was already there.+ else full = true;document.body.classList.toggle('sb-full', !!full);const tog = sbEl('sbStageToggle');if (tog) {@@ -49659,7 +50061,28 @@ function sbSyncStage() {b.classList.toggle('active', b.dataset.sbStage === (full ? 'list' : 'player')));}}-function sbSetStage(mode) { SB.stageMode = mode; sbSyncStage(); }+function sbSetStage(mode) {+ SB.stageMode = mode;+ // Session-scoped, so a reload mid-film does not re-dock a player the user closed.+ // sessionStorage, not localStorage: this is a working preference for this sitting, not+ // a setting the user should have to find and undo next week.+ try { sessionStorage.setItem('phos.sb.stageMode', mode); } catch (e) {}+ sbSyncStage();+}++// Esc collapses the docked preview, matching the lightbox's own Esc. Deliberately narrow:+// only on the storyboard tab, only when the player is actually docked, and only when the+// lightbox is closed (its Esc wins) and the user is not typing in a shot's textarea.+document.addEventListener('keydown', function (e) {+ if (e.key !== 'Escape') return;+ if (document.body.dataset.workflow !== 'storyboard') return;+ if (document.body.classList.contains('sb-full')) return;+ const lb = document.getElementById('expandLightbox');+ if (lb && getComputedStyle(lb).display !== 'none') return;+ const t = document.activeElement;+ if (t && /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)) return;+ sbSetStage('list');+});// ---- the plan screen -------------------------------------------------------function sbRenderPlan(r) {@@ -50080,8 +50503,10 @@ function sbOpenShotClip(n) {const s = (((SB.payload || {}).board) || {}).shots.find(x => x.n === n);const clip = s && (s.final_output || s.draft_output);if (!clip) return;- if (SB.stageMode === 'list') SB.stageMode = 'auto';- sbSyncStage();+ // Opening a clip IS the request for the player, so it says so outright rather than+ // dropping back to 'auto' and hoping auto agrees. Since auto now means "stay on the+ // list", the old line would have opened a clip into a hidden player.+ sbSetStage('player');selectOutput(clip);}diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex acb8385..899e75a 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -2638,6 +2638,34 @@ for line in sys.__stdin__:distilled_lora=p.get("distilled_lora"))# Y1.037: short-clip VAE-streaming opt-out (HQ T2V/I2V path)._apply_vae_streaming_decision(int(p["frames"]))+ lp_kwargs: dict = {}+ # LIVE PREVIEW ON THE HQ LANE TOO — it was only ever built in the+ # `generate` branch. High advertises preview_every=2 in the quality+ # table and published nothing, so the UI reported a MISSING DECODER+ # on a lane that had simply never been wired. Every-2 is the lane+ # rule, decided server-side: res_2s evaluates the denoiser twice per+ # stage-2 step and its odd ANCHOR estimates come back patchy, so the+ # even SUBSTEP ones are the clean series.+ # TI2VidTwoStagesHQPipeline.generate_and_save takes `live_preview`+ # directly; _filter_unsupported_kwargs below still guards a stock+ # upstream that does not.+ for _k in ("live_preview_dir", "live_preview_tae", "live_preview_every"):+ if p.get(_k) is not None:+ lp_kwargs[_k] = p[_k]+ # output_path too: LivePreviewMonitor takes it, so leaving it out+ # made _build_live_preview raise KeyError into its own "never fatal"+ # except and return None — the preview silently not happening in the+ # one place whose entire job is to stop things silently not+ # happening. The `generate` branch passes the whole kwargs dict,+ # which is why it never hit this.+ if lp_kwargs:+ lp_kwargs["output_path"] = p["output_path"]+ _hq_preview = _build_live_preview(lp_kwargs) if lp_kwargs else None+ if _hq_preview is not None:+ emit({"event": "log",+ "line": f"live preview on (HQ) — every "+ f"{lp_kwargs.get('live_preview_every', 2)} estimate(s) "+ f"→ {p.get('live_preview_dir')}"})kwargs = dict(prompt=p["prompt"],output_path=p["output_path"],@@ -2737,6 +2765,8 @@ for line in sys.__stdin__:# etc., which would crash a stock install. Introspect once, drop# any kwarg the installed signature doesn't accept — better to# silently skip a feature flag than to fail the whole render.+ if _hq_preview is not None:+ kwargs["live_preview"] = _hq_previewkwargs = _filter_unsupported_kwargs(pipe.generate_and_save, kwargs)out_path = pipe.generate_and_save(**kwargs)elapsed = round(time.time() - t0, 2)diff --git a/pinokio.js b/pinokio.jsindex 575e07e..589e717 100644--- a/pinokio.js+++ b/pinokio.js@@ -83,7 +83,11 @@ function repoComplete(installRoot, repo, minBytes) {module.exports = {version: "7.0",title: "Phosphene",- description: "[MAC ONLY] Local generative video panel for Apple Silicon. Joint audio+video via LTX 2.3 (MLX). T2V, I2V, FFLF, Extend. Lossless h264. Hardware-tier feature gating. Free, open source.",+ // The Pinokio store listing. It still said "via LTX 2.3 (MLX)" three weeks after 2.5+ // became the generation a fresh install renders with — the first sentence a prospective+ // user reads, naming the wrong engine, while a confused existing user hunting a "why+ // does it keep asking for LTX 2.3" answer finds it confirming their suspicion.+ description: "[MAC ONLY] Local generative video panel for Apple Silicon. Joint audio+video via LTX-2.5 (MLX), with Hailuo H3 as a second engine. T2V, I2V, FFLF, Extend, trained characters. Lossless h264. Hardware-tier feature gating. Free, open source.",icon: "icon.png",menu: async (kernel, info) => {// Resolve the install root. cocktailpeanut diagnosed that `info.path` is@@ -100,7 +104,39 @@ module.exports = {// --- per-repo completeness from the unified manifest ---const repos = required.repos || []- const baseRepos = repos.filter(r => r.kind === "base")+ // WHAT HIDES START IS "CAN THIS RENDER", NOT "IS EVERY base ROW COMPLETE".+ // `kind: "base"` had come to mean two different things — fetched on a fresh+ // install, AND the panel cannot render without it — and Gemma 3 is the first+ // but not the second: it is LTX-2.3's encoder and the Enhance/planner model,+ // and the active 2.5 generation renders with Gemma 4 instead. Marked base, a+ // half-downloaded planner model made Pinokio declare the base renderer+ // incomplete and hide Start on an install that renders perfectly. The+ // preview decoder had the identical bug one commit earlier; this closes the+ // class by asking the capability instead of the label.+ const caps = required.capabilities || {}+ const capRender = caps.render || {}+ // THE ACTIVE GENERATION, where it is knowable. A user pinned back with+ // LTX_MODEL_VERSION=ltx23 renders on 2.3's packs, and evaluating the+ // manifest's default here told them their install was incomplete for a+ // generation they are not using. The panel resolves this from its own+ // process env; Pinokio's menu runs elsewhere, so it reads the same override+ // from the ENVIRONMENT file the launcher sources — which is exactly where+ // docs/H3_ENGINE.md tells users to put persistent overrides. Falls back to+ // the manifest default when nothing has been pinned, which is the norm.+ let activeVersion = capRender.default_version+ try {+ const envPath = path.join(installRoot, "ENVIRONMENT")+ if (fs.existsSync(envPath)) {+ const m = fs.readFileSync(envPath, "utf8")+ .split("\n").filter(l => !/^\s*#/.test(l))+ .join("\n").match(/^\s*LTX_MODEL_VERSION\s*=\s*(\S+)\s*$/m)+ if (m && (capRender.repos_by_version || {})[m[1]]) activeVersion = m[1]+ }+ } catch (e) { /* unreadable ENVIRONMENT: keep the manifest default */ }+ const renderKeys = ((capRender.repos_by_version || {})[activeVersion] || [])+ const baseRepos = renderKeys.length+ ? renderKeys.map(k => repos.find(r => r.key === k)).filter(Boolean)+ : repos.filter(r => r.kind === "base")// THE PACK THE BUTTON ACTUALLY INSTALLS. This read `key === "q8"` —// LTX-2.3's pack — while the menu entry it gates dispatches// download_q8.js -> q8_weights.sh -> `--repo-key q8_25`, i.e. LTX-2.5's.@@ -108,7 +144,16 @@ module.exports = {// successful 30 GB install the menu kept offering the download forever.// Resolved by mirror-block presence rather than a hardcoded key so a third// generation does not reopen it: the 2.5-era packs are the mirrored ones.- const q8Repo = repos.find(r => r.key === "q8_25") || repos.find(r => r.key === "q8")+ // THE Q8 PACK OF THE ACTIVE GENERATION. This preferred q8_25 unconditionally,+ // so a user pinned back with LTX_MODEL_VERSION=ltx23 whose 2.3 Q8 pack was+ // already complete still saw "Download Q8 weights (~30 GB)" forever — an+ // offer to fetch 30 GB their generation does not load. `characters` is the+ // capability that names it, and it is declared per version.+ const capChars = caps.characters || {}+ const q8Keys = ((capChars.repos_by_version || {})[activeVersion]+ || (capChars.repos_by_version || {})[capChars.default_version] || [])+ const q8Repo = q8Keys.map(k => repos.find(r => r.key === k)).filter(Boolean)[0]+ || repos.find(r => r.key === "q8_25") || repos.find(r => r.key === "q8")const base_ready = baseRepos.length > 0 && baseRepos.every(r => repoComplete(installRoot, r, minBytes))const q8_ready = q8Repo ? repoComplete(installRoot, q8Repo, minBytes) : false@@ -123,10 +168,20 @@ module.exports = {// `mflux-generate-qwen-edit` binary didn't land (mflux <0.17.5).const qwen_ready =info.exists("ltx-2-mlx/env/bin/mflux-generate-qwen-edit")- // Hailuo H3 readiness — the engine's own venv AND the pruned bf16 DiT (the- // one 41 GB file; if that landed, the small siblings did too). Weights live- // under mlx_models/ so they survive Reset like every other model. Both- // download layouts are accepted, matching _h3_model_roots() in the panel.+ // Hailuo H3 readiness — the engine's own venv, its runner, and EVERY weight+ // component the panel requires.+ //+ // The old note here said "the one 41 GB file; if that landed, the small+ // siblings did too". That assumption is what Medium 6 was: a partial install+ // where the DiT arrived and a compact Q8 component did not looked ready from+ // this side and refused to run from the panel's, and because the menu thought+ // it was fine it hid the Install/Repair entry that would have fixed it. The+ // components are declared once in required_files.json and checked here, so+ // the assumption is gone rather than reworded.+ //+ // Weights live under mlx_models/ so they survive Reset like every other+ // model, and both download layouts are accepted (capabilities.h3.model_roots+ // mirrors _h3_model_roots() in the panel).//// Probed with Node's own fs, NOT info.exists() — deliberately, and this is// the whole fix. `uv venv` builds the venv interpreter as a symlink chain@@ -151,16 +206,29 @@ module.exports = {const h3Resolves = (rel) => {try { return fs.existsSync(path.join(installRoot, rel)) } catch (e) { return false }}- const h3_venv =- h3Resolves("minimax-h3-mlx/.venv/bin/python3.11") ||- h3Resolves("minimax-h3-mlx/.venv/bin/python")- const h3_runner = h3Resolves("minimax-h3-mlx/scripts/generate_staged.py")+ // DECLARED, NOT RE-DERIVED. This used to call H3 ready on venv + runner ++ // the one big DiT, while the panel additionally required every compact Q8+ // component and the upstream text config — so a partial install hid the+ // Install/Repair entry here while the panel refused to run H3, and the user+ // had no route to the fix. Both sides now read the same component list from+ // required_files.json → capabilities.h3.+ const capH3 = ((required.capabilities || {}).h3) || {}+ const h3_venv = (capH3.venv_any || []).some(h3Resolves)+ const h3_runner = (capH3.paths || []).every(h3Resolves)// The weights are the expensive thing (~75 GB) and they live under// mlx_models/, a completely different tree from the clone — so they- // routinely survive whatever broke the engine.- const h3_weights =- h3Resolves("mlx_models/hailuo-h3/models/deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors") ||- h3Resolves("mlx_models/hailuo-h3/deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors")+ // routinely survive whatever broke the engine. `model_roots` are+ // ALTERNATIVES (either download layout is valid); every entry in `models`+ // is required beneath whichever root carried the DiT.+ // PER FILE, not per root. This required every component beneath ONE root,+ // while the panel resolves each file against any of them — and the panel is+ // right: LTX_H3_MODELS and LTX_H3_COMPACT_DIR legitimately split a layout+ // across roots, which is the documented dev setup. On a split layout the+ // panel said installed and this said not, so Pinokio offered a 75 GB+ // install for weights already on disk. Two consumers, one manifest, and now+ // one resolution rule.+ const h3_weights = (capH3.models || []).every(rel =>+ (capH3.model_roots || []).some(root => h3Resolves(root + "/" + rel)))const h3_ready = h3_venv && h3_runner && h3_weights// Weights on disk but the code/venv gone → a REPAIR, not a 75 GB install.// install_h3.js is idempotent and skips every intact weight, so the same@@ -324,7 +392,11 @@ module.exports = {// ~30 GB and what it actually buys on 2.5: trained characters and voices.// High additionally needs the separate 29.5 GB add-on, which is offered// in Settings -> Models rather than here — one menu entry, one download.- baseMenu.push({ icon: "fa-solid fa-download", text: "Download Q8 weights (~30 GB) — trained characters + voices", href: "download_q8.js" })+ // Size and wording follow the pack that will actually be fetched.+ const q8Size = q8Repo && q8Repo.size_gb ? `~${Math.round(q8Repo.size_gb)} GB` : "~30 GB"+ baseMenu.push({ icon: "fa-solid fa-download",+ text: `Download Q8 weights (${q8Size}) — trained characters + voices`,+ href: "download_q8.js" })}if (!sharp_ready) {baseMenu.push({ icon: "fa-solid fa-wand-magic-sparkles", text: "Install Sharp upscaler (PiperSR, optional)", href: "install_sharp.js" })@@ -344,7 +416,10 @@ module.exports = {// never reads as a missing piece of the base install.baseMenu.push(h3_repair? { icon: "fa-solid fa-screwdriver-wrench", text: "Repair Hailuo H3 (weights kept — no re-download)", href: "install_h3.js" }- : { icon: "fa-solid fa-comments", text: "Install Hailuo H3 (optional, ~75 GB)", href: "install_h3.js" })+ // ENGINES ARE PEERS: "optional" told a user that half the panel's+ // video capability was a side dish. The entry names what it IS.+ // The panel's install card quotes this string verbatim -- change both.+ : { icon: "fa-solid fa-comments", text: "Install Hailuo H3 (second video engine, ~75 GB)", href: "install_h3.js" })}baseMenu.push({ icon: "fa-solid fa-rotate", text: "Update", href: "update.js" },diff --git a/required_files.json b/required_files.jsonindex eff49f8..060672f 100644--- a/required_files.json+++ b/required_files.json@@ -1,6 +1,97 @@{"_comment": "Single source of truth for what counts as a complete install. Read by pinokio.js (sidebar menu), mlx_ltx_panel.py (/status, /models, run-time job validation), and consumed indirectly by install.js + download_q8.js (whose `hf download` calls land files at the local_dir paths listed below). When the upstream model layout changes, edit ONE file.",- "_download_include_comment": "Y1.024 \u2014 `download_include` is the list of patterns passed as `--include` flags to `hf download`. Without it `hf download` grabs every file in the repo, which on dgrauet's LTX repos means duplicate transformer variants (transformer-distilled.safetensors AND transformer-distilled-1.1.safetensors AND transformer-dev.safetensors), duplicate distilled LoRAs (-384 and -384-1.1), the temporal upscaler we don't wire, and the x1.5 spatial upscaler we don't use \u2014 turning a declared 25 GB Q8 download into 82 GB on disk (and a 25 GB Q4 into 56 GB). With `download_include` we pull only what the panel actually loads. Pattern syntax: huggingface_hub fnmatch globs \u2014 bare filenames and wildcards both work. We pass `*.json` to keep all sidecar configs (split_model.json etc.) which are tiny and required at runtime.",+ "_download_include_comment": "Y1.024 — `download_include` is the list of patterns passed as `--include` flags to `hf download`. Without it `hf download` grabs every file in the repo, which on dgrauet's LTX repos means duplicate transformer variants (transformer-distilled.safetensors AND transformer-distilled-1.1.safetensors AND transformer-dev.safetensors), duplicate distilled LoRAs (-384 and -384-1.1), the temporal upscaler we don't wire, and the x1.5 spatial upscaler we don't use — turning a declared 25 GB Q8 download into 82 GB on disk (and a 25 GB Q4 into 56 GB). With `download_include` we pull only what the panel actually loads. Pattern syntax: huggingface_hub fnmatch globs — bare filenames and wildcards both work. We pass `*.json` to keep all sidecar configs (split_model.json etc.) which are tiny and required at runtime.",+ "capabilities": {+ "_comment": "CAPABILITY-LEVEL REQUIREMENTS. Before this block, readiness was `kind: \"base\"` plus a handful of hand-written booleans, and 'base' had come to mean two different things: 'this pack is fetched on a fresh install' AND 'the panel cannot render without it'. Those are not the same question, and conflating them is what let a partially-downloaded Gemma 3 -- the LTX-2.3 encoder and the Enhance/planner model, which the active 2.5 generation does not render with -- tell Pinokio the base renderer was incomplete and hide Start. The preview decoder had the identical bug one commit earlier. Each capability names what it actually needs; both consumers (mlx_ltx_panel.py and pinokio.js) read THIS, so they cannot drift apart. `blocking` is the only thing that may hide Start.",+ "render": {+ "label": "Render video",+ "blocking": true,+ "_comment": "Per generation, because which packs render is exactly what a generation IS. The active version is resolved at runtime by the panel; pinokio.js uses `default_version` since a fresh install boots into it.",+ "default_version": "ltx25",+ "repos_by_version": {+ "ltx25": [+ "q4_25",+ "gemma4_25"+ ],+ "ltx23": [+ "q4",+ "gemma"+ ]+ }+ },+ "enhance": {+ "label": "Prompt Enhance and the Storyboard planner",+ "blocking": false,+ "_comment": "Gemma 3 runs these WHICHEVER generation renders, which is why it is still fetched on a fresh install -- but a missing or half-downloaded planner model costs you Enhance and the planner, not the renderer.",+ "repos": [+ "gemma"+ ]+ },+ "characters": {+ "label": "Trained characters and voices",+ "blocking": false,+ "_comment": "Per generation, for the same reason render is: on 2.3 a trained character renders on ITS q8 pack, not 2.5's. Hardcoding q8_25 told a user pinned back with LTX_MODEL_VERSION=ltx23 to download a pack their generation does not use.",+ "default_version": "ltx25",+ "repos_by_version": {+ "ltx25": [+ "q8_25"+ ],+ "ltx23": [+ "q8"+ ]+ }+ },+ "high_tier": {+ "label": "High tier, FFLF and Extend",+ "blocking": false,+ "_comment": "2.3 ships its dev transformer and distilled LoRA INSIDE its own q8 repo and has no add-on at all, so the 2.5 add-on must not be demanded there.",+ "default_version": "ltx25",+ "repos_by_version": {+ "ltx25": [+ "q8_25",+ "hq_25"+ ],+ "ltx23": [+ "q8"+ ]+ }+ },+ "live_preview": {+ "label": "Live preview",+ "blocking": false,+ "_comment": "`engines` scopes the UI notice: the decoder decodes LTX latents, so an H3 or image job missing it is not a fact about that job and must not be announced on it.",+ "engines": [+ "ltx"+ ],+ "repos": [+ "tae"+ ]+ },+ "h3": {+ "label": "Hailuo H3 (second video engine)",+ "blocking": false,+ "_comment": "THE COMPONENT LIST BOTH CONSUMERS CHECK. pinokio.js used to call H3 ready on venv + runner + the one big DiT, while the panel additionally required every compact Q8 component and the upstream text config -- so a partial install hid the Install/Repair entry in Pinokio while the panel refused to run H3. `model_roots` are alternatives (either layout is valid, no post-download move is ever needed); everything under `models` is required beneath whichever root carried the DiT.",+ "paths": [+ "minimax-h3-mlx/scripts/generate_staged.py"+ ],+ "venv_any": [+ "minimax-h3-mlx/.venv/bin/python3.11",+ "minimax-h3-mlx/.venv/bin/python"+ ],+ "model_roots": [+ "mlx_models/hailuo-h3/models",+ "mlx_models/hailuo-h3"+ ],+ "models": [+ "deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors",+ "ddalcu-q8/text_encoder.safetensors",+ "ddalcu-q8/video_vae.safetensors",+ "ddalcu-q8/audio_vae.safetensors",+ "upstream-meta/FL2VA/text_encoder/config.json"+ ],+ "_venv_comment": "INTERPRETERS ONLY. `bin/activate` was listed here and Pinokio accepted it, so a broken venv read as ready on one side and not the other. uv creates bin/python as a symlink chain into a shared managed interpreter, and installing another pack can move it -- leaving activate in place beside a dangling python. That is the v3.4.0 'installed other packs and Hailuo H3 vanished' report. Both consumers resolve the symlink (fs.existsSync / Path.exists both follow), so a dangling chain is false."+ }+ },"repos": [{"_v40_comment": "kind flipped base -> optional in v4.0. `base` means an install WITHOUT it reads INCOMPLETE, so a fresh 2.5-only install showed the red 'Base models needed before you can render' block and Pinokio offered Resume Install — for a pack nothing renders with. From v4.0 a fresh install fetches 2.5 only and this is a normal in-panel offer, downloaded when the user wants to TRAIN a character. Existing installs that already hold it see no behaviour change: the files are there, the row reads Ready, and Storage still offers to reclaim it.",@@ -49,7 +140,7 @@{"key": "q8","kind": "optional",- "name": "LTX 2.3 \u2014 Q8 (high-quality + FFLF)",+ "name": "LTX 2.3 — Q8 (high-quality + FFLF)","blurb": "The previous generation's high-quality weights. On LTX-2.5 the High tier uses the 2.5 Q8 pack plus the High add-on instead.","repo_id": "dgrauet/ltx-2.3-mlx-q8","local_dir": "mlx_models/ltx-2.3-mlx-q8",@@ -80,7 +171,7 @@"key": "ic_colorize","kind": "optional","name": "Colorize IC-LoRA (community)",- "blurb": "Optional. Powers the Colorize restore mode \u2014 adds natural color to a B&W source clip. Un-gated community weights (no HF token).",+ "blurb": "Optional. Powers the Colorize restore mode — adds natural color to a B&W source clip. Un-gated community weights (no HF token).","repo_id": "DoctorDiffusion/LTX-2.3-IC-LoRA-Colorizer","local_dir": "mlx_models/loras/ic","size_gb": 1,@@ -95,11 +186,11 @@]},{- "_comment": "Ingredients (flagship multi-reference) IC-LoRA. BYTE-IDENTICAL to the gated official Lightricks/LTX-2.3-22b-IC-LoRA-Ingredients (same 1308778338-byte size, sha256 515e4e139001ac6282357a5b35372e42e98b3affd5fcc886a52242abeed19559), mirrored un-gated. WARNING: DeepBeepMeep/LTX-2 is a ~708 GB mega-repo (71 safetensors) \u2014 the download_include here pulls ONLY the one ingredients file (1.3 GB), and the worker fallback uses hf_hub_download for the exact filename, NEVER a bare snapshot_download of the whole repo.",+ "_comment": "Ingredients (flagship multi-reference) IC-LoRA. BYTE-IDENTICAL to the gated official Lightricks/LTX-2.3-22b-IC-LoRA-Ingredients (same 1308778338-byte size, sha256 515e4e139001ac6282357a5b35372e42e98b3affd5fcc886a52242abeed19559), mirrored un-gated. WARNING: DeepBeepMeep/LTX-2 is a ~708 GB mega-repo (71 safetensors) — the download_include here pulls ONLY the one ingredients file (1.3 GB), and the worker fallback uses hf_hub_download for the exact filename, NEVER a bare snapshot_download of the whole repo.","key": "ic_ingredients","kind": "optional","name": "Ingredients IC-LoRA",- "blurb": "Optional. Powers the Ingredients mode \u2014 composes 2-8 reference images (face + prop + location) into one new video. Un-gated mirror of the official weight (no HF token).",+ "blurb": "Optional. Powers the Ingredients mode — composes 2-8 reference images (face + prop + location) into one new video. Un-gated mirror of the official weight (no HF token).","repo_id": "DeepBeepMeep/LTX-2","local_dir": "mlx_models/loras/ic","size_gb": 2,@@ -114,11 +205,11 @@]},{- "_comment": "Control (Union) IC-LoRA \u2014 drives a render's motion/structure/composition from a control video. This is the OFFICIAL Lightricks weight and it is UN-GATED + public (gated:false, single 654465352-byte safetensors), so it downloads token-less exactly like the community Colorizer \u2014 NO mrbizarro mirror, NO HF token, NO mega-repo workaround. reference_downscale_factor=2 (the IC encoder halves the control clip; handled in iclora_utils).",+ "_comment": "Control (Union) IC-LoRA — drives a render's motion/structure/composition from a control video. This is the OFFICIAL Lightricks weight and it is UN-GATED + public (gated:false, single 654465352-byte safetensors), so it downloads token-less exactly like the community Colorizer — NO mrbizarro mirror, NO HF token, NO mega-repo workaround. reference_downscale_factor=2 (the IC encoder halves the control clip; handled in iclora_utils).","key": "ic_union_control","kind": "optional","name": "Control IC-LoRA (Union, official)",- "blurb": "Optional. Powers the Control mode \u2014 drives motion/structure/composition from a control video. Official un-gated Lightricks weight (no HF token).",+ "blurb": "Optional. Powers the Control mode — drives motion/structure/composition from a control video. Official un-gated Lightricks weight (no HF token).","repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control","local_dir": "mlx_models/loras/ic","size_gb": 1,@@ -133,8 +224,8 @@]},{- "_comment": "LTX-2.5 Q4. Built by us (scripts/convert_ltx_mlx.py -> scripts/quantize_ltx.py) from the official Lightricks bf16 release, not by dgrauet. Mirrored through a GitHub release rather than HuggingFace, so deep-verify reads sha256 from the in-pack phosphene_quant_manifest.json (verify_source 'manifest') instead of the HF checksum API \u2014 which is why that manifest is listed as a required file. temporal_upscaler and duration_head ship because 2.5 has them and they are tiny; the x1.5 spatial upscaler does not exist for 2.5.",- "_mirror_comment": "PUBLISHED 2026-08-12. `repo_id` names a HuggingFace repo that DOES NOT EXIST and never will \u2014 our HF token is read-only and this pack is our own quantisation of a gated upstream. It is kept only as the pack's stable identity string (the panel shows it, and `_expected_meta` never calls the HF API for a verify_source 'manifest' pack). The bytes come from the `mirror` block: GitHub release assets, sharded at 1.9 GB because the cap is 2 GiB, fetched + reassembled + sha256-verified by scripts/fetch_pack_release.py. `download_include` is inert on this lane (the release manifest is the allowlist) and is kept only so the entry stays shaped like every other.",+ "_comment": "LTX-2.5 Q4. Built by us (scripts/convert_ltx_mlx.py -> scripts/quantize_ltx.py) from the official Lightricks bf16 release, not by dgrauet. Mirrored through a GitHub release rather than HuggingFace, so deep-verify reads sha256 from the in-pack phosphene_quant_manifest.json (verify_source 'manifest') instead of the HF checksum API — which is why that manifest is listed as a required file. temporal_upscaler and duration_head ship because 2.5 has them and they are tiny; the x1.5 spatial upscaler does not exist for 2.5.",+ "_mirror_comment": "PUBLISHED 2026-08-12. `repo_id` names a HuggingFace repo that DOES NOT EXIST and never will — our HF token is read-only and this pack is our own quantisation of a gated upstream. It is kept only as the pack's stable identity string (the panel shows it, and `_expected_meta` never calls the HF API for a verify_source 'manifest' pack). The bytes come from the `mirror` block: GitHub release assets, sharded at 1.9 GB because the cap is 2 GiB, fetched + reassembled + sha256-verified by scripts/fetch_pack_release.py. `download_include` is inert on this lane (the release manifest is the allowlist) and is kept only so the entry stays shaped like every other.","key": "q4_25","kind": "base","name": "LTX-2.5 base",@@ -269,8 +360,9 @@{"_comment": "The tiny decoder behind LIVE PREVIEW. 22.4 MiB, MIT, ungated, from github.com/madebyollin/taehv (taeltx2_3.safetensors, 23,531,296 B, sha256 f0773b4e…be246 — verified byte count and hash before publishing). It turns the x0 estimate the denoise loop ALREADY HOLDS into a thumbnail, so nothing is recomputed and a render with the preview on is byte-identical to the same render with it off.","_mirror_comment": "Mirrored onto the SAME release as the 2.5 packs rather than fetched from raw.githubusercontent at render time, so it rides the ordinary lane: files[] + download_include[], one manifest format, sha256-verified and resumable by scripts/fetch_pack_release.py, and no new fetch-lane code. `repo_id` names the upstream for attribution; the bytes come from the mirror block.",+ "_kind_comment": "NOT `base`, and marking it base cost a user their panel. `kind: base` is the gate for CAN THIS MACHINE RENDER AT ALL: pinokio.js hides Start behind it and the panel raises the red 'Base models needed before you can render' block over everything. A missing 22 MB PREVIEW decoder is none of those things - the renderer never loads it, live_preview_enabled() returns False and every render proceeds normally. Marked base, its absence reported a working install as unable to render, permanently, as '(1 files left)', with no way to clear it but a download the user had no idea they needed. Both fetch lanes name it explicitly (--repo-key tae in scripts/pinokio/ltx25_weights.sh and scripts/post_update.sh), so `optional` costs nothing on install or update; it only stops the panel lying about what is broken.","key": "tae",- "kind": "base",+ "kind": "optional","name": "Live-preview decoder","blurb": "22 MB. Draws the shot as it forms, so a wrong take can be stopped in seconds instead of minutes.","repo_id": "madebyollin/taehv",@@ -293,7 +385,7 @@}],"env": {- "_comment": "Marker that the venv exists. SHIP-BLOCKER history: we used to point at `bin/python3.11` but uv creates that as a symlink chain (python3.11 -> python -> ~/pinokio/cache/.../uv/python/.../python3.11). Pinokio's info.exists() check returned false on that chain, so the menu rendered Install instead of Start even after a complete install \u2014 confirmed by cocktailpeanut. Use `pyvenv.cfg` instead: it's a tiny ASCII file uv writes to every venv root, never a symlink, never moves. `bin/activate` is the same kind of plain file; we keep it as a secondary check. The bin/python3.11 entries stay last as a final fallback for older installs.",+ "_comment": "Marker that the venv exists. SHIP-BLOCKER history: we used to point at `bin/python3.11` but uv creates that as a symlink chain (python3.11 -> python -> ~/pinokio/cache/.../uv/python/.../python3.11). Pinokio's info.exists() check returned false on that chain, so the menu rendered Install instead of Start even after a complete install — confirmed by cocktailpeanut. Use `pyvenv.cfg` instead: it's a tiny ASCII file uv writes to every venv root, never a symlink, never moves. `bin/activate` is the same kind of plain file; we keep it as a secondary check. The bin/python3.11 entries stay last as a final fallback for older installs.","marker_paths": ["ltx-2-mlx/env/pyvenv.cfg","ltx-2-mlx/.venv/pyvenv.cfg",diff --git a/scripts/check_ltx_pin.js b/scripts/check_ltx_pin.jsindex be54ee5..6d643d0 100644--- a/scripts/check_ltx_pin.js+++ b/scripts/check_ltx_pin.js@@ -128,10 +128,141 @@ for (const [re, what] of banned) {}if (thin) ok("update.js is thin — no installs, patches, downloads or trims")-if (!/git pull --ff-only \|\|/.test(updateSrc)) {- fail("update.js's ff-only pull is not the bare form. `git pull --ff-only $UPSTREAM` passes \"origin/main\" as the REPOSITORY argument and has never once succeeded — every update silently took the reset --hard fallback.")+// ---- the update is transactional -------------------------------------------+// This used to assert one string: that the ff-only pull was the BARE form,+// because `git pull --ff-only $UPSTREAM` passes "origin/main" as the REPOSITORY+// argument and had never once succeeded — measured against the real update+// path, not reasoned about.+// v4.0.1 replaced the pull with an explicit fetch + merge so the fetch result+// can be checked, which made that assertion obsolete while the property it was+// protecting got MORE important. So the gate now checks the property.+const updCode = updateSrc.split("\n").filter((l) => !/^\s*\/\//.test(l)).join("\n")++// 1. The original bug must never come back in either form.+if (/git pull --ff-only \s*\$/.test(updCode)) {+ fail("update.js passes $UPSTREAM to `git pull --ff-only`, which git reads as a REPOSITORY argument. That form has never once succeeded — every update silently took the reset --hard fallback.")+} else {+ ok("no `git pull --ff-only $UPSTREAM` — the form that never worked")+}++// 2. A failed fetch must stop the update. The whole class of "Update reported+// success while staying on stale code" hangs off this one guard: $UPSTREAM is+// the LOCAL tracking ref, so resetting to it after a failed fetch is a no-op+// that exits 0 and lets post_update run against the old tree.+if (!/git fetch[^\n]*\|\|[^\n]*exit 1/.test(updCode)) {+ fail("update.js does not make a failed `git fetch` fatal. Without it a network or auth failure becomes: failed fetch -> failed pull -> 'successful' reset onto the stale tracking ref -> post_update against old code -> Update reports success.")} else {- ok("the ff-only pull uses the bare form")+ ok("a failed fetch aborts the update")+}++// 3+4. THE DESTRUCTIVE PATH IS ASSERTED BY BEHAVIOUR, NOT BY STRINGS.+//+// The previous two checks tested that `git diff --quiet` and `rev-list --count`+// APPEARED SOMEWHERE in the file. Both were present and the updater still+// deleted an untracked file: a clone with genuine divergence AND an untracked+// path that upstream now tracks passed every string test and reached+// `reset --hard`. A gate that greps for the fix cannot see the case the fix+// misses — so this one builds a real repository, drives the REAL dispatches out+// of update.js, and shims `git reset` so any call is recorded rather than run.+//+// Three scenarios, one rule: reset is allowed ONLY when history truly diverged+// AND nothing untracked is in the way.+const { execFileSync, spawnSync } = require("child_process")+const os = require("os")++function updateDispatches() {+ const mod = require(path.join(root, "update.js"))+ return (mod.run || [])+ .filter((st) => st.method === "shell.run" && st.params && st.params.message)+ .map((st) => st.params.message)+ .filter((m) => !/post_update/.test(m))+}++function probe(scenario) {+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "phos-upd-"))+ const G = { cwd: null, env: Object.assign({}, process.env, {+ GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" }) }+ const git = (cwd, args) => execFileSync("git", args, { cwd, env: G.env, stdio: "pipe" })+ const up = path.join(work, "up"), clone = path.join(work, "clone")+ fs.mkdirSync(up)+ git(up, ["init", "-q", "."])+ git(up, ["config", "user.email", "a@b"]); git(up, ["config", "user.name", "t"])+ fs.writeFileSync(path.join(up, "f.txt"), "v1\n")+ git(up, ["add", "f.txt"]); git(up, ["commit", "-qm", "v1"])+ git(work, ["clone", "-q", up, clone])+ git(clone, ["config", "user.email", "a@b"]); git(clone, ["config", "user.name", "t"])++ if (scenario === "mixed" || scenario === "obstruction_only") {+ fs.writeFileSync(path.join(up, "notes.txt"), "upstream\n")+ git(up, ["add", "notes.txt"]); git(up, ["commit", "-qm", "add notes"])+ fs.writeFileSync(path.join(clone, "notes.txt"), "MINE\n")+ if (scenario === "mixed") git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])+ } else if (scenario === "divergence_only") {+ fs.writeFileSync(path.join(up, "f.txt"), "v2\n")+ git(up, ["commit", "-qam", "v2"])+ git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])+ } else if (scenario === "clean_ff") {+ fs.writeFileSync(path.join(up, "f.txt"), "v2\n")+ git(up, ["commit", "-qam", "v2"])+ }+ git(clone, ["fetch", "-q", "origin"])++ const bin = path.join(work, "bin")+ fs.mkdirSync(bin)+ fs.writeFileSync(path.join(bin, "git"),+ '#!/usr/bin/env bash\nif [ "${1:-}" = "reset" ]; then echo "RESET_CALLED $*"; exit 0; fi\nexec ' ++ execFileSync("which", ["git"]).toString().trim() + ' "$@"\n')+ fs.chmodSync(path.join(bin, "git"), 0o755)++ const script = updateDispatches()+ .map((m, i) => `(\n${m}\n)\nrc=$?; [ $rc -eq 0 ] || exit $rc\n`).join("")+ const r = spawnSync("bash", ["-c", script], {+ cwd: clone, encoding: "utf8",+ env: Object.assign({}, G.env, { PATH: bin + ":" + process.env.PATH }),+ })+ const outText = (r.stdout || "") + (r.stderr || "")+ const notes = fs.existsSync(path.join(clone, "notes.txt"))+ ? fs.readFileSync(path.join(clone, "notes.txt"), "utf8").trim() : null+ fs.rmSync(work, { recursive: true, force: true })+ return { reset: /RESET_CALLED/.test(outText), code: r.status, notes, out: outText }+}++let probesRan = false+try {+ execFileSync("git", ["--version"], { stdio: "ignore" })+ probesRan = true+} catch (e) {+ ok("SKIPPED the updater behaviour probes — git is not available here")+}++if (probesRan) {+ const mixed = probe("mixed")+ if (mixed.reset || mixed.notes !== "MINE") {+ fail(`update.js RESET on a diverged clone whose untracked file is tracked upstream — the file is destroyed. Divergence and obstruction are independent; the destructive step must clear BOTH. (reset=${mixed.reset}, notes=${JSON.stringify(mixed.notes)})`)+ } else {+ ok("mixed divergence + untracked obstruction: no reset, file intact")+ }++ const obs = probe("obstruction_only")+ if (obs.reset || obs.notes !== "MINE") {+ fail(`update.js RESET over an untracked obstruction with no divergence at all (reset=${obs.reset}, notes=${JSON.stringify(obs.notes)})`)+ } else {+ ok("untracked obstruction alone: no reset, file intact")+ }++ const div = probe("divergence_only")+ if (!div.reset) {+ fail("update.js refused to reset a genuinely diverged, clean clone — the updater must still be able to converge.")+ } else {+ ok("genuine divergence with a clean tree: reset is reached")+ }++ const ff = probe("clean_ff")+ if (ff.reset || ff.code !== 0) {+ fail(`a plain fast-forward must not reset and must succeed (reset=${ff.reset}, exit=${ff.code})`)+ } else {+ ok("plain fast-forward: converges without reset")+ }}console.log("")diff --git a/scripts/extract_panel_js.py b/scripts/extract_panel_js.pynew file mode 100644index 0000000..fd28d27--- /dev/null+++ b/scripts/extract_panel_js.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+"""Pull named JS functions (and the HTML) out of mlx_ltx_panel.py so tests can RUN them.++The panel is one Python file that contains its own HTML, CSS and client JS as a+string. That is the whole reason the Character contract could drift three ways at+once without a gate noticing: the client half was untestable, so the first+version of the round-trip gate "tested" it by grepping the source for the calls it+hoped were there. It passed while the live loader was still broken.++A test that passes by finding strings is worse than no test, because it also+reports that the area is covered. This module is the fix: it extracts the real+function bodies and the real markup, and the test executes them in node against a+DOM shim. If the function stops doing the thing, the test fails — which is the+only property that makes a gate worth having.++Extraction is deliberately dumb and strict: brace-matching from a known+`function <name>(` header, and it RAISES if a requested function is missing or+unbalanced. A rename must break the test loudly rather than silently reduce+coverage back to grepping.+"""+from __future__ import annotations++import re+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+PANEL = ROOT / "mlx_ltx_panel.py"+++class ExtractError(RuntimeError):+ pass+++def panel_source() -> str:+ return PANEL.read_text(encoding="utf-8")+++def extract_function(name: str, src: str | None = None) -> str:+ """The full text of `function <name>(...) { ... }`, braces balanced."""+ s = src if src is not None else panel_source()+ m = re.search(r"^(?:async\s+)?function\s+%s\s*\(" % re.escape(name), s, re.M)+ if not m:+ raise ExtractError("function %s() not found in mlx_ltx_panel.py" % name)+ start = m.start()+ i = s.index("{", m.end() - 1)+ depth, j, in_s, esc, in_c, in_lc = 0, i, "", False, False, False+ while j < len(s):+ ch = s[j]+ nxt = s[j + 1] if j + 1 < len(s) else ""+ if in_lc:+ if ch == "\n":+ in_lc = False+ elif in_c:+ if ch == "*" and nxt == "/":+ in_c = False+ j += 1+ elif in_s:+ if esc:+ esc = False+ elif ch == "\\":+ esc = True+ elif ch == in_s:+ in_s = ""+ elif ch in "\"'`":+ in_s = ch+ elif ch == "/" and nxt == "/":+ in_lc = True+ j += 1+ elif ch == "/" and nxt == "*":+ in_c = True+ j += 1+ elif ch == "{":+ depth += 1+ elif ch == "}":+ depth -= 1+ if depth == 0:+ return s[start:j + 1]+ j += 1+ raise ExtractError("unbalanced braces while extracting %s()" % name)+++def extract_object(name: str, src: str | None = None) -> str:+ """`window.CHARACTERS = { ... };` — the state object, verbatim."""+ s = src if src is not None else panel_source()+ m = re.search(r"^window\.%s\s*=\s*" % re.escape(name), s, re.M)+ if not m:+ raise ExtractError("window.%s not found" % name)+ i = s.index("{", m.end() - 1)+ depth, j, in_s, esc, in_c, in_lc = 0, i, "", False, False, False+ while j < len(s):+ ch = s[j]+ nxt = s[j + 1] if j + 1 < len(s) else ""+ if in_lc:+ if ch == "\n":+ in_lc = False+ elif in_c:+ if ch == "*" and nxt == "/":+ in_c = False+ j += 1+ elif in_s:+ if esc:+ esc = False+ elif ch == "\\":+ esc = True+ elif ch == in_s:+ in_s = ""+ elif ch in "\"'`":+ in_s = ch+ elif ch == "/" and nxt == "/":+ in_lc = True+ j += 1+ elif ch == "/" and nxt == "*":+ in_c = True+ j += 1+ elif ch == "{":+ depth += 1+ elif ch == "}":+ depth -= 1+ if depth == 0:+ return s[i:j + 1]+ j += 1+ raise ExtractError("unbalanced braces while extracting window.%s" % name)+++def extract_element(element_id: str, src: str | None = None) -> str:+ """The raw markup of the tag carrying id="<element_id>". Used to read what a+ control actually DISPLAYS, which is the half a grep-based test cannot see."""+ s = src if src is not None else panel_source()+ m = re.search(r"<[a-zA-Z][^>]*\bid=\"%s\"[^>]*>" % re.escape(element_id), s)+ if not m:+ raise ExtractError('no element with id="%s"' % element_id)+ return m.group(0)+++def attr(markup: str, name: str) -> str | None:+ m = re.search(r'\b%s="([^"]*)"' % re.escape(name), markup)+ return m.group(1) if m else None+++if __name__ == "__main__":+ import sys+ for fn in sys.argv[1:]:+ print(extract_function(fn))diff --git a/scripts/pinokio/q8_weights.sh b/scripts/pinokio/q8_weights.shindex aa0f554..fccd291 100644--- a/scripts/pinokio/q8_weights.sh+++ b/scripts/pinokio/q8_weights.sh@@ -25,16 +25,28 @@# a complete 30 GB pack hostage to a 60 GB wait. Q8 alone is what characters and# voices need; High is one more click in Settings → Models.#-# A USER PINNED BACK TO 2.3 (LTX_MODEL_VERSION=ltx23) should use Settings →-# Models, which offers every registered pack of every generation. This button is-# the one-click path for the generation the panel actually boots into.+# A USER PINNED BACK TO 2.3 FOLLOWS THEIR PIN. This used to fetch q8_25+# unconditionally while the sidebar entry that dispatches it was gated on the+# same hardcoded key — so a 2.3-pinned install with its own Q8 pack complete was+# still offered "Download Q8 weights (~30 GB)", and clicking it fetched 30 GB of+# a generation that install does not load. The version is resolved from the same+# ENVIRONMENT file the launcher sources and pinokio.js reads, so the button, its+# gate and this fetch all name one pack.+VERSION=$(sed -n 's/^[[:space:]]*LTX_MODEL_VERSION[[:space:]]*=[[:space:]]*\([^[:space:]#]*\).*/\1/p' \+ ENVIRONMENT 2>/dev/null | tail -1)+VERSION="${LTX_MODEL_VERSION:-$VERSION}"+case "$VERSION" in+ ltx23) REPO_KEY=q8; LABEL='LTX-2.3 Q8 weights' ;;+ *) REPO_KEY=q8_25; LABEL='LTX-2.5 Q8 weights' ;;+esac+echo "Fetching $LABEL (pack key: $REPO_KEY)…"PY=./ltx-2-mlx/env/bin/python3.11-if $PY scripts/fetch_pack_release.py --repo-key q8_25; then- echo 'LTX-2.5 Q8 weights ready (verified against the published manifest).'+if $PY scripts/fetch_pack_release.py --repo-key "$REPO_KEY"; then+ echo "$LABEL ready (verified against the published manifest)."elseecho '=================================================================='- echo 'PHOSPHENE COULD NOT DOWNLOAD THE LTX-2.5 Q8 WEIGHTS'+ echo "PHOSPHENE COULD NOT DOWNLOAD THE $LABEL"echo 'Nothing is broken - this pack is optional. The panel keeps rendering'echo 'on the base weights; trained characters and voices are what need Q8.'echo 'This is almost always a network problem (no connection, a VPN or'diff --git a/scripts/post_update.sh b/scripts/post_update.shindex c712be1..62fd43a 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -8,8 +8,8 @@# Pinokio loads `update.js` from disk into memory and THEN runs it. Our step 1# is what pulls the repo, so the repo moves to the new version MID-RUN and# execution continues from the STALE in-memory script. cocktailpeanut hit this-# on his own machine and confirmed the sequencing with timestamps-# by timestamp: the fix an app ships to its own+# on his own machine and confirmed the sequencing by timestamp: the fix an+# app ships to its own# installer always lands ONE CLICK LATE, and the user sees a failure they have# already downloaded the fix for.#@@ -100,6 +100,27 @@ require "the vendored engine pin move" -- bash "$ROOT/scripts/pinokio/ltx_checko# mlx moves and nothing that depends on it is re-resolved.require "the mlx 0.31.1 pin" -- uv pip install --python "$VENV_PY" --reinstall --no-deps 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1'+# ---- 2b. THE TRANSFORMERS CAP — the one install.js has been promising -------+# install.js has said, since the 2026-07-10 ship-blocker, that "uv downgrades an+# already-installed 5.13.0 on the next Update". Nothing in the update path ever+# constrained transformers, so that sentence was false for a month: mlx-lm+# 0.31.1 declares `transformers>=5.0.0` with NO upper bound, and step 2 above+# uses --no-deps precisely so nothing else moves — which also means an existing+# 5.13.0 survives every Update untouched.+#+# The failure it leaves behind is total and silent: mlx_lm.tokenizer_utils+# breaks, the Gemma text-encoder load no-ops ("done in 0.0s"), and EVERY+# generation dies on "'str' object has no attribute '__module__'" →+# "Model not loaded. Call load() first." A user in that state can click Update,+# watch it succeed, and still not be able to render a single frame.+#+# FATAL, not best-effort: an install that finishes this script with 5.13.0+# cannot generate anything, so "continue and hope" is not a kindness. Resolved+# on the SAME uv invocation as the mlx trio (exactly as install.js:268 does it)+# so the solver cannot re-widen the cap while satisfying mlx-lm.+require "the transformers <5.13.0 cap (5.13.0 breaks every generation)" -- \+ uv pip install --python "$VENV_PY" 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1' 'transformers>=5.0.0,<5.13.0'+# ---- 3. Re-install the three vendored packages ------------------------------# This is what actually moves an existing user's RUNTIME: a bare git checkout# leaves the previous copy in site-packages. `--reinstall` also replaces thediff --git a/storyboard.py b/storyboard.pyindex 77ffbaf..c82a8a6 100644--- a/storyboard.py+++ b/storyboard.py@@ -1,6 +1,7 @@#!/usr/bin/env python3.11"""Storyboard — plan a run of shots that share a character, then shoot them.+WHAT THIS IS, IN PHOSPHENE'S OWN TERMS--------------------------------------Phosphene's thesis is "your trained character, in any scene." A storyboard is simply that at@@ -851,6 +852,23 @@ def shot_to_job(shot: dict, policy_pass: dict, *,return {k: v for k, v in job.items() if v is not None}+# THE ONE POLICY LITERAL. storyboard_planner.default_policy() had its own copy and+# they had drifted: this said Draft 640x448 (what a Quick render actually delivers,+# ffprobe-verified) while the planner said 640x480, a canvas the panel's own engine+# registry lists as never delivered. The main path masked it by keeping the board's+# existing policy, so only a direct planner consumer would ever have seen the+# fictional geometry. One literal, imported by the planner.+DEFAULT_POLICY: dict = {+ "draft": {"quality": "quick", "width": 640, "height": 448, "frames": 49},+ "final": {"quality": "balanced", "width": 1024, "height": 576, "frames": 121},+}+++def default_policy() -> dict:+ """A fresh copy of DEFAULT_POLICY — callers mutate it (the planner clamps it)."""+ return {k: dict(v) for k, v in DEFAULT_POLICY.items()}++def new_storyboard(board_id: str, title: str, *, shots: list[dict] | None = None,cast: list[dict] | None = None, policy: dict | None = None) -> dict:"""Build an empty, schema-correct storyboard. Kept here so the planner, the tests and any@@ -861,9 +879,6 @@ def new_storyboard(board_id: str, title: str, *, shots: list[dict] | None = None"title": title,"created_at": int(time.time()),"cast": cast or [],- "policy": policy or {- "draft": {"quality": "quick", "width": 640, "height": 448, "frames": 49},- "final": {"quality": "balanced", "width": 1024, "height": 576, "frames": 121},- },+ "policy": policy or default_policy(),"shots": shots or [],}diff --git a/storyboard_planner.py b/storyboard_planner.pyindex f3f36c6..c4ef494 100644--- a/storyboard_planner.py+++ b/storyboard_planner.py@@ -197,6 +197,22 @@ class PlannerError(Exception):# The validator we must satisfy — imported, never reimplemented# --------------------------------------------------------------------------------------+def _storyboard_module():+ """storyboard.py, or None if it cannot be imported.++ Same import path `_load_validator()` uses, but non-fatal: default_policy()+ is called from contexts that must not raise just because the schema module+ is unavailable, and it carries its own fallback literal.+ """+ if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))+ try:+ import storyboard # type: ignore+ return storyboard+ except Exception:+ return None++def _load_validator():"""Return (validate_fn, storyboard_module).@@ -274,6 +290,49 @@ L11 THE FACE IS THE WHOLE POINT. A shot is judged on whether the face reads. Ifwith no face in it. End on the face instead.A face may be dark, wet, bruised, half in shadow or lit from one side. It may not beturned away, blocked, cut off by the frame edge, or reduced to an outline.+L12 A CAST CHARACTER'S APPEARANCE IS FIXED, AND YOU CANNOT SEE IT. A cast character is a+ trained model of a real, specific face. What they look like is already decided and is+ NOT in this brief - so any physical description you write is a guess, and a guess that+ disagrees with the trained face FIGHTS it and degrades the likeness.+ For a cast character write ONLY: the trigger and name, their ROLE, their WARDROBE,+ their ACTION and their EMOTION. Never their species or creature type, never their+ face, hair, eyes, skin or build, never their age. This includes BODY PARTS that only+ one kind of creature has - no paw, muzzle, snout, fur, tail, whiskers, claws, hooves,+ wings or scales. They have hands.+ WRONG "bizarrotrn Bizarro, a grizzled badger in a military uniform, leans over ..."+ WRONG "bizarrotrn Bizarro, a tall bearded man in his fifties, leans over ..."+ RIGHT "bizarrotrn Bizarro, the unit's commander in a muddy field uniform, leans+ over the map table and traces the river with one finger"+ THIS LAW APPLIES TO CAST CHARACTERS AND TO NOBODY ELSE, and getting that wrong in the+ other direction ruins the film just as fast. EVERY OTHER CHARACTER **MUST** be+ described the way the concept asks - species, age, build, all of it. If the brief says+ the soldiers are humanoid animals, then the soldiers ARE humanoid animals, on screen,+ in the words, in as many shots as they appear: badgers, wolves, a boar sergeant. A+ plan that quietly turns them all into ordinary humans has thrown away the premise and+ is WRONG, even though every cast character in it is lawful.+ WHEN THE PREMISE COVERS EVERYONE - "all the characters are animals", "everyone is a+ robot" - the cast character is the ONE EXCEPTION, and the exception is SILENCE, not+ conversion. Do not say what they are. Do not turn the rest of the cast human to match+ them. Do not write a sentence explaining why they look different. Give the cast+ character a role, a uniform and an action, describe everyone else exactly as the+ premise demands, and let the trained face answer the only question you left open.+L13 NEVER WRITE SPEECH THE VIEWER CANNOT HEAR. A shot is either SPOKEN or SILENT, and you+ must choose one on purpose.+ SPOKEN the exact words are in the shot, in the dialogue form: <d>[English] Move out,+ and keep to the treeline.</d> Short - one or two sentences. The words being+ present IN THAT TAG is what switches the voice on. Quotation marks are not a+ substitute: He says, "Move out" leaves the voice switched OFF and the model+ guessing. The tag, every time.+ SILENT no speech happens at all. Then the description must not say that speech+ happens: no explains, briefs, tells, discusses, talks, orders, argues,+ murmurs, mutters, whispers, addresses, announces - and no describing a voice+ ("his voice low and authoritative"). The soundscape must not carry speech+ either: no murmur, chatter, voices, conversation, talking.+ "He explains the mission, his voice low and authoritative" with no words written is the+ worst of both: the model is told a man is speaking and given nothing to say, so it+ invents mouth noise. If the beat needs him to brief the unit, WRITE THE LINE. If it+ does not, show him working the map in silence and put footsteps, wind, paper and radio+ static in the soundscape instead."""_H3_EXAMPLES = """\@@ -495,12 +554,34 @@ def _build_user_prompt(" \"character_id\" to that id and is written in the LTX register:"]for c in cast:desc = (c.get("description") or "").strip()- lines.append(" - %s%s%s" % (+ noun = (c.get("subject_noun") or "").strip()+ pron = (c.get("pronoun") or "").strip()+ facts = []+ if noun:+ facts.append("a %s" % noun)+ if pron:+ facts.append("%s/%s" % (pron, "him" if pron == "he" else+ "her" if pron == "she" else "them"))+ lines.append(" - %s%s%s%s" % (c["id"],(" (%s)" % c["name"]) if c.get("name") and c["name"] != c["id"] else "",+ (" - %s" % ", ".join(facts)) if facts else "",(": " + desc) if desc else "",))- lines.append(" Any shot without a listed character sets \"character_id\": null.")+ # L12 restated where the cast is actually read, because the laws block is long and+ # this is the moment the model is deciding what these people look like.+ lines += [+ " THE LINE ABOVE IS EVERYTHING YOU KNOW ABOUT HOW THEY LOOK, and it is all you",+ " are allowed to imply. Their face is a trained model you cannot see. Give them",+ " a role, wardrobe, action and emotion - never a species, creature type, face,",+ " hair, eyes, build or age.",+ " EVERYONE ELSE IN THE FILM IS DESCRIBED NORMALLY, and if the concept gives the",+ " world a premise - humanoid animals, robots, a period, a species - that premise",+ " applies to them in full and must be visible in the shots they appear in. The",+ " cast character is the ONE you leave undescribed; they are not a reason to make",+ " the rest of the film plain.",+ " Any shot without a listed character sets \"character_id\": null.",+ ]else:lines += ["", "CAST: none. Every shot sets \"character_id\": null."]if must_include:@@ -836,6 +917,346 @@ _WANTS_HIDDEN_RE = re.compile(r"\bwithout showing (?:the |their |his |her )?face", re.IGNORECASE)+# --- the appearance law (L12) -----------------------------------------------------------+# A cast character is a trained LoRA. Its appearance is decided, it is not in the brief, and+# prose that guesses at it fights the weights at render time. The planner has no way to know+# this on its own, so it styles the cast like everything else in the film — measured live:+# "ww2 scene but main characters are humanoid animals, bizarrotrn is the boss of the team"+# produced "bizarrotrn Bizarro, a grizzled badger with a military uniform", assigning a+# SPECIES to the one face in the film that already has one.+#+# The detector is deliberately narrow, because the false positives are the expensive kind:+# wardrobe and rank are exactly what we WANT ("in a muddy officer's uniform", "the unit's+# commander"), and every non-cast character in an animal film is legitimately an animal. So+# it fires only on an appositive or copular phrase bound to the cast mention, and only when+# the part of that phrase describing what they ARE — the span before any wardrobe+# preposition — contains a species noun or a physical adjective.++_SPECIES = (+ r"badger|wolf|wolves|fox|vixen|bear|rabbit|hare|dog|hound|wolfhound|cat|feline|lion|"+ r"lioness|tiger|leopard|panther|jaguar|cheetah|stoat|weasel|otter|ferret|mink|marten|"+ r"mouse|mice|rat|squirrel|hedgehog|mole|shrew|boar|pig|hog|sow|stag|deer|doe|elk|moose|"+ r"goat|ram|sheep|ewe|bull|ox|cow|horse|stallion|mare|donkey|mule|zebra|"+ r"hawk|falcon|eagle|owl|raven|crow|rook|magpie|sparrow|finch|heron|stork|crane|gull|"+ r"duck|drake|goose|swan|rooster|cockerel|hen|chicken|turkey|pigeon|dove|"+ r"frog|toad|newt|lizard|gecko|snake|serpent|adder|viper|turtle|tortoise|crocodile|"+ r"fish|shark|whale|dolphin|seal|walrus|penguin|"+ r"ape|monkey|gorilla|chimp|chimpanzee|baboon|lemur|"+ r"dragon|griffin|gryphon|centaur|minotaur|satyr|faun|"+ r"elf|dwarf|orc|goblin|troll|ogre|gnome|hobbit|halfling|"+ r"vampire|werewolf|zombie|skeleton|ghost|demon|angel|deity|god|goddess|"+ r"robot|android|droid|cyborg|automaton|alien|extraterrestrial|mutant|"+ r"anthropomorphic|humanoid|creature|beast|critter|animal"+)+_SPECIES_RE = re.compile(r"\b(?:%s)s?\b" % _SPECIES, re.IGNORECASE)++_PHYS_ADJ = (+ r"old|older|elderly|aged|ancient|young|younger|youthful|teenage|teenaged|adolescent|"+ r"middle-aged|middleaged|boyish|girlish|weathered|grizzled|wizened|craggy|"+ r"tall|short|stocky|burly|brawny|hulking|lean|lanky|slim|slender|skinny|thin|scrawny|"+ r"wiry|muscular|muscled|husky|heavyset|heavy-set|stout|portly|obese|fat|plump|petite|"+ r"broad-shouldered|barrel-chested|squat|gaunt|"+ r"bald|balding|shaven|clean-shaven|bearded|moustached|mustachioed|whiskered|"+ r"long-haired|short-haired|red-haired|grey-haired|gray-haired|white-haired|"+ r"dark-haired|fair-haired|blonde|blond|brunette|redheaded|red-headed|ponytailed|"+ r"blue-eyed|green-eyed|brown-eyed|dark-eyed|wide-eyed|hollow-eyed|one-eyed|"+ r"scarred|freckled|wrinkled|pockmarked|jowly|chiselled|chiseled|square-jawed|"+ r"hook-nosed|snub-nosed|pale-skinned|dark-skinned|olive-skinned|ruddy|swarthy|"+ r"handsome|beautiful|pretty|ugly|homely|striking|"+ r"furred|furry|fur-covered|feathered|scaly|striped|spotted|shaggy|bristled|"+ r"black-furred|brown-furred|grey-furred|gray-furred|white-furred"+)+_PHYS_ADJ_RE = re.compile(r"\b(?:%s)\b" % _PHYS_ADJ, re.IGNORECASE)++# What the character WEARS, CARRIES or DOES. Never a violation, always desirable.+_WARDROBE_SPLIT_RE = re.compile(+ r"\b(?:in|wearing|dressed|clad|carrying|holding|armed|with)\b", re.IGNORECASE)+_WARDROBE_LEAD_RE = re.compile(+ r"^\s*(?:in|wearing|dressed|clad|carrying|holding|armed)\b", re.IGNORECASE)+++def _cast_mention_re(trigger: str, name: str) -> Optional[Any]:+ names = [n for n in (trigger, name) if n]+ if not names:+ return None+ alt = "|".join(re.escape(n) for n in names)+ return r"\b(?:%s)\b(?:\s+(?:%s)\b)?" % (alt, alt)+++def _appearance_violations(text: str, trigger: str, name: str = "") -> List[str]:+ """Appearance claims bound to a cast mention. Empty list = the prose is lawful."""+ mention = _cast_mention_re(trigger, name)+ if not mention or not text:+ return []+ pat = re.compile(r"%s\s*(?:,\s*|\s+(?:is|as)\s+)((?:a|an|the)\s+[^.;]{0,80})" % mention,+ re.IGNORECASE)+ out: List[str] = []+ for m in pat.finditer(text):+ clause = m.group(1)+ head = re.sub(r"^(?:a|an|the)\s+", "", clause, flags=re.IGNORECASE)+ if _WARDROBE_LEAD_RE.match(head):+ continue+ being = _WARDROBE_SPLIT_RE.split(head, maxsplit=1)[0]+ if _SPECIES_RE.search(being) or _PHYS_ADJ_RE.search(being):+ out.append(clause.strip())+ return out+++def _neutralise_appearance(text: str, trigger: str, name: str = "",+ subject_noun: str = "") -> Tuple[str, List[str]]:+ """Last resort, after a re-plan has already been spent. Returns (text, cuts).++ TOKEN SCRUB, not excision. Two designs were tried and thrown away first: cutting the+ appositive ate the sentence's verb ("Bizarro, with a military uniform leans over the+ map table"), and swapping the whole appositive for the canon noun could not be bounded+ correctly when the clause held its own comma ("a tall, broad-shouldered man") — it+ either truncated the clause or swallowed the action after it.++ Replacing the offending WORDS in place cannot do either, because it restructures+ nothing: the species noun becomes the bundle's canon noun, physical adjectives are+ deleted, and the verb, the wardrobe and the rest of the sentence are untouchable.+ """+ mention = _cast_mention_re(trigger, name)+ if not mention or not text:+ return text, []+ noun = subject_noun or "figure"+ cuts: List[str] = []+ win = re.compile(r"(%s\s*(?:,\s*|\s+(?:is|as)\s+)(?:a|an|the)\s+)([^.;]{0,90})" % mention,+ re.IGNORECASE)++ def fix(m):+ lead, body = m.group(1), m.group(2)+ being = _WARDROBE_SPLIT_RE.split(body, maxsplit=1)[0]+ tail = body[len(being):]+ if not (_SPECIES_RE.search(being) or _PHYS_ADJ_RE.search(being)):+ return m.group(0)+ cuts.append(being.strip().rstrip(","))+ fixed = _SPECIES_RE.sub(noun, being)+ fixed = _PHYS_ADJ_RE.sub("", fixed)+ # "humanoid fox" carries TWO species tokens and would become "man man".+ fixed = re.sub(r"\b%s(?:\s+%s\b)+" % (re.escape(noun), re.escape(noun)),+ noun, fixed, flags=re.IGNORECASE)+ fixed = re.sub(r"\s*,\s*(?=,|$)", "", fixed)+ fixed = re.sub(r"^[\s,]+", "", fixed)+ fixed = re.sub(r"\s*,\s*", ", ", fixed)+ fixed = re.sub(r"\s{2,}", " ", fixed).strip() or noun+ return lead + fixed + ((" " + tail.lstrip()) if tail.strip() else "")++ out = win.sub(fix, text)+ out = re.sub(r"\ban (?=[bcdfghjklmnpqrstvwxyz])", "a ", out, flags=re.IGNORECASE)+ out = re.sub(r"\s{2,}", " ", out)+ out = re.sub(r"\s+([,.])", r"\1", out)+ return out, cuts+++# --- the speech law (L13) ---------------------------------------------------------------+# Measured live on the same film: shot 1 read "He explains the mission, his voice low and+# authoritative" with no line written anywhere, and the soundscape carried "the quiet murmur+# of other animals". The <d> gating did its job and kept the voice LoRA OFF — correctly,+# there were no words — but the prompt still TOLD the model a man was speaking. Given speech+# to render and no words to render, the audio branch babbles. The owner's verdict on the+# clip was "talking gibberish".+#+# So a shot is SPOKEN (the words are present, which is also what flips the voice on) or it+# is SILENT (nothing may imply speech). Describing speech without providing it is the one+# combination that is always wrong.++# `brief` is deliberately NOT `brief(?:s|ing)?`: the first live run flagged "a dimly lit+# briefing room" three times, because a briefing room is a room. The verb needs an object.+_SPEECH_VERB_RE = re.compile(+ r"\b(?:explain(?:s|ing)?|brief(?:s|ed)\b|briefing (?:the|his|her|their|them|us)\b|"+ r"describ(?:es|ing)|discuss(?:es|ing)|"+ r"talk(?:s|ing)?|speak(?:s|ing)?|says?|saying|tell(?:s|ing)?|address(?:es|ing)?|"+ r"order(?:s|ing)?|command(?:s|ing)?|instruct(?:s|ing)?|argu(?:es|ing)|"+ r"murmur(?:s|ing)?|mutter(?:s|ing)?|whisper(?:s|ing)?|mumbl(?:es|ing)|"+ r"announc(?:es|ing)|declar(?:es|ing)|recit(?:es|ing)|narrat(?:es|ing)|"+ r"chat(?:s|ting)?|converse(?:s)?|conversing|reply|replies|replying|"+ r"answer(?:s|ing)?|ask(?:s|ing)?|shout(?:s|ing)?|call(?:s|ing) out|"+ r"read(?:s|ing)? (?:it )?(?:aloud|out))\b", re.IGNORECASE)++# Describing a voice is describing speech, even with no verb.+_VOICE_DESC_RE = re.compile(+ r"\b(?:his|her|their|the|a|its)\s+voice\b"+ r"|\bin a (?:low|quiet|soft|hushed|loud|steady|calm|firm|gravelly|hoarse|deep)\s+voice\b"+ r"|\bvoice (?:low|quiet|soft|steady|calm|firm|even|hard)\b"+ r"|\bmid-sentence\b|\bmid-speech\b", re.IGNORECASE)++# Speech-shaped AUDIO. The soundscape babbles from these on its own.+_SPEECH_AUDIO_RE = re.compile(+ r"\b(?:murmur(?:s|ing)?|chatter(?:ing)?|voices?|conversation(?:s)?|talking|speech|"+ r"dialogue|whisper(?:s|ing)?|mutter(?:s|ing)?|shouting|shouts|yelling|calls?|"+ r"chant(?:s|ing)?|singing|song|barked orders?|radio chatter)\b", re.IGNORECASE)++# The soundscape's own way of saying "silent", which the H3 exemplar already uses. Its+# presence means the model has consciously chosen silence, so the audio cue check is moot.+_SILENCE_DECLARED_RE = re.compile(+ r"\bnobody speaks\b|\bno voice is heard\b|\bno one speaks\b|\bno speech\b|"+ r"\bno dialogue\b|\bnobody says\b", re.IGNORECASE)++# A NEGATED cue is the opposite of a violation — "no voices", "without chatter" and "not a+# word is spoken" are how a soundscape says silence, and the H3 exemplars use exactly that+# form. Matching them as speech was the first false positive this law produced: it fired on+# "Steady rain on stone, a distant gutter running, no voices."+_NEGATED_CUE_RE = re.compile(+ r"\b(?:no|not|without|never|nobody|none|silent|silence)\b[\w\s]{0,12}$", re.IGNORECASE)+++def _unnegated_speech_audio(sound: str) -> Optional[str]:+ """The first speech cue in `sound` that is NOT negated, or None."""+ for m in _SPEECH_AUDIO_RE.finditer(sound or ""):+ if not _NEGATED_CUE_RE.search(sound[:m.start()]):+ return m.group(0)+ return None++_SILENCE_SENTENCE = "Nobody speaks and no voice is heard at any point."++# Silent stand-ins, for the mechanical fallback only. Each keeps the beat and removes the+# claim that a mouth is moving.+_SILENT_VERB_SWAP = (+ (re.compile(r"\bexplain(?:s|ing)?\b|\bbrief(?:s|ing)?\b|\bdescrib(?:es|ing)\b"+ r"|\bdiscuss(?:es|ing)\b|\bgoes over\b", re.IGNORECASE), "studies"),+ (re.compile(r"\border(?:s|ing)?\b|\bcommand(?:s|ing)?\b|\binstruct(?:s|ing)?\b",+ re.IGNORECASE), "signals"),+ (re.compile(r"\bmurmur(?:s|ing)?\b|\bmutter(?:s|ing)?\b|\bwhisper(?:s|ing)?\b"+ r"|\bmumbl(?:es|ing)\b", re.IGNORECASE), "leans in"),+ (re.compile(r"\btalk(?:s|ing)?\b|\bspeak(?:s|ing)?\b|\bchat(?:s|ting)?\b"+ r"|\bargu(?:es|ing)\b|\bconvers(?:es|ing)\b", re.IGNORECASE), "gestures"),+ (re.compile(r"\bsays?\b|\btell(?:s|ing)?\b|\bannounc(?:es|ing)\b|\bdeclar(?:es|ing)\b"+ r"|\baddress(?:es|ing)?\b|\brecit(?:es|ing)\b|\bnarrat(?:es|ing)\b"+ r"|\bask(?:s|ing)?\b|\banswer(?:s|ing)?\b|\brepl(?:y|ies|ying)\b"+ r"|\bshout(?:s|ing)?\b", re.IGNORECASE), "looks up"),+)+++# DIALOGUE IN THE WRONG CLOTHES. The first live run under this law turned up a failure the+# owner's clip had not shown: four of twelve shots DID carry real spoken lines — "He says,+# 'Gentlemen, we have a situation'" — written as ordinary prose quotes instead of the <d>+# form. That is worse than it looks. The words are there, so silencing the shot would throw+# away the director's line; but no <d> tag means the voice gate never flips, so the trained+# voice stays off and the audio branch improvises around words it was never handed properly.+# The fix is a CONVERSION, not a deletion: same words, correct wrapper, gate on.+_PROSE_DIALOGUE_RE = re.compile(+ r"(\b(?:says?|said|replies|replied|answers?|answered|asks?|asked|adds?|added|"+ r"calls?|called|shouts?|shouted|whispers?|whispered|murmurs?|murmured|"+ r"orders?|ordered|announces?|announced|declares?|declared)\b\s*[,:]?\s*)"+ r"[\"'“‘]([^\"'”’]{3,220})[\"'”’]")++_JAW_STOP = " His jaw ceases speaking motion and his mouth settles closed."+++def _has_dialogue(text: str) -> bool:+ """A <d> tag with actual words in it. An empty tag is not a line."""+ for m in _D_TAG_RE.finditer(text or ""):+ if (m.group(1) or "").strip():+ return True+ return False+++def _prose_dialogue(text: str) -> List[str]:+ """Spoken lines written as prose quotes instead of <d> tags."""+ if _has_dialogue(text):+ return []+ return [m.group(2).strip() for m in _PROSE_DIALOGUE_RE.finditer(text or "")]+++def _convert_prose_dialogue(text: str) -> Tuple[str, int]:+ """Rewrap prose-quoted lines as <d>[English] ...</d>. Returns (text, count)."""+ if _has_dialogue(text):+ return text, 0+ n = [0]++ def repl(m):+ n[0] += 1+ return "%s<d>[English] %s</d>" % (m.group(1), m.group(2).strip())++ out = _PROSE_DIALOGUE_RE.sub(repl, text or "")+ if n[0] and "ceases speaking motion" not in out:+ out = out.rstrip()+ # A closing </d> already ends the sentence — appending a full stop to it produces+ # "</d>." and the tag is the punctuation.+ if not out.endswith((".", "!", "?", ">")):+ out += "."+ out += _JAW_STOP+ return out, n[0]+++def _speech_violations(desc: str, sound: str) -> List[str]:+ """Speech implied but never written. Empty list = the shot is honestly silent or spoken."""+ if _has_dialogue(desc):+ return []+ out: List[str] = []+ quoted = _prose_dialogue(desc or "")+ if quoted:+ # The line EXISTS — this is a form error, not a silence error, and it is reported+ # on its own so the fix is "rewrap it", never "delete it".+ return ["wrote the spoken line %r as prose quotes instead of <d>[English] ...</d>, "+ "so the voice never switches on" % quoted[0][:60]]+ m = _SPEECH_VERB_RE.search(desc or "")+ if m:+ out.append("speech verb %r with no spoken line" % m.group(0))+ m = _VOICE_DESC_RE.search(desc or "")+ if m:+ out.append("describes a voice (%r) with no spoken line" % m.group(0))+ if not _SILENCE_DECLARED_RE.search(sound or ""):+ cue = _unnegated_speech_audio(sound or "")+ if cue:+ out.append("soundscape carries speech (%r) with no spoken line" % cue)+ return out+++def _neutralise_speech(desc: str, sound: str) -> Tuple[str, str, List[str]]:+ """Last resort: stage the shot silent rather than let it babble. (desc, sound, notes)."""+ notes: List[str] = []+ out_desc = desc or ""+ # CONVERT BEFORE SILENCING. A shot whose line is merely in the wrong wrapper keeps its+ # line — rewrapping flips the voice gate on and the beat survives intact. Silencing it+ # would delete words the director wrote, which is a worse outcome than the bug.+ converted, n_conv = _convert_prose_dialogue(out_desc)+ if n_conv:+ notes.append("rewrapped %d prose-quoted line(s) as <d>[English] ...</d>, so the "+ "voice switches on" % n_conv)+ return converted, (sound or ""), notes+ for pat, repl in _SILENT_VERB_SWAP:+ new = pat.sub(repl, out_desc)+ if new != out_desc:+ notes.append("silenced a speech verb")+ out_desc = new+ # "his voice low and authoritative" and friends: drop the clause, keep the sentence.+ new = re.sub(r",\s*(?:his|her|their|its)\s+voice\b[^.;]{0,60}", "", out_desc,+ flags=re.IGNORECASE)+ if new != out_desc:+ notes.append("dropped a voice description")+ out_desc = new+ out_sound = sound or ""+ if not _SILENCE_DECLARED_RE.search(out_sound):+ # PER FRAGMENT, not per sentence. A soundscape reads "Boots on wet planks, the quiet+ # murmur of other animals, rain on canvas." — dropping the whole sentence for one+ # bad clause throws away the boots and the rain, which were the good half of the+ # line and exactly what should carry the shot once the voices are gone.+ dropped = False+ sentences: List[str] = []+ for sent in re.split(r"(?<=[.!?])\s+", out_sound):+ if not sent.strip():+ continue+ if not _unnegated_speech_audio(sent):+ sentences.append(sent.strip())+ continue+ frags = [f.strip() for f in sent.split(",")]+ keep = [f for f in frags if f and not _unnegated_speech_audio(f)]+ dropped = dropped or len(keep) != len([f for f in frags if f])+ rebuilt = ", ".join(keep).strip(" .")+ if rebuilt:+ sentences.append(rebuilt + ".")+ if dropped:+ notes.append("removed speech from the soundscape")+ out_sound = " ".join(sentences).strip()+ out_sound = (out_sound + " " + _SILENCE_SENTENCE).strip() if out_sound \+ else _SILENCE_SENTENCE+ out_desc = re.sub(r"\s{2,}", " ", out_desc)+ out_desc = re.sub(r"\s+([,.])", r"\1", out_desc)+ return out_desc, out_sound, notes++def _face_level(raw: Any, desc: str) -> Tuple[str, bool]:"""Normalise the model's `face` choice. Returns (level, was_overridden).@@ -1073,6 +1494,15 @@ def _normalise_cast(characters: Optional[Iterable[Any]]) -> List[Dict[str, str]]"trigger": str(c.get("trigger") or cid).strip(),"name": str(c.get("name") or cid).strip(),"description": str(c.get("description") or c.get("bio") or "").strip(),+ # THE ONE APPEARANCE FACT THE BUNDLE ACTUALLY KNOWS. lora-lab writes+ # `subject_noun` ("man", "woman", "person") and `pronoun` into every+ # bundle.json, and the planner never saw either — so when a film's premise said+ # "everyone is an animal" the planner had nothing to contradict it with and+ # made the trained character a badger. It is deliberately the ONLY appearance+ # word that crosses: it is canon, it comes from the bundle rather than a guess,+ # and it is what the mechanical fallback substitutes back in.+ "subject_noun": str(c.get("subject_noun") or "").strip(),+ "pronoun": str(c.get("pronoun") or "").strip(),})return out@@ -1164,10 +1594,25 @@ def default_policy(max_dim: Optional[int] = None) -> Dict[str, Any]:validate_storyboard() rejects a policy whose longest edge exceeds `max_dim`, so theclamp happens here rather than being discovered at validation time."""- policy = {- "draft": {"quality": "quick", "width": 640, "height": 480, "frames": 49},- "final": {"quality": "balanced", "width": 1024, "height": 576, "frames": 121},- }+ # IMPORTED, NOT RESTATED. This held its own copy and the two had drifted:+ # storyboard.py said Draft 640x448 — what a Quick render actually delivers,+ # ffprobe-verified — and this said 640x480, a canvas the panel's own engine+ # registry lists as never delivered. The docstring above claimed both were+ # "the same shape". The main panel path masked it by keeping the board's+ # existing policy, so only a direct planner consumer would ever have been+ # handed the fictional geometry.+ # NO FALLBACK LITERAL. A second copy of the numbers was kept here "in case+ # the import fails", and a spare copy of a value that has already drifted+ # once is not insurance, it is the next drift waiting. storyboard.py is a+ # hard dependency of this module — coerce_spec() already calls into it for+ # the schema — so if it cannot be imported the honest outcome is the error,+ # not a policy nobody will ever notice is stale.+ _sb = _storyboard_module()+ if _sb is None or not hasattr(_sb, "default_policy"):+ raise PlannerError(+ "cannot import storyboard.default_policy() — the planner takes the "+ "render policy from storyboard.py and has no copy of its own")+ policy = _sb.default_policy()if max_dim:for key in ("draft", "final"):p = policy[key]@@ -1284,6 +1729,19 @@ def coerce_spec(if not desc.strip():warnings.append("shot %d was entirely face-hiding and was dropped" % (idx + 1))continue+ # --- the appearance law (L12) and the speech law (L13) --------------------------+ # Detected here so a direct caller of coerce_spec() is told, but NOT repaired here:+ # the plan loop gets to spend one targeted re-plan first, and a model rewrite beats+ # a regex rewrite every time it works. The mechanical fallback runs only after that+ # re-plan has been spent — see _enforce_laws().+ if char:+ for clause in _appearance_violations(desc, char["trigger"], char.get("name", "")):+ warnings.append("shot %d described %s's appearance (%r) — a cast character's "+ "look belongs to the trained face, not the prompt"+ % (idx + 1, char["trigger"], clause[:60]))+ for problem in _speech_violations(desc, sound):+ warnings.append("shot %d %s" % (idx + 1, problem))+if _TEXT_KEYWORD_RE.search(desc) and not _DQ_RE.search(desc):warnings.append("shot %d names on-screen text but does not put it in double ""quotes — H3 renders described strings as letter-shaped noise"@@ -1780,9 +2238,74 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validameta=dict(meta, warnings=warnings, elapsed_s=round(time.time() - t_start, 2),**_session_meta(sess)))+ # ---- L12 / L13: enforcement, not hope --------------------------------------------+ # After the plan is VALID, because both laws are about prose quality rather than schema+ # and a plan that fails the validator has a bigger problem than a species adjective.+ # Skipped on a per-shot re-roll: the caller is already editing one shot by hand, and+ # re-planning a re-plan from inside itself is how a 25 s call becomes a 4-minute one.+ _degraded: List[str] = []+ if fb_mode != "shot":+ def _replan_one(current, n, note):+ resp3 = sess.generate(+ system, _build_shot_feedback_prompt(current, n, note),+ max_tokens=min(budget, 1400),+ temperature=max(0.0, temperature * 0.6),+ seed=(seed_base + 7 + n) % 100000)+ meta["attempts"] = int(meta.get("attempts") or 0) + 1+ obj3 = extract_json_object(resp3.get("text") or "")+ if obj3 is None:+ return None+ fixed, warn3 = _coerce_for_mode(+ obj3, "shot", n, current, concept=concept, n_shots=n_shots, style=style,+ cast=cast, board_id=board_id, engine=engine, tier=tier,+ duration_s=duration_s, seed_base=seed_base, max_dim=max_dim, sb=sb,+ allow_hidden_faces=allow_hidden_faces)+ # A re-roll that breaks the SCHEMA is discarded outright — the law fix is not+ # worth an invalid plan, and the mechanical fallback can still clean the prose.+ if check(fixed):+ return None+ warnings.extend(w for w in warn3 if "law" not in w.lower())+ return fixed+ spec = _enforce_laws(spec, cast, warnings, replan=_replan_one, style=style, sb=sb)+ # The premise check runs LAST and only when the brief named creatures: the+ # appearance law is what puts it at risk, so it is checked after that law has+ # finished rewriting shots.+ _premise = _premise_species(" ".join([concept or "", style or ""]))+ spec = _enforce_premise(+ spec, cast, warnings, replan=_replan_one, style=style, sb=sb,+ premise=_premise)+ # ---- THE FINAL INVARIANT SCAN ------------------------------------+ # After the LAST mutation, whichever pass made it. Every pass before+ # this validated only the condition it owned, so the last repair could+ # silently undo an earlier guarantee and nothing looked.+ spec, _degraded = _assert_final_invariants(+ spec, cast, warnings, style=style, sb=sb, premise=_premise)+ else:+ # A RE-ROLL IS A PLAN TOO. The whole enforcement block above is skipped+ # for fb_mode == "shot" — correctly, because re-planning a re-plan from+ # inside itself turns a 25 s call into a four-minute one. But skipping+ # the RE-PLAN also skipped the final SCAN, so a re-rolled shot carrying+ # an L13 violation came back with ok: true, degraded: false and empty+ # reasons. The expensive part is the model round trip; scanning what it+ # returned costs nothing and is exactly the thing that must not be+ # optional. Mechanical repair still applies, and what cannot be repaired+ # is reported the same way a full plan reports it.+ _premise = _premise_species(" ".join([concept or "", style or ""]))+ spec, _degraded = _assert_final_invariants(+ spec, cast, warnings, style=style, sb=sb, premise=_premise)++ # A DEGRADED PLAN DOES NOT GET TO SAY ok=True. The final pass reports what it+ # could not repair — an unlawful shot, or a premise the film never showed —+ # and stamping success over that is how a known defect reaches a user with a+ # green tick on it. `ok` here is the PLANNER's metadata, not the top-level+ # error flag `is_plan_error()` reads, so a degraded plan is still a usable+ # storyboard the caller can render; it is simply no longer described as+ # clean, and `degraded_reasons` says why in the words the UI already shows.spec["_planner"] = dict(meta,- ok=True,+ ok=not _degraded,+ degraded=bool(_degraded),+ degraded_reasons=list(_degraded),warnings=warnings,first_try_errors=first_try,first_try_clean=first_try_clean,@@ -1796,6 +2319,361 @@ def _plan_with_session(sess, *, system, user, fb_mode, fb_shot, previous, validareturn spec+def _scan_laws(spec: Dict[str, Any],+ cast: Sequence[Dict[str, str]]) -> List[Tuple[int, List[str]]]:+ """Every shot that breaks L12 or L13, as [(shot_n, [reasons])].++ One entry per SHOT, not per law, because a shot that trips both gets ONE re-plan with+ both restated — sending the model back twice for the same paragraph wastes 20 s and+ invites it to fix the second complaint by reintroducing the first.+ """+ by_id = {c["id"]: c for c in cast}+ out: List[Tuple[int, List[str]]] = []+ for s in spec.get("shots") or ():+ if not isinstance(s, dict):+ continue+ desc = s.get("description") or ""+ sound = s.get("soundscape") or ""+ reasons: List[str] = []+ char = by_id.get(s.get("character_id"))+ if char:+ for clause in _appearance_violations(desc, char["trigger"], char.get("name", "")):+ reasons.append(+ "APPEARANCE (L12): you wrote %r. %s is a TRAINED face — you cannot see "+ "it and must not describe it. Keep the role, the wardrobe, the action "+ "and the emotion; delete the species, the build, the age and the "+ "features." % (clause[:70], char["trigger"]))+ for problem in _speech_violations(desc, sound):+ reasons.append(+ "SPEECH (L13): %s. Either write the actual line as <d>[English] ...</d>, or "+ "stage the shot silent — no speech verbs, no described voice, and no "+ "murmur/chatter/voices in the soundscape." % problem)+ if reasons:+ out.append((int(s.get("n") or 0), reasons))+ return out+++def _premise_species(brief: str) -> List[str]:+ """Species/creature words the BRIEF itself asked for. The film's premise, in the+ user's own words — never inferred, never the model's."""+ return sorted({m.group(0).lower() for m in _SPECIES_RE.finditer(brief or "")})+++# Irregular plurals the species table lists in both forms. A brief that says+# "wolves" is satisfied by a shot that says "wolf", and vice versa.+_SPECIES_FORMS = {+ "wolf": "wolves", "wolves": "wolf", "mouse": "mice", "mice": "mouse",+ "goose": "geese", "geese": "goose", "ox": "oxen", "oxen": "ox",+ "sheep": "sheep", "deer": "deer", "fish": "fish",+}+++def _premise_term_re(term: str) -> Any:+ """`fox` -> matches fox/foxes; `wolf` -> matches wolf/wolves."""+ forms = {term, _SPECIES_FORMS.get(term, "")} - {""}+ alts = sorted({re.escape(f) for f in forms})+ return re.compile(r"\b(?:%s)(?:e?s)?\b" % "|".join(alts), re.IGNORECASE)+++def _premise_terms_present(text: str, premise: Sequence[str]) -> bool:+ """Does `text` show the premise's OWN creatures?++ It used to be enough for ANY species word to appear anywhere, so a brief+ asking for a fox was considered preserved by a shot containing a robot —+ the check passed while the film had quietly become a different film. The+ premise is the user's words; only the user's words can satisfy it.+ """+ return any(_premise_term_re(t).search(text or "") for t in premise)+++def _premise_missing_terms(spec: Dict[str, Any], cast: Sequence[Dict[str, str]],+ premise: Sequence[str]) -> List[str]:+ """Which of the brief's OWN creatures never made it onto the screen.++ ALL THE TERMS, NOT ANY OF THEM. "the crew are a fox and a badger" was+ counted as preserved by a film containing only the fox — half the premise+ silently dropped and the check said fine. Every term the brief names has to+ appear somewhere the law does not govern.++ THE PRESENCE BUDGET. Requiring all of them unconditionally would be its own+ lie: a brief naming five species cannot show five in a two-shot film, and+ the format's own COMPOSITION LIMITS forbid crowding a shot with subjects to+ make a checker happy. So the requirement is capped by the number of uncast+ shots — the places a creature can legitimately appear. With room for two,+ two distinct terms are required; with room for one, one is enough.+ """+ if not premise:+ return []+ cast_ids = {c["id"] for c in cast}+ uncast = [s for s in (spec.get("shots") or ())+ if isinstance(s, dict) and s.get("character_id") not in cast_ids]+ if not uncast:+ return []+ seen, unseen = [], []+ for term in premise:+ rx = _premise_term_re(term)+ (seen if any(rx.search(s.get("description") or "") for s in uncast)+ else unseen).append(term)+ budget = min(len(premise), len(uncast))+ if len(seen) >= budget:+ return []+ return unseen+++def _premise_lost(spec: Dict[str, Any], cast: Sequence[Dict[str, str]],+ premise: Sequence[str]) -> bool:+ """Did the appearance law eat the film's own premise?++ THE OVER-CORRECTION, measured. Told never to give the cast character a species, the+ planner generalised it to never mentioning species AT ALL: the owner's "main+ characters are humanoid animals" film came back with zero animal words across twelve+ shots — every soldier on both sides quietly turned into an ordinary human, which is a+ different film. Each shot was individually lawful, and the plan was wrong.++ So the check is on the shots the law does NOT govern. If the brief named creatures and+ not one uncast shot shows them, the premise is gone.+ """+ return bool(_premise_missing_terms(spec, cast, premise))+++def _premise_note(premise: Sequence[str]) -> str:+ return ("This shot lost the film's premise. The brief asked for %s, and not one shot "+ "that is free to show them does. Re-write this shot so the characters in it "+ "are visibly what the concept says they are — the rule about not describing a "+ "trained cast character applies ONLY to that one character, never to anyone "+ "else, and it is not a reason to make the rest of the film plain."+ % ", ".join(premise[:4]))+++def _law_note(reasons: Sequence[str]) -> str:+ return ("This shot breaks a hard law of the format. Fix ONLY this, keep everything else "+ "word for word:\n" + "\n".join(" - %s" % r for r in reasons))+++def _reassemble_prompt(shot: Dict[str, Any], style: str,+ cast: Sequence[Dict[str, str]], sb: Any) -> str:+ """Rebuild the assembled prompt after a mechanical edit to description/soundscape."""+ desc = shot.get("description") or ""+ sound = shot.get("soundscape") or ""+ music = shot.get("music") or "N/A"+ camera = shot.get("camera") or "static"+ settle = shot.get("settle") or ""+ face = shot.get("face") or "medium"+ char = None+ for c in cast:+ if c["id"] == shot.get("character_id"):+ char = c+ break+ if shot.get("engine") == "h3":+ if char:+ return _assemble_h3_prompt(+ "%s The on-screen subject is %s." % (desc, char["trigger"]),+ sound, music, camera, settle, face)+ return _assemble_h3_prompt(desc, sound, music, camera, settle, face)+ prompt = _assemble_ltx_prompt(desc, sound, style, camera, settle, face)+ if char:+ if sb is not None and hasattr(sb, "ensure_trigger"):+ prompt = sb.ensure_trigger(prompt, char["trigger"])+ elif not re.search(r"\b%s\b" % re.escape(char["trigger"]), prompt):+ prompt = "%s %s" % (char["trigger"], prompt)+ return prompt+++def _assert_final_invariants(spec, cast, warnings, *, style, sb, premise=()):+ """The last word: every law, over the whole plan, after the last mutation.++ THE PASSES WERE NOT COMPOSABLE. Each one validated only the condition it+ owned — the law pass checked laws, the premise pass checked the premise —+ so the final repair could undo an earlier guarantee and nothing ever looked+ again. That is a structural hole, not a bug in any one pass: it reopens+ every time a new pass is added at the end.++ This runs after all of them, mechanically neutralises anything still+ standing, and — the part that matters — reports honestly when it cannot. A+ plan that reaches a user with a known violation must say so; the previous+ behaviour was to ship it under a warning claiming the repair had worked.+ """+ remaining = _scan_laws(spec, cast)+ if not remaining:+ missing = _premise_missing_terms(spec, cast, premise)+ if missing:+ msg = ("PLAN LOST PART OF ITS PREMISE: no shot shows %s. The concept "+ "asked for it and the film does not have it."+ % ", ".join(missing[:4]))+ warnings.append(msg)+ return spec, [msg]+ return spec, []+ by_id = {c["id"]: c for c in cast}+ for n, _reasons in remaining:+ for s in spec.get("shots") or ():+ if not isinstance(s, dict) or int(s.get("n") or 0) != n:+ continue+ touched = False+ char = by_id.get(s.get("character_id"))+ if char:+ fixed, cuts = _neutralise_appearance(+ s.get("description") or "", char["trigger"], char.get("name", ""),+ char.get("subject_noun", ""))+ if cuts:+ s["description"] = fixed+ touched = True+ d0, s0 = s.get("description") or "", s.get("soundscape") or ""+ d2, s2, _ = _neutralise_speech(d0, s0)+ if (d2, s2) != (d0, s0):+ s["description"], s["soundscape"] = d2, s2+ touched = True+ if touched:+ s["prompt"] = _reassemble_prompt(s, style, cast, sb)+ warnings.append("shot %d: final invariant pass had to repair it" % n)+ still = _scan_laws(spec, cast)+ degraded: List[str] = []+ if still:+ msg = ("PLAN SHIPPED WITH %d UNREPAIRED SHOT(S): %s. This is a defect, not a "+ "style note - re-roll those shots or re-word the concept."+ % (len(still), ", ".join(str(n) for n, _ in still)))+ warnings.append(msg)+ degraded.append(msg)+ # THE PREMISE IS AN INVARIANT TOO. This pass checked L12/L13 and stopped,+ # so a premise repair that failed was still the last word on the plan and+ # nothing downstream ever re-asked. Now it is asked here, after everything.+ missing = _premise_missing_terms(spec, cast, premise)+ if missing:+ msg = ("PLAN LOST PART OF ITS PREMISE: no shot shows %s. The concept asked "+ "for it and the film does not have it."+ % ", ".join(missing[:4]))+ warnings.append(msg)+ degraded.append(msg)+ return spec, degraded+++def _enforce_premise(spec, cast, warnings, *, replan, premise, style, sb) -> Dict[str, Any]:+ """One re-plan to put the film's own premise back, if the appearance law ate it.++ Bounded to a SINGLE uncast shot: one example is enough to re-anchor the world, and+ this runs after every other pass, so it must not turn a 40 s plan into a 4 minute one.+ """+ if not _premise_lost(spec, cast, premise):+ return spec+ warnings.append("the plan lost the brief's premise (%s) — no uncast shot shows them"+ % ", ".join(premise[:4]))+ cast_ids = {c["id"] for c in cast}+ target = next((s for s in (spec.get("shots") or ())+ if isinstance(s, dict) and s.get("character_id") not in cast_ids), None)+ if target is None:+ warnings.append("every shot is cast, so there is nowhere to restate the premise")+ return spec+ n = int(target.get("n") or 0)+ try:+ candidate = replan(spec, n, _premise_note(premise))+ except PlannerError as exc:+ warnings.append("premise re-plan failed (%s)" % exc)+ return spec+ if candidate is None:+ return spec+ # A REPAIR THAT BREAKS A LAW IS NOT A REPAIR. The replan helper validates+ # schema only, so a shot that came back with the premise restored could also+ # come back describing speech it never writes — and it was accepted, under a+ # warning that said "the premise is back". Measured by the external review:+ # a returned shot containing "explains the mission" with no dialogue tags.+ #+ # The premise is the LESSER law: a film that keeps its animals but babbles is+ # worse than one that lost its animals, and the animals can be asked for+ # again in the concept. Neutralise first; if it still violates, REJECT.+ broke = dict(_scan_laws(candidate, cast))+ if n in broke:+ for s_ in candidate.get("shots") or ():+ if isinstance(s_, dict) and int(s_.get("n") or 0) == n:+ d0, s0 = s_.get("description") or "", s_.get("soundscape") or ""+ d2, s2, _ = _neutralise_speech(d0, s0)+ if (d2, s2) != (d0, s0):+ s_["description"], s_["soundscape"] = d2, s2+ s_["prompt"] = _reassemble_prompt(s_, style, cast, sb)+ if n in dict(_scan_laws(candidate, cast)):+ warnings.append("shot %d: the premise re-plan broke a hard law and was "+ "REJECTED - the film keeps its previous shot %d" % (n, n))+ return spec+ warnings.append("shot %d: the premise re-plan needed silencing to stay lawful" % n)+ if _premise_lost(candidate, cast, premise):+ # Not neutralised mechanically: writing a badger into someone's film is authorship,+ # not repair, and a wrong guess is worse than the omission. The warning stands and+ # the user can re-roll the shot themselves.+ warnings.append("shot %d was re-planned and the premise is still missing — say it "+ "again in the concept, or re-roll a shot" % n)+ else:+ warnings.append("shot %d: re-planned and the premise is back" % n)+ return candidate+++def _enforce_laws(spec, cast, warnings, *, replan, style, sb) -> Dict[str, Any]:+ """L12/L13: one targeted re-plan per offending shot, then a mechanical fallback.++ `replan(current, n, note) -> spec | None` re-rolls ONE shot through the existing+ per-shot machinery, which carries every other shot across by reference — so a film+ whose shot 4 was fixed is byte-identical everywhere else.++ THE CURRENT SPEC IS AN ARGUMENT, and that is not decoration. It was a closure over the+ caller's `spec` for one draft, which meant every re-plan spliced its fix into the+ ORIGINAL plan: fix shot 1, then fix shot 2 against the unfixed plan, and shot 1's fix+ is gone. A live 4-shot film reported "shot 1: re-planned and now obeys", the same for+ 2 and 3, and then failed the final scan on all three — three model calls spent to+ change nothing. Threading it through is what makes the fixes accumulate.++ The fallback is not optional. A law that is only enforced when the model cooperates is+ a suggestion, and L12 exists because the model demonstrably does not cooperate.+ """+ offenders = _scan_laws(spec, cast)+ if not offenders:+ return spec+ warnings.append("law check: %d shot(s) broke the appearance or speech law on the first "+ "pass" % len(offenders))+ for n, reasons in offenders:+ try:+ candidate = replan(spec, n, _law_note(reasons))+ except PlannerError as exc:+ candidate = None+ warnings.append("shot %d: law re-plan failed (%s)" % (n, exc))+ if candidate is not None:+ still = dict(_scan_laws(candidate, cast))+ if n not in still:+ spec = candidate+ warnings.append("shot %d: re-planned and now obeys the law" % n)+ continue+ # The re-plan came back and broke it again — keep it (it may be better prose)+ # and let the mechanical pass finish the job.+ spec = candidate+ # --- mechanical fallback, second failure only --------------------------------+ by_id = {c["id"]: c for c in cast}+ for s in spec.get("shots") or ():+ if not isinstance(s, dict) or int(s.get("n") or 0) != n:+ continue+ char = by_id.get(s.get("character_id"))+ touched = False+ if char:+ fixed, cuts = _neutralise_appearance(+ s.get("description") or "", char["trigger"], char.get("name", ""),+ char.get("subject_noun", ""))+ if cuts:+ s["description"] = fixed+ touched = True+ for c in cuts:+ warnings.append("shot %d: appearance %r was written for a trained "+ "face and has been neutralised" % (n, c[:60]))+ d0, s0 = s.get("description") or "", s.get("soundscape") or ""+ d2, s2, notes = _neutralise_speech(d0, s0)+ # Keyed on the DIFF, not on `notes`: appending the silence sentence is a real+ # change that produces no note of its own, and a shot that reached here has+ # already been flagged — leaving it half-fixed is the worst outcome.+ if d2 != d0 or s2 != s0:+ s["description"], s["soundscape"] = d2, s2+ touched = True+ for note in (notes or ["staged the shot silent"]):+ warnings.append("shot %d: %s (the shot is now honestly silent)"+ % (n, note))+ if touched:+ s["prompt"] = _reassemble_prompt(s, style, cast, sb)+ return spec++def _session_meta(sess: PlannerSession) -> Dict[str, Any]:return _session_meta_from(sess.stats)diff --git a/test_character_roundtrip.py b/test_character_roundtrip.pynew file mode 100644index 0000000..58a551d--- /dev/null+++ b/test_character_roundtrip.py@@ -0,0 +1,391 @@+#!/usr/bin/env python3+"""The Character round-trip gate — it EXECUTES the panel's own JavaScript.++WHY THIS FILE WAS REWRITTEN. The first version asserted the contract by grepping+mlx_ltx_panel.py for the calls it hoped were present. All 12 tests passed while+the live Characters loader was still broken and the visible slider still+displayed a different number from the one being submitted. An external review+called it a false positive, and it was: a test that passes by finding strings is+worse than no test, because it also reports the area as covered.++This version extracts the REAL functions — charactersSyncStrengthControls,+_restoreCharacterStrengths, charactersLoadParams — plus the REAL slider markup,+and runs them in node against a small DOM shim. What it asserts is the property+the user experiences:++ displayed value == submitted value == restored value++If a function stops doing that, the test fails. If a function is renamed or+deleted, extraction raises and the test fails loudly rather than quietly going+back to grepping.+"""+import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import ( # noqa: E402+ attr, extract_element, extract_function, extract_object, panel_source,+)++import mlx_ltx_panel as P # noqa: E402++NODE = shutil.which("node")++# A DOM shim just large enough for the functions under test: getElementById,+# element values, textContent, and the querySelectorAll calls they make.+DOM_SHIM = r"""+const _els = {};+function _mk(id, props) {+ // A real <input>.value ALWAYS coerces to string. The shim does the same, so a+ // type bug in the panel shows up here instead of being smoothed over.+ let _v = '';+ const e = Object.assign({+ id, textContent: '', min: '', max: '', className: '',+ dataset: {}, hidden: false, style: {}, innerHTML: '',+ classList: { toggle(){}, add(){}, remove(){}, contains(){ return false } },+ querySelector(){ return null }, querySelectorAll(){ return [] },+ setAttribute(){}, getAttribute(){ return null }, appendChild(){}, remove(){},+ dispatchEvent(){ return true }, addEventListener(){}, focus(){}, blur(){},+ }, props || {});+ Object.defineProperty(e, 'value', {+ get() { return _v; },+ set(x) { _v = (x === null || x === undefined) ? '' : String(x); },+ enumerable: true, configurable: true,+ });+ if (props && Object.prototype.hasOwnProperty.call(props, 'value')) e.value = props.value;+ _els[id] = e;+ return e;+}+global.document = {+ getElementById: (id) => _els[id] || null,+ querySelector: () => null,+ querySelectorAll: () => [],+ createElement: () => _mk('_tmp'),+ addEventListener: () => {},+ body: { dataset: {}, classList: { toggle(){}, add(){}, remove(){}, contains(){return false} } },+};+global.window = global;+global.BOOT = { ltx: {} };+global.escapeHtml = (s) => String(s);+global.Event = function (t) { this.type = t; };+global.CustomEvent = global.Event;+global.fetch = async () => ({ json: async () => ({}) });+global._renderCharsAppliedNote = () => {};+global.selectManualCharacter = () => {};+global._setCharacterQuality = () => {};+global.renderLorasList = () => {};+global.charactersRenderChips = () => {};+global.charactersEscapeAttr = (s) => String(s);+global.charactersEscapeHtml = (s) => String(s);+global.setMode = () => {};+global.setQuality = () => {};+global.workflowSwitch = () => {};+global.charactersOpenCompose = () => {};+global.charactersBackToGrid = () => {};+global.charactersInit = async () => {};+global.setAspect = () => {};+global.updateEstimate = () => {};+global.localStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {} };+// The loader refuses a character it cannot find — correctly. Seed the list the+// panel would have loaded from /characters.+global._manualCharacters = [{ id: 'bizarrotrn', trigger: 'bizarrotrn', name: 'Bizarro',+ face_lora_path: 'f.safetensors', audio_lora_path: 'a.safetensors' }];+global._activeLoras = [];+global.refreshManualCharacters = async () => {};+global.console = console;+// Auto-vivify: charactersLoadParams touches a known, small set of ids and one+// querySelectorAll. Creating on demand keeps the shim honest — if the loader+// starts touching something new, it still runs, and the ASSERTIONS are what+// decide whether it behaved.+const _origGet = global.document.getElementById;+global.document.getElementById = (id) => _els[id] || _mk(id);+global.document.querySelectorAll = (sel) => (sel === '#aspectGroup .pill-btn')+ ? [_mk('_aspL', {dataset:{aspect:'landscape'}}), _mk('_aspV', {dataset:{aspect:'vertical'}})]+ : [];+"""+++def _run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ raise AssertionError("node failed:\n%s\n%s" % (r.stdout[-2000:], r.stderr[-2000:]))+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)+++class _JS:+ """Lazily extracted panel JavaScript, shared by the cases below."""+ _src = None++ @classmethod+ def src(cls):+ if cls._src is None:+ cls._src = panel_source()+ return cls._src++ @classmethod+ def fn(cls, name):+ return extract_function(name, cls.src())++ @classmethod+ def state(cls):+ return extract_object("CHARACTERS", cls.src())+++def _run_loader(sidecar):+ """Execute the REAL charactersLoadParams() against the DOM shim.++ This is the difference between a gate and a rumour: the function is+ extracted from the panel, run in node, and the DOM it leaves behind is what+ the assertions read. Insert an early return anywhere above the restoration+ and these tests fail.+ """+ script = DOM_SHIM + """+%s+%s+%s+window.CHARACTERS = %s;+_mk('characterStrength', {value: ''});+_mk('characterVoiceStrength', {value: ''});+_mk('charactersStrength', {value: '0.8', min: '0.4', max: '1.2'});+_mk('charactersStrengthValue', {textContent: '0.80'});+_mk('width', {value: ''}); _mk('height', {value: ''});+(async () => {+ await charactersLoadParams(%s);+ console.log(JSON.stringify({+ face: document.getElementById('characterStrength').value,+ voice: document.getElementById('characterVoiceStrength').value,+ slider: document.getElementById('charactersStrength').value,+ displayed: document.getElementById('charactersStrengthValue').textContent,+ width: document.getElementById('width').value,+ height: document.getElementById('height').value,+ }));+})().catch(e => { console.error(e); process.exit(3); });+""" % (_JS.fn("charactersSyncStrengthControls"),+ _JS.fn("_restoreCharacterStrengths"),+ _JS.fn("charactersLoadParams"),+ _JS.state(), json.dumps(sidecar))+ return _run_node(script)+++class TestVisibleEqualsSubmitted(unittest.TestCase):+ """The defect the review found: the form displayed 0.80 and submitted 1.0."""++ def test_slider_markup_is_not_a_second_default(self):+ el = extract_element("charactersStrength", _JS.src())+ markup_value = float(attr(el, "value"))+ state = re.search(r"charStrength:\s*([0-9.]+)", _JS.state()).group(1)+ # The markup value is a placeholder; what matters is that the sync+ # function exists to overwrite it. But if they disagree AND nothing+ # syncs, the user reads one number and sends another.+ script = DOM_SHIM + """+%s+%s+window.CHARACTERS = %s;+_mk('charactersStrength', {value: '%s', min: '%s', max: '%s'});+_mk('charactersStrengthValue', {textContent: '%.2f'});+charactersSyncStrengthControls();+console.log(JSON.stringify({+ displayed: document.getElementById('charactersStrengthValue').textContent,+ slider: document.getElementById('charactersStrength').value,+ state: window.CHARACTERS.charStrength,+}));+""" % (_JS.fn("charactersUpdateStrengthDisplay"),+ _JS.fn("charactersSyncStrengthControls"),+ _JS.state(), markup_value, attr(el, "min"), attr(el, "max"), markup_value)+ out = _run_node(script)+ self.assertEqual(float(out["slider"]), float(state),+ "the visible slider does not hold the state's value")+ self.assertEqual(float(out["displayed"]), float(state),+ "the printed number does not match the state's value")++ def test_untouched_form_displays_what_it_submits(self):+ """End to end: sync the control, then read what the submit path sends."""+ script = DOM_SHIM + """+%s+%s+window.CHARACTERS = %s;+_mk('charactersStrength', {value: '0.8', min: '0.4', max: '1.2'});+_mk('charactersStrengthValue', {textContent: '0.80'});+charactersSyncStrengthControls();+// what charactersGenerate() would put on the form, by its own expressions+const submittedFace = String(window.CHARACTERS.charStrength ?? 1.0);+const submittedVoice = String(window.CHARACTERS.voiceStrength ?? 1.0);+console.log(JSON.stringify({+ displayed: document.getElementById('charactersStrengthValue').textContent,+ submittedFace, submittedVoice,+}));+""" % (_JS.fn("charactersUpdateStrengthDisplay"),+ _JS.fn("charactersSyncStrengthControls"), _JS.state())+ out = _run_node(script)+ self.assertEqual(float(out["displayed"]), float(out["submittedFace"]),+ "displayed %s but submits %s" % (out["displayed"], out["submittedFace"]))+ self.assertEqual(float(out["submittedFace"]), 1.0)+ self.assertEqual(float(out["submittedVoice"]), 1.0)++ def test_the_submit_path_sends_both_strengths(self):+ body = _JS.fn("charactersGenerate")+ self.assertIn("character_strength", body)+ self.assertIn("character_voice_strength", body,+ "the voice strength is never submitted, so it cannot round-trip")+++class TestRestoreRunsInBothLoadPaths(unittest.TestCase):+ """The remainder the review found: the live Characters branch returned before+ the Manual path's restoration, so NEITHER strength came back."""++ def _restore(self, sidecar):+ script = DOM_SHIM + """+%s+%s+window.CHARACTERS = %s;+_mk('characterStrength', {value: ''});+_mk('characterVoiceStrength', {value: ''});+_mk('charactersStrength', {value: '0.8', min: '0.4', max: '1.2'});+_mk('charactersStrengthValue', {textContent: '0.80'});+_restoreCharacterStrengths(%s);+console.log(JSON.stringify({+ face: document.getElementById('characterStrength').value,+ voice: document.getElementById('characterVoiceStrength').value,+ slider: document.getElementById('charactersStrength').value,+ displayed: document.getElementById('charactersStrengthValue').textContent,+ stateFace: window.CHARACTERS.charStrength,+ stateVoice: window.CHARACTERS.voiceStrength,+}));+""" % (_JS.fn("charactersSyncStrengthControls"),+ _JS.fn("_restoreCharacterStrengths"), _JS.state(), json.dumps(sidecar))+ return _run_node(script)++ def test_both_strengths_come_back(self):+ out = self._restore({"character_strength": 0.9, "character_voice_strength": 1.4})+ self.assertEqual(float(out["face"]), 0.9)+ self.assertEqual(float(out["voice"]), 1.4)++ def test_the_visible_control_follows_the_restore(self):+ # Restoring a value the user cannot see is the same bug in a new place.+ out = self._restore({"character_strength": 0.65, "character_voice_strength": 1.1})+ self.assertEqual(float(out["slider"]), 0.65)+ self.assertEqual(float(out["displayed"]), 0.65)++ def test_a_value_outside_the_slider_range_is_still_shown(self):+ # The markup caps at 1.2; the server accepts up to 2.0. A restored 1.6+ # must not be silently clamped to something the user never chose.+ out = self._restore({"character_strength": 1.6, "character_voice_strength": 1.0})+ self.assertEqual(float(out["slider"]), 1.6)+ self.assertEqual(float(out["face"]), 1.6)++ def test_the_LIVE_loader_restores_both_strengths(self):+ """charactersLoadParams() ITSELF, executed.++ The previous version of this test string-checked that the loader+ contained a call to the restorer. An early return inserted above that+ call would still have passed — which is precisely the defect the loader+ shipped with. This runs the real function end to end and reads the DOM+ it leaves behind, so an early return fails the suite."""+ out = _run_loader({+ "source": "characters", "character_id": "bizarrotrn", "mode": "t2v",+ "width": 704, "height": 384, "frames": 121,+ "character_strength": 0.65, "character_voice_strength": 1.4,+ "prompt": "at the map table", "seed": 7,+ })+ self.assertEqual(float(out["face"]), 0.65,+ "the LIVE loader did not restore the face strength")+ self.assertEqual(float(out["voice"]), 1.4,+ "the LIVE loader did not restore the voice strength")+ self.assertEqual(float(out["slider"]), 0.65)+ self.assertEqual(out["width"], "704")+ self.assertEqual(out["height"], "384")++ def test_the_live_loader_round_trips_pro_too(self):+ out = _run_loader({+ "source": "characters", "character_id": "bizarrotrn", "mode": "t2v",+ "width": 1024, "height": 576, "frames": 121,+ "character_strength": 1.0, "character_voice_strength": 1.0,+ "prompt": "x", "seed": 1,+ })+ self.assertEqual(float(out["face"]), 1.0)+ self.assertEqual(float(out["voice"]), 1.0)+ self.assertEqual(out["width"], "1024")+++class TestDraftCanvasRoundTrips(unittest.TestCase):+ """A Draft render must reopen as Draft — exercised through the real loader's+ own expression, not a restatement of it."""++ def _is_draft(self, w, h):+ body = _JS.fn("charactersLoadParams")+ m = re.search(r"const _draftPairs = (\[.*?\]);", body, re.S)+ self.assertIsNotNone(m, "the loader no longer declares _draftPairs")+ script = DOM_SHIM + """+const _draftPairs = %s;+const sidecarW = %d, sidecarH = %d;+const isDraft = _draftPairs.some(([w, h]) =>+ (sidecarW === w && sidecarH === h) || (sidecarW === h && sidecarH === w));+console.log(JSON.stringify({isDraft}));+""" % (m.group(1), w, h)+ return _run_node(script)["isDraft"]++ def test_the_size_the_server_emits_is_recognised(self):+ w, h = P._CHARACTER_QUALITY_RESOLUTION["draft"]+ self.assertTrue(self._is_draft(w, h),+ "Load Params does not recognise the Draft canvas the server "+ "emits (%dx%d), so Draft renders reopen as Pro" % (w, h))++ def test_legacy_and_vertical_still_round_trip(self):+ self.assertTrue(self._is_draft(736, 416))+ self.assertTrue(self._is_draft(384, 704))++ def test_pro_is_not_mistaken_for_draft(self):+ w, h = P._CHARACTER_QUALITY_RESOLUTION["high"]+ self.assertFalse(self._is_draft(w, h))+++class TestServerContract(unittest.TestCase):+ def test_server_defaults_match_the_client_state(self):+ state = _JS.state()+ face = float(re.search(r"charStrength:\s*([0-9.]+)", state).group(1))+ voice = float(re.search(r"voiceStrength:\s*([0-9.]+)", state).group(1))+ src = _JS.src()+ s_face = float(re.search(+ r'form\.get\("character_strength",\s*\["([0-9.]+)"\]', src).group(1))+ s_voice = float(re.search(+ r'form\.get\("character_voice_strength",\s*\["([0-9.]+)"\]', src).group(1))+ self.assertEqual(face, s_face)+ self.assertEqual(voice, s_voice)++ def test_full_payload_round_trip(self):+ """payload -> sidecar -> restore -> payload, over the real restorer."""+ for quality, face, voice in (("draft", 1.0, 1.0), ("high", 1.0, 1.0),+ ("draft", 1.15, 0.75), ("high", 0.9, 1.4)):+ w, h = P._CHARACTER_QUALITY_RESOLUTION[quality]+ first = {"character_id": "bizarrotrn", "width": w, "height": h,+ "frames": 121, "character_strength": face,+ "character_voice_strength": voice}+ sidecar = json.loads(json.dumps(first))+ sidecar["source"] = "characters"+ out = _run_loader(sidecar) # the LIVE loader, not the helper+ self.assertEqual(float(out["face"]), first["character_strength"], first)+ self.assertEqual(float(out["voice"]), first["character_voice_strength"], first)+ self.assertEqual(out["width"], str(first["width"]), first)+ self.assertEqual(out["height"], str(first["height"]), first)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_storyboard_planner.py b/test_storyboard_planner.pyindex f076067..1aaa784 100644--- a/test_storyboard_planner.py+++ b/test_storyboard_planner.py@@ -805,5 +805,520 @@ class TestLivePlanner(unittest.TestCase):meta["first_try_clean"]))+class TestAppearanceLaw(unittest.TestCase):+ """L12. Every string here came from, or was written against, the live defect:++ "ww2 scene but main characters are humanoid animals, bizarrotrn is the boss of the+ team. they are with the allies. the bad guys are natzi animals as well."++ which planned "bizarrotrn Bizarro, a grizzled badger with a military uniform" — a+ SPECIES assigned to the one face in the film that already has one.+ """++ def _v(self, text):+ return P._appearance_violations(text, "bizarrotrn", "Bizarro")++ def test_the_live_defect_is_caught(self):+ self.assertTrue(self._v(+ "bizarrotrn Bizarro, a grizzled badger with a military uniform, leans over "+ "the map table."))++ def test_species_age_and_build_are_all_caught(self):+ for bad in (+ "bizarrotrn Bizarro, an anthropomorphic badger in an allied coat, salutes.",+ "bizarrotrn, a tall broad-shouldered man, kicks the door open.",+ "bizarrotrn Bizarro, a scarred old wolf, moves into the treeline.",+ "bizarrotrn is a humanoid fox in a flight jacket.",+ "bizarrotrn Bizarro, a grey-furred stoat, checks his rifle.",+ ):+ self.assertTrue(self._v(bad), "missed: %s" % bad)++ def test_wardrobe_rank_and_action_are_never_violations(self):+ # These are what we WANT the planner to write. A law that eats them is worse than+ # no law: it would strip the only concrete direction a cast shot carries.+ for good in (+ "bizarrotrn Bizarro, in a muddy allied officer's uniform, leans over the map.",+ "bizarrotrn Bizarro, the boss of the team, points at the ridge.",+ "bizarrotrn Bizarro, a sergeant in the allied unit, waves the squad forward.",+ "bizarrotrn Bizarro, carrying a field radio, crouches behind the sandbags.",+ "bizarrotrn Bizarro stands at the map table and traces the river with a finger.",+ "bizarrotrn Bizarro, a commander who has not slept, rubs his eyes.",+ ):+ self.assertFalse(self._v(good), "false positive: %s" % good)++ def test_every_other_character_may_still_be_an_animal(self):+ # The premise is the film's to keep. Only the CAST character is undescribable.+ for good in (+ "A grizzled badger sergeant in a nazi greatcoat sneers across the table.",+ "Two humanoid wolves in enemy uniforms drag a crate through the mud.",+ "bizarrotrn Bizarro faces a hulking boar officer across the bunker.",+ ):+ self.assertFalse(self._v(good), "the premise was suppressed: %s" % good)++ def test_the_fallback_substitutes_canon_and_keeps_the_action(self):+ out, cuts = P._neutralise_appearance(+ "bizarrotrn Bizarro, a grizzled badger with a military uniform, leans over "+ "the map table.", "bizarrotrn", "Bizarro", "man")+ self.assertEqual(out, "bizarrotrn Bizarro, a man with a military uniform, leans "+ "over the map table.")+ self.assertTrue(cuts)++ def test_the_fallback_never_eats_the_verb(self):+ # The failure mode of the two designs that were rejected before token-scrub.+ for text in (+ "bizarrotrn Bizarro, a scarred old wolf, moves into the treeline.",+ "bizarrotrn, a tall, broad-shouldered man, kicks the door open.",+ "bizarrotrn Bizarro, a grey-furred stoat, checks his rifle.",+ ):+ out, _ = P._neutralise_appearance(text, "bizarrotrn", "Bizarro", "man")+ self.assertFalse(P._appearance_violations(out, "bizarrotrn", "Bizarro"))+ self.assertTrue(out.rstrip().endswith("."), out)+ self.assertIn(text.rsplit(",", 1)[-1].strip().rstrip("."), out)++ def test_the_bundles_subject_noun_reaches_the_planner(self):+ # lora-lab writes subject_noun into every bundle; it was being dropped on the floor.+ cast = P._normalise_cast([{"id": "bizarrotrn", "name": "Bizarro",+ "subject_noun": "man", "pronoun": "he"}])+ self.assertEqual(cast[0]["subject_noun"], "man")+ prompt = P._build_user_prompt("a ww2 film", 6, "", cast, [])+ self.assertIn("a man", prompt)+ self.assertIn("never a species", prompt.lower().replace("-", " ")+ if "never a species" in prompt.lower() else prompt.lower())+++class TestSpeechLaw(unittest.TestCase):+ """L13. From the same film: shot 1 read "He explains the mission, his voice low and+ authoritative" with no line written anywhere, and the soundscape carried "the quiet+ murmur of other animals". The voice gate was correctly OFF — there were no words — so+ the model was told a man was speaking and given nothing to say. It babbled."""++ def test_the_live_defect_is_caught(self):+ v = P._speech_violations(+ "He explains the mission, his voice low and authoritative.",+ "Boots on wet planks, the quiet murmur of other animals, rain on canvas.")+ self.assertEqual(len(v), 3, v) # verb, voice description, audio cue++ def test_a_written_line_is_the_whole_point_and_passes(self):+ self.assertFalse(P._speech_violations(+ "bizarrotrn Bizarro leans over the map. <d>[English] Move out, and keep to the "+ "treeline.</d> His jaw ceases speaking motion and his mouth settles closed.",+ "Rain on canvas and boots on wet planks."))++ def test_an_empty_dialogue_tag_is_not_a_line(self):+ self.assertTrue(P._speech_violations("He explains the plan. <d>[English] </d>", ""))++ def test_a_genuinely_silent_shot_passes(self):+ self.assertFalse(P._speech_violations(+ "bizarrotrn Bizarro traces the river on the map with one finger and taps twice.",+ "Rain on canvas, boots on wet planks, a radio hissing static."))++ def test_negated_cues_are_how_silence_is_written(self):+ # THE first false positive this law produced: the planner's own exemplars end+ # soundscapes with "no voices", which is a declaration of silence, not speech.+ for quiet in ("Steady rain on stone, a distant gutter running, no voices.",+ "Wind over the ridge. Nobody speaks and no voice is heard at any point.",+ "Rain on canvas, without chatter of any kind."):+ self.assertFalse(P._speech_violations("He taps the map twice.", quiet), quiet)++ def test_the_fallback_keeps_the_good_ambience(self):+ # Dropping the whole sentence for one bad clause threw away the boots and the rain,+ # which are exactly what should carry a silent shot.+ _, sound, notes = P._neutralise_speech(+ "He explains the mission.",+ "Boots on wet planks, the quiet murmur of other animals, rain on canvas.")+ self.assertIn("Boots on wet planks", sound)+ self.assertIn("rain on canvas", sound)+ self.assertNotIn("murmur", sound)+ self.assertIn("Nobody speaks", sound)+ self.assertTrue(notes)++ def test_a_briefing_room_is_a_room(self):+ # The first false positive the LIVE run produced, three times in one film:+ # `brief(?:s|ing)?` matched the noun in "a dimly lit briefing room".+ self.assertFalse(P._speech_violations("A dimly lit briefing room, full of maps.", ""))+ self.assertFalse(P._speech_violations("He exits the briefing room.", ""))+ # ...but the verb still has to be caught.+ self.assertTrue(P._speech_violations("He is briefing the team on the crossing.", ""))+ self.assertTrue(P._speech_violations("He briefs the team.", ""))++ def test_a_prose_quoted_line_is_rewrapped_not_deleted(self):+ # The LIVE run's second finding: 4 of 12 shots carried REAL lines written as+ # ordinary quotes. No <d> tag means the voice gate never flips — but the words are+ # the director's and deleting them is worse than the bug.+ d = ("bizarrotrn Bizarro nods curtly. He says, 'Gentlemen, we have a situation.'")+ v = P._speech_violations(d, "Chairs scrape.")+ self.assertEqual(len(v), 1)+ self.assertIn("prose quotes", v[0])+ out, sound, notes = P._neutralise_speech(d, "Chairs scrape.")+ self.assertIn("<d>[English] Gentlemen, we have a situation.</d>", out)+ self.assertTrue(P._has_dialogue(out), "the voice gate must now flip on")+ self.assertFalse(P._speech_violations(out, sound))+ self.assertIn("ceases speaking motion", out, "L6 wants the mouth stopped")+ self.assertNotIn("</d>.", out, "double punctuation after the tag")+ self.assertTrue(any("rewrapped" in n for n in notes), notes)+ self.assertEqual(sound, "Chairs scrape.", "a spoken shot keeps its soundscape")++ def test_the_fallback_silences_the_verb_and_the_voice(self):+ desc, sound, _ = P._neutralise_speech(+ "bizarrotrn Bizarro explains the mission, his voice low and authoritative.",+ "Rain on canvas.")+ self.assertFalse(P._speech_violations(desc, sound), desc)+ self.assertNotIn("explains", desc)+ self.assertNotIn("voice", desc)+++class TestLawEnforcement(unittest.TestCase):+ """The laws are enforced by the plan loop, not merely reported by it."""++ CAST = [{"id": "bizarrotrn", "trigger": "bizarrotrn", "name": "Bizarro",+ "subject_noun": "man", "pronoun": "he"}]+ BAD = ("bizarrotrn Bizarro, a grizzled badger with a military uniform, leans over the "+ "map table and sets down a brass compass beside the river marker.")+ GOOD = ("bizarrotrn Bizarro, the unit's commander in a muddy field uniform, leans over "+ "the map table and sets down a brass compass beside the river marker.")++ def _film(self, desc, n=2):+ return json.dumps({"title": "Night Crossing", "shots": [+ _shot(i + 1, description=desc if i == 0 else+ "Live-action, cinematic, rain beads on a brass compass on a folded map.",+ character_id="bizarrotrn" if i == 0 else None)+ for i in range(n)]})++ def test_a_violation_is_re_planned_and_the_fix_is_kept(self):+ one = json.dumps({"title": "Night Crossing",+ "shots": [_shot(1, description=self.GOOD,+ character_id="bizarrotrn")]})+ spec, stub = _plan([self._film(self.BAD), one], n_shots=2,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertFalse(P._appearance_violations(spec["shots"][0]["description"],+ "bizarrotrn", "Bizarro"))+ self.assertIn("badger", stub.calls[1]["user"],+ "the re-plan must quote the offending clause back")+ self.assertIn("APPEARANCE (L12)", stub.calls[1]["user"])++ def test_a_second_violation_is_neutralised_mechanically(self):+ # The model refuses twice. The law still holds — that is the difference between+ # enforcement and hope.+ spec, _ = _plan([self._film(self.BAD), self._film(self.BAD)], n_shots=2,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ desc = spec["shots"][0]["description"]+ self.assertFalse(P._appearance_violations(desc, "bizarrotrn", "Bizarro"), desc)+ self.assertNotIn("badger", desc.lower())+ self.assertIn("a man", desc)+ self.assertIn("compass", desc, "the action was destroyed by the fallback")+ self.assertNotIn("badger", spec["shots"][0]["prompt"].lower(),+ "the assembled prompt was not rebuilt after the fix")++ def test_a_lawful_plan_costs_no_extra_model_calls(self):+ spec, stub = _plan([self._film(self.GOOD)], n_shots=2,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual(len(stub.calls), 1, "a clean plan must not trigger a re-plan")++ def test_fixes_for_several_shots_all_survive(self):+ """The bug a live 4-shot film found and the single-offender tests could not.++ `replan` closed over the caller's spec, so every re-roll spliced its fix into the+ ORIGINAL plan: shot 1 fixed, shot 2 fixed against the unfixed plan, shot 1's fix+ gone. The film reported "re-planned and now obeys" three times and then failed the+ final scan on all three — three model calls spent to change nothing.+ """+ bad = json.dumps({"title": "Night Crossing", "shots": [+ _shot(1, description=self.BAD, character_id="bizarrotrn"),+ _shot(2, description=self.BAD.replace("brass compass", "field radio"),+ character_id="bizarrotrn"),+ _shot(3, description="Live-action, cinematic, rain beads on a folded map."),+ ]})+ def fixed(n, extra):+ return json.dumps({"title": "Night Crossing", "shots": [+ _shot(n, description=self.GOOD.replace("brass compass", extra),+ character_id="bizarrotrn")]})+ spec, stub = _plan([bad, fixed(1, "brass compass"), fixed(2, "field radio")],+ n_shots=3, characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual(len(stub.calls), 3, "one plan + one re-plan per offending shot")+ for s in spec["shots"]:+ self.assertFalse(+ P._appearance_violations(s.get("description", ""), "bizarrotrn", "Bizarro"),+ "shot %s kept its violation: %r" % (s.get("n"), s.get("description", "")[:80]))+ # and each fix is the one that shot was given, not the last one to arrive+ self.assertIn("brass compass", spec["shots"][0]["description"])+ self.assertIn("field radio", spec["shots"][1]["description"])++ def test_the_law_must_not_eat_the_films_premise(self):+ """The over-correction, measured live on the owner's film.++ Told never to give the CAST character a species, the planner generalised it to+ never mentioning species at all: twelve shots, zero animal words, every soldier on+ both sides quietly an ordinary human. Each shot was individually lawful and the+ film was wrong. The law is scoped to one character; the premise belongs to+ everyone else.+ """+ concept = ("ww2 scene but main characters are humanoid animals, bizarrotrn is the "+ "boss of the team. the bad guys are natzi animals as well.")+ self.assertTrue(P._premise_species(concept), "the brief plainly names creatures")+ plain = json.dumps({"title": "Operation Wildfire", "shots": [+ _shot(1, description=self.GOOD, character_id="bizarrotrn"),+ _shot(2, description="Live-action, cinematic, two soldiers in muddy allied "+ "uniforms drag a crate through the rain."),+ ]})+ withanimals = json.dumps({"title": "Operation Wildfire", "shots": [+ _shot(2, description="Live-action, cinematic, two humanoid wolves in muddy "+ "allied uniforms drag a crate through the rain.")]})+ spec, stub = _plan([plain, withanimals], n_shots=2, concept=concept,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ # the uncast shot carries the premise again...+ self.assertTrue(P._SPECIES_RE.search(spec["shots"][1]["description"]),+ spec["shots"][1]["description"])+ # ...while the cast character is still undescribed+ self.assertFalse(P._appearance_violations(spec["shots"][0]["description"],+ "bizarrotrn", "Bizarro"))+ self.assertIn("premise", stub.calls[-1]["user"].lower())++ def test_the_premise_needs_its_OWN_terms_not_any_species(self):+ """A robot is not a fox.++ `_premise_lost()` accepted ANY species word, so a brief asking for a fox+ was considered preserved by a shot containing a robot — the check passed+ while the film had quietly become a different film. Found by the external+ review, which also noted the old test codified the same weak condition by+ asserting only that some _SPECIES_RE matched.+ """+ premise = P._premise_species("a lone fox mechanic repairs a lunar rover")+ self.assertEqual(premise, ["fox"])+ robot = {"shots": [{"n": 1, "character_id": None,+ "description": "A hulking robot welds a strut in the bay."}]}+ foxes = {"shots": [{"n": 1, "character_id": None,+ "description": "Two foxes in overalls weld a strut."}]}+ self.assertTrue(P._premise_lost(robot, [], premise),+ "a robot must not satisfy a brief that asked for a fox")+ self.assertFalse(P._premise_lost(foxes, [], premise))++ def test_irregular_plurals_still_match(self):+ premise = P._premise_species("the soldiers are humanoid wolves")+ self.assertIn("wolves", premise)+ one = {"shots": [{"n": 1, "character_id": None,+ "description": "A wolf sharpens his bayonet."}]}+ self.assertFalse(P._premise_lost(one, [], premise),+ "'wolf' must satisfy a brief that said 'wolves'")++ def test_a_premise_repair_that_breaks_a_law_is_rejected(self):+ """The review's probe: a returned shot containing 'explains the mission'+ with no dialogue tags, accepted, under a warning claiming the premise was+ back. The premise is the lesser law — a film that keeps its animals but+ babbles is worse than one that lost them."""+ concept = "ww2 scene but the soldiers are humanoid wolves"+ plain = json.dumps({"title": "Op", "shots": [+ _shot(1, description=self.GOOD, character_id="bizarrotrn"),+ _shot(2, description="Live-action, cinematic, two soldiers drag a crate."),+ ]})+ # The premise comes back, but so does an unwritten speech act.+ unlawful = json.dumps({"title": "Op", "shots": [+ _shot(2, description="Live-action, cinematic, two humanoid wolves drag a "+ "crate. The sergeant explains the mission to them.")]})+ spec, _ = _plan([plain, unlawful], n_shots=2, concept=concept,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ shot2 = spec["shots"][1]+ # Whatever survived, it must be LAWFUL — either neutralised or rejected.+ self.assertFalse(P._speech_violations(shot2.get("description", ""),+ shot2.get("soundscape", "")),+ "an unlawful repair was shipped: %r" % shot2.get("description"))+ # And the warning must record what actually happened. "the premise is+ # back" is honest ONLY once the shot is lawful — which is the whole+ # point: the claim and the state have to match.+ warns = " ".join((spec.get("_planner") or {}).get("warnings") or [])+ self.assertTrue(+ ("needed silencing to stay lawful" in warns) or ("REJECTED" in warns),+ "the unlawful repair was accepted silently: %s" % warns)++ def test_the_final_scan_runs_after_the_last_mutation(self):+ # The structural hole: each pass validated only its own condition, so the+ # LAST repair could undo an earlier guarantee with nothing left to look.+ self.assertTrue(hasattr(P, "_assert_final_invariants"))+ spec = {"shots": [{"n": 1, "character_id": "bizarrotrn",+ "engine": "ltx", "camera": "static", "face": "medium",+ "settle": "he is still", "music": "N/A",+ "soundscape": "Rain on canvas.",+ "description": "bizarrotrn Bizarro, a grizzled badger, "+ "explains the mission to the unit."}]}+ warnings = []+ out, degraded = P._assert_final_invariants(+ spec, self.CAST, warnings, style="", sb=None)+ s = out["shots"][0]+ self.assertFalse(P._appearance_violations(s["description"], "bizarrotrn", "Bizarro"))+ self.assertFalse(P._speech_violations(s["description"], s["soundscape"]))+ self.assertTrue(any("final invariant" in w for w in warnings), warnings)++ def test_an_unrepairable_plan_says_so_out_loud(self):+ spec = {"shots": [{"n": 1, "character_id": None, "engine": "ltx",+ "camera": "static", "face": "medium", "settle": "still",+ "music": "N/A", "soundscape": "Wind.",+ "description": "A radio voice reads the coordinates aloud."}]}+ warnings = []+ _out, _deg = P._assert_final_invariants(+ spec, self.CAST, warnings, style="", sb=None)+ joined = " ".join(warnings)+ if P._speech_violations(spec["shots"][0]["description"],+ spec["shots"][0]["soundscape"]):+ self.assertIn("UNREPAIRED", joined,+ "a plan shipped with a known violation must say so")++ def test_multi_term_premise_needs_ALL_its_terms(self):+ """Codex's probe: "a fox and badger premise is considered preserved when+ only one appears". Half the premise silently dropped, check said fine."""+ premise = P._premise_species("a heist film where the crew are a fox and a badger")+ self.assertEqual(premise, ["badger", "fox"])+ two_shots = lambda a, b: {"shots": [+ {"n": 1, "character_id": None, "description": a},+ {"n": 2, "character_id": None, "description": b}]}+ only_fox = two_shots("A fox in a tuxedo cracks the safe.", "Rain on the car.")+ self.assertTrue(P._premise_lost(only_fox, [], premise),+ "half a premise is not a preserved premise")+ self.assertEqual(P._premise_missing_terms(only_fox, [], premise), ["badger"])+ both = two_shots("A fox cracks the safe.", "A badger keeps watch.")+ self.assertFalse(P._premise_lost(both, [], premise))++ def test_the_presence_budget_does_not_demand_the_impossible(self):+ """A brief naming five species cannot show five in a one-shot film, and+ the format's own composition limits forbid crowding a shot to satisfy a+ checker. The requirement is capped by the number of uncast shots."""+ premise = P._premise_species("the crew are a fox and a badger")+ one_shot = {"shots": [{"n": 1, "character_id": None,+ "description": "A fox cracks the safe."}]}+ self.assertFalse(P._premise_lost(one_shot, [], premise),+ "with room for one creature, one is enough")++ def test_the_final_pass_checks_the_premise_too(self):+ # It checked L12/L13 and stopped, so a failed premise repair was the last+ # word on the plan and nothing downstream ever re-asked.+ premise = ["wolves"]+ spec = {"shots": [{"n": 1, "character_id": None, "engine": "ltx",+ "camera": "static", "face": "medium", "settle": "still",+ "music": "N/A", "soundscape": "Wind.",+ "description": "Two soldiers drag a crate through mud."}]}+ warnings = []+ _out, degraded = P._assert_final_invariants(+ spec, self.CAST, warnings, style="", sb=None, premise=premise)+ self.assertTrue(degraded, "a lost premise must degrade the plan")+ self.assertIn("LOST PART OF ITS PREMISE", " ".join(degraded))++ def test_a_degraded_plan_does_not_claim_ok(self):+ """A failed premise repair must not stamp _planner.ok=True."""+ concept = "ww2 scene but the soldiers are humanoid wolves"+ # Both the plan and its repair omit the premise entirely.+ plain = json.dumps({"title": "Op", "shots": [+ _shot(1, description=self.GOOD, character_id="bizarrotrn"),+ _shot(2, description="Live-action, cinematic, two soldiers drag a crate."),+ ]})+ still_plain = json.dumps({"title": "Op", "shots": [+ _shot(2, description="Live-action, cinematic, two soldiers lift a crate.")]})+ spec, _ = _plan([plain, still_plain], n_shots=2, concept=concept,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), "still a usable storyboard")+ blk = spec["_planner"]+ self.assertFalse(blk["ok"], "a degraded plan must not report ok=True")+ self.assertTrue(blk["degraded"])+ self.assertTrue(blk["degraded_reasons"])+ self.assertIn("PREMISE", " ".join(blk["degraded_reasons"]).upper())++ def test_a_clean_plan_still_reports_ok(self):+ ok = json.dumps({"title": "Op", "shots": [+ _shot(1, description=self.GOOD, character_id="bizarrotrn"),+ _shot(2, description="Live-action, cinematic, a humanoid wolf lifts a crate."),+ ]})+ spec, _ = _plan([ok], n_shots=2, concept="soldiers are humanoid wolves",+ characters=self.CAST, engine="ltx")+ blk = spec["_planner"]+ self.assertTrue(blk["ok"])+ self.assertFalse(blk["degraded"])+ self.assertEqual(blk["degraded_reasons"], [])++ def test_a_shot_reroll_is_scanned_like_any_other_plan(self):+ """The enforcement block is skipped for fb_mode == "shot" — correctly,+ because re-planning a re-plan from inside itself turns a 25 s call into+ four minutes. But it skipped the final SCAN too, so a re-rolled shot+ carrying an L13 violation came back ok: true, degraded: false, empty+ reasons. Codex's probe, as a test."""+ prev = {"schema": 1, "id": "sb-x", "title": "Op", "created_at": 0, "cast": [],+ "policy": P.default_policy(),+ "shots": [{"n": 1, "title": "a", "mode": "text", "engine": "ltx",+ "tier": "draft", "prompt": "x", "duration_s": 5.0, "seed": 1,+ "refs": [], "status": "pending",+ "description": "A quiet room.", "camera": "static",+ "face": "medium", "settle": "still",+ "soundscape": "Wind.", "music": "N/A"}]}+ reroll = json.dumps({"title": "Op", "shots": [_shot(+ 1, description="Live-action, cinematic, he explains the mission to the unit.",+ soundscape="The low murmur of voices.")]})+ spec, _ = _plan([reroll], n_shots=1, feedback={"shot": 1, "note": "redo"},+ previous=prev)+ self.assertFalse(P.is_plan_error(spec), spec)+ s = spec["shots"][0]+ # The violation must not survive into the plan the user gets...+ self.assertFalse(P._speech_violations(s["description"], s["soundscape"]),+ "a re-rolled shot shipped an L13 violation: %r" % s["description"])+ self.assertNotIn("explains", s["description"])+ self.assertNotIn("murmur", s["soundscape"])+ # ...and the assembled prompt must be rebuilt, not left stale.+ self.assertNotIn("explains", s["prompt"])+ self.assertTrue(any("final invariant" in w+ for w in (spec["_planner"].get("warnings") or [])),+ spec["_planner"].get("warnings"))++ def test_a_clean_shot_reroll_stays_clean_and_quiet(self):+ prev = {"schema": 1, "id": "sb-y", "title": "Op", "created_at": 0, "cast": [],+ "policy": P.default_policy(),+ "shots": [{"n": 1, "title": "a", "mode": "text", "engine": "ltx",+ "tier": "draft", "prompt": "x", "duration_s": 5.0, "seed": 1,+ "refs": [], "status": "pending",+ "description": "A quiet room.", "camera": "static",+ "face": "medium", "settle": "still",+ "soundscape": "Wind.", "music": "N/A"}]}+ reroll = json.dumps({"title": "Op", "shots": [_shot(+ 1, description="Live-action, cinematic, he traces the river with one finger.")]})+ spec, _ = _plan([reroll], n_shots=1, feedback={"shot": 1, "note": "redo"},+ previous=prev)+ blk = spec["_planner"]+ self.assertTrue(blk["ok"])+ self.assertFalse(blk["degraded"])+ self.assertFalse(any("final invariant" in w for w in (blk.get("warnings") or [])))++ def test_a_film_that_kept_its_premise_costs_no_extra_call(self):+ concept = "ww2 scene but the soldiers are humanoid animals"+ ok = json.dumps({"title": "Operation Wildfire", "shots": [+ _shot(1, description=self.GOOD, character_id="bizarrotrn"),+ _shot(2, description="Live-action, cinematic, a humanoid badger sergeant in a "+ "nazi greatcoat sneers across the table."),+ ]})+ spec, stub = _plan([ok], n_shots=2, concept=concept, characters=self.CAST,+ engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual(len(stub.calls), 1)++ def test_a_film_with_no_creature_premise_is_never_premise_checked(self):+ ok = json.dumps({"title": "The Key", "shots": [+ _shot(1, description=self.GOOD, character_id="bizarrotrn"),+ _shot(2, description="Live-action, cinematic, rain beads on a brass key."),+ ]})+ spec, stub = _plan([ok], n_shots=2, concept="a lost brass key finds its door",+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ self.assertEqual(len(stub.calls), 1, "an ordinary film must not pay for this check")++ def test_one_shot_breaking_both_laws_is_re_planned_once(self):+ both = (self.BAD.rstrip(".") + ", and he explains the mission, his voice low.")+ spec, stub = _plan([self._film(both), self._film(both)], n_shots=2,+ characters=self.CAST, engine="ltx")+ self.assertFalse(P.is_plan_error(spec), spec)+ # Exactly one re-plan call for the one offending shot, carrying BOTH complaints.+ self.assertEqual(len(stub.calls), 2, [c["user"][:40] for c in stub.calls])+ self.assertIn("APPEARANCE (L12)", stub.calls[1]["user"])+ self.assertIn("SPEECH (L13)", stub.calls[1]["user"])++if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/update.js b/update.jsindex f06aa4a..2c5c623 100644--- a/update.js+++ b/update.js@@ -68,15 +68,87 @@ module.exports = {// The bare form uses the configured upstream and fast-forwards correctly;// the reset --hard fallback is kept, and now only fires when it is true.// Measured against the real update path, not reasoned about.+ // v4.0.1 FIX — THE UPDATE IS TRANSACTIONAL NOW, AND IT WAS NOT.+ //+ // The old block ignored the fetch result and sent EVERY pull failure to+ // `git reset --hard $UPSTREAM`. `$UPSTREAM` is the LOCAL tracking ref, so+ // when the fetch was the thing that failed the reset landed on the stale+ // ref that was already checked out — a no-op that exits 0. The sequence a+ // user offline (or behind an auth failure) actually got was:+ //+ // failed fetch → failed pull → "successful" reset onto old code →+ // successful rev-parse → post_update runs against the old tree →+ // Update reports success and nothing has changed.+ //+ // The same fallback also could not tell a dirty worktree from genuine+ // divergent history, so it answered "you have local edits" by destroying+ // them.+ //+ // Split into two steps, both short enough for the dispatch gate, and the+ // ordering is the guarantee: NOTHING moves the tree until a fetch has+ // provably succeeded, and reset only ever runs against a ref that fetch+ // just refreshed.+ {+ method: "shell.run",+ params: {+ message: [+ "U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)",+ "[ -n \"$U\" ] || { echo 'FATAL: no upstream configured'; exit 1; }",+ "echo \"updating $(git rev-parse --abbrev-ref HEAD) from $U\"",+ "git fetch \"${U%%/*}\" || { echo 'FATAL: fetch failed (offline?) - nothing changed, re-run Update'; exit 1; }"+ ].join("\n")+ }+ },+ // Converge. A reset is reached ONLY on proven history divergence.+ //+ // v4.0.1 second pass — THE UNTRACKED-FILE DELETION PATH. The previous+ // version classified every merge failure that left tracked files clean as+ // "divergence" and reset. But `git diff --quiet` IGNORES UNTRACKED FILES,+ // so the most common non-divergence failure — an untracked path that a+ // newly tracked upstream path would overwrite — passed both checks, and+ // `git reset --hard` then deleted the user's file as the "obstruction".+ // A user who dropped a note or a config beside the app lost it to an+ // update that had no local commits to reconcile in the first place.+ //+ // Divergence is now PROVEN, not inferred from what else failed:+ // `git rev-list --count $U..HEAD` is the number of commits this clone has+ // that upstream does not. Zero means the history did not diverge, whatever+ // made the merge fail — so we stop and print git's own error, which names+ // the obstructing paths. Nothing is deleted on that path, ever.+ // THE OBSTRUCTION GUARD, and it runs BEFORE anything can move the tree.+ //+ // The rev-list proof added in the previous pass only covered the+ // zero-local-commit case. A clone that has genuinely diverged (A > 0) AND+ // holds an untracked file where upstream now tracks one still reached+ // `reset --hard`, because both `git diff` checks ignore untracked files —+ // so the reset deleted it while legitimately reconciling real divergence.+ // Divergence and obstruction are independent facts and the destructive+ // step must clear BOTH.+ //+ // The set is computed exactly: every untracked path that also exists in the+ // fetched upstream tree (`git cat-file -e $U:<path>`). No process+ // substitution, so it behaves the same under sh, bash and zsh.+ {+ method: "shell.run",+ params: {+ message: [+ "U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})",+ "O=$(git status --porcelain -uall | sed -n 's/^?? //p' | while read -r f; do git cat-file -e \"$U:$f\" 2>/dev/null && echo \"$f\"; done)",+ "[ -z \"$O\" ] || { echo \"$O\"; echo 'FATAL: the untracked files above are tracked upstream. Move them, then Update. Nothing deleted.'; exit 1; }"+ ].join("\n")+ }+ },{method: "shell.run",params: {message: [- "REMOTE=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null | cut -d/ -f1)",- "UPSTREAM=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)",- "echo \"updating branch: $(git rev-parse --abbrev-ref HEAD) (upstream: $UPSTREAM)\"",- "git fetch $REMOTE",- "git pull --ff-only || (echo 'not a fast-forward; resetting to upstream' && git reset --hard $UPSTREAM)",+ "U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})",+ "M=$(git merge --ff-only \"$U\" 2>&1) && exec git rev-parse --short HEAD",+ "A=$(git rev-list --count \"$U\"..HEAD)",+ "[ \"$A\" -gt 0 ] || { echo \"$M\"; echo 'FATAL: blocked above; history has NOT diverged. Nothing deleted.'; exit 1; }",+ "git diff --quiet && git diff --cached --quiet || { echo 'FATAL: local edits to tracked files'; exit 1; }",+ "echo \"diverged: $A commit(s) - resetting\"",+ "git reset --hard \"$U\" || exit 1","git rev-parse --short HEAD"].join("\n")}