@aicopycoders/exodus 2026.11.1100-beta.5 → 2026.11.1100-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -50,6 +50,10 @@ keep their existing timing. After the worker update, **Cut again** can reuse the
50
50
  existing clips for this reservation-only failure; it does not require generating
51
51
  new clips.
52
52
 
53
+ A measured native cut that exceeds its frozen length budget offers a longer target
54
+ and plan re-approval. Re-cutting unchanged selected clips is deterministic, so the
55
+ length refusal does not offer that as a recovery action.
56
+
53
57
  Storyboard caption and overlay boxes use normalized `[x, y, width, height]`.
54
58
  The first-cut text adapter converts them to the renderer's
55
59
  `[left, top, right, bottom]`; source-ad reference boxes already use that renderer
@@ -57,6 +61,21 @@ contract and are preserved. Invalid geometry still holds the finish without
57
61
  clamping. After the worker update, **Cut again** can retry a caption-geometry
58
62
  adapter failure using the existing clips; no clip regeneration is needed.
59
63
 
64
+ Template sound choices stay explicit through prompt compilation, worker finishing
65
+ and CLI pull: `roomTone: false` requests no ambience and adds neither a room-tone
66
+ asset nor fallback brown noise. An absent historical choice keeps its existing
67
+ behavior. A selected music bed is independent of room tone; music-off templates
68
+ do not mix a stray bed file. In worker cuts and hand cuts from `exodus video pull`,
69
+ an actual held song master owns the audio alone: the pull carries `wholeVoice`
70
+ and `templateMotion` so first-cut omits the selected music bed. `songAsVoice` being
71
+ enabled without a held song does not suppress a selected bed or other sound.
72
+ The worker and backend share the same song-ownership check: a picked track or a
73
+ kept master counts; a pending song request alone does not.
74
+ The backend exposes `heldSong` only for a trusted template launch; ordinary
75
+ and legacy runs keep their existing response shape.
76
+ Narration takes a separate bed only when selected; no sound choice changes the
77
+ approved words, action windows or playback speed.
78
+
60
79
  #### V2 input assistance and script review
61
80
 
62
81
  Template input assistance is **not execution automation**:
@@ -307,10 +326,44 @@ If you edit the script or its bound context, first quote and authorize another
307
326
  script check using `--resume-script` with **`--stop-at-script --json`**. Review and
308
327
  save that refreshed response before separately quoting storyboard preparation.
309
328
  Neither a quote nor a previously signed receipt silently reapproves changed copy.
329
+
330
+ Template script receipts last **24 hours** and belong to the approving member in
331
+ that workspace. Resume using an API key owned by that same member (rotating the
332
+ key without changing its owner is fine). Receipt **v2** predates member/expiry
333
+ binding and cannot authorize a new storyboard quote or launch; this receipt version
334
+ is separate from the V2 template-input API. Already launched runs are unaffected.
335
+
336
+ An expired or legacy **signed** receipt can be renewed without rewriting your
337
+ script. Keep the saved JSON (including the old receipt) and your edited text file:
338
+
339
+ ```bash
340
+ exodus video start --script reviewed.txt --resume-script saved-stop-response.json \
341
+ --conceit ugc-template --style raw-iphone-ugc-template \
342
+ --stop-at-script --renew-script-approval --quote-preparation --json > renewal-quote.json
343
+ # Review the script-check allowance, then authorize that same input:
344
+ exodus video start --script reviewed.txt --resume-script saved-stop-response.json \
345
+ --conceit ugc-template --style raw-iphone-ugc-template \
346
+ --stop-at-script --renew-script-approval --authorize-preparation renewal-quote.json \
347
+ --json > refreshed-review.json
348
+ ```
349
+
350
+ This keeps the edited script, original approved source, product, context **and signed
351
+ receipt**. Before consent, the server verifies the old receipt's signature, workspace,
352
+ template, product and source, including v2's original signing domain. Reapproval
353
+ ignores only the old expiry/member binding and issues the reviewing member a new
354
+ receipt. An unreadable, missing or unverifiable receipt requires a fresh write;
355
+ changing products also requires writing a new script, not renewing the old approval.
356
+ Checking may still cost the quoted amount; it is not a new write or storyboard
357
+ authorization. `--stop-at-script` performs this guarded review for expired/v2
358
+ receipts; `--renew-script-approval` makes recovery explicit after a server rejection.
359
+ It cannot be used with `--rewrite-to-fit`, without `--resume-script --stop-at-script`,
360
+ or on a Show. Review the refreshed response before requesting a separate storyboard
361
+ quote using an API key owned by the new approving member.
362
+
310
363
  The resumed POST carries the script alongside the saved opaque `scriptApproval`,
311
- exact approved source, brief and product. The server checks its workspace,
312
- template and context binding. An approved description stays the original
313
- description, not the generated or edited script. Source modes are `verbatim` and
364
+ exact approved source, brief and product. The server checks its approving member,
365
+ 24-hour lifetime, workspace, template and context binding. An approved description
366
+ stays the original description, not the generated or edited script. Source modes are `verbatim` and
314
367
  `description`; `script` is not a
315
368
  wire mode. Explicit `--requested-seconds`, `--pictures-per-scene`, `--voice`,
316
369
  `--voice-path` and `--video-model` override their matching saved choices. The CLI
@@ -164,7 +164,12 @@ does offer, and nothing is spent.
164
164
  3. Write the script out byte for byte:
165
165
  `node -e 'process.stdout.write(require("./stop1.json").script)' > script.txt`.
166
166
  Show the member the source and `script.txt` side by side, and the cast:
167
- each name that speaks a line. Ask: go on, change a line, or stop.
167
+ each name that speaks a line. The stop file can also carry the app's notes
168
+ on the copy, such as a claim it could not check against the source or a
169
+ line that may not fit:
170
+ `node -e 'for (const n of require("./stop1.json").copyNotes ?? []) console.log(n.detail)'`.
171
+ Show each note next to the script, word for word. A note stops nothing;
172
+ the member decides. Ask: go on, change a line, or stop.
168
173
  - Go on: "The run starts" below.
169
174
  - Change a line: copy `script.txt` to `edited.txt` and make their change.
170
175
  An edited script is checked and approved again, at a price of its own.
@@ -178,7 +183,7 @@ does offer, and nothing is spent.
178
183
  ```
179
184
 
180
185
  From here `stop1b.json` is the stop file. Write its script over
181
- `script.txt` the same way and show it again.
186
+ `script.txt` the same way and show it again, with its copy notes.
182
187
  - Stop: nothing more is spent.
183
188
 
184
189
  ### The run starts
@@ -187,6 +192,15 @@ does offer, and nothing is spent.
187
192
  Use it with `script.txt` written out from it, unchanged. A different script,
188
193
  product, voice or reference is refused, and nothing starts.
189
194
 
195
+ The approval in a stop file lasts 24 hours, and only a key of the member who
196
+ approved it can use it. After that the storyboard quote is refused and nothing
197
+ is spent. Renew it with the two "Change a line" lines above, with
198
+ `<stop file>` in place of `stop1.json`, `script.txt` as the script and
199
+ `--renew-script-approval` added to both. That checks the
200
+ same script again at a price of its own (give the member the price, and run
201
+ the second line on their yes); it writes nothing new. Continue from the new
202
+ stop file.
203
+
190
204
  ```
191
205
  exodus video start --resume-script <stop file> --script script.txt \
192
206
  --conceit <key> --style <look> --quote-preparation --json > board-quote.json
@@ -242,7 +256,8 @@ speaks with which voice ("Reading the storyboard gate" has the detail). Show it
242
256
  with the run page link, then ask: approve, redo a picture, change a voice,
243
257
  move someone (Micro-drama template only), or stop.
244
258
 
245
- - Approve: `exodus video approve <runId>`. It buys the voices and the clips
259
+ - Approve: `exodus video approve <runId>`. It approves the storyboard and
260
+ buys the voices and the clips
246
261
  (with the pilot stop, the pilot first), the expensive part. The CLI prints
247
262
  no price for them at this stop: say so, and approve on their yes. A storyboard the app's check stopped is
248
263
  refused with the reason. Tell the member, and on their yes approve again
@@ -296,6 +311,23 @@ keep: offer the redo it prints, which names the scene.
296
311
  their yes. The note steers the motion,
297
312
  never the words.
298
313
 
314
+ ### The audition stop
315
+
316
+ A template run started from the dashboard can film a few planned scenes first
317
+ and hold the rest. A run started here never asks for one. `status` then names
318
+ the audition scenes and prints what to run next:
319
+
320
+ - `exodus video approve <runId> --audition <digest>`: show the member those
321
+ clips on the run page first. On their yes, run it exactly as printed. The
322
+ run then goes on and makes the clips it held.
323
+ - `exodus video approve <runId>` with "failed audition takes only": it pays
324
+ for another try of the audition takes that did not finish; the finished
325
+ ones are kept. The CLI prints no price for it: say so and wait for their
326
+ yes.
327
+ - "inputs changed" or "refused for safety or their pictures": nothing can
328
+ be approved. Offer to stop the run (`exodus workflow cancel <runId>`) and
329
+ start a new video.
330
+
299
331
  ### End: watch and approve
300
332
 
301
333
  At the final watch, follow the block `status` prints ("Where a run can
@@ -835,7 +867,10 @@ CLI words it the way the run page does. On their own brands they can:
835
867
  video says `"stage": "failed"` with the held scenes in `cutHolds`.
836
868
  - `video storyboard <runId>`: each scene's line and picture, while the
837
869
  storyboard waits for review.
838
- - `video approve <runId>`: approves the storyboard. Nothing else.
870
+ - `video approve <runId>`: approves the storyboard. At an audition stop,
871
+ `video approve <runId> --audition <digest>` accepts the audition clips, and
872
+ plain `video approve <runId>` pays for another try of the failed audition
873
+ takes ("The audition stop"). Nothing else.
839
874
  - `video voices <runId>`: who speaks, their current voice, and the voices on
840
875
  the tester's own ElevenLabs account. `--set <character>=<voiceId>` picks one,
841
876
  until the storyboard is approved.
@@ -973,6 +1008,14 @@ neither is refused, and nothing is spent. The template flags, as `exodus video
973
1008
  A different product still needs fresh writing and approval
974
1009
  without --resume-script.
975
1010
  Not for --show
1011
+ --renew-script-approval
1012
+ Optional. Every --resume-script --stop-at-script review
1013
+ already re-checks the --script edits against the saved
1014
+ source and issues a new 24-hour approval, also when the
1015
+ saved one expired; it never writes a fresh script. This
1016
+ flag sends nothing extra: it only refuses the line
1017
+ without --resume-script --stop-at-script, or with
1018
+ --rewrite-to-fit or --show
976
1019
  --input-options List your templates: Golden Six first, then more templates.
977
1020
  Add --conceit <template> for structures, capabilities,
978
1021
  identity locks, references and account voices.
@@ -984,6 +1027,7 @@ neither is refused, and nothing is spent. The template flags, as `exodus video
984
1027
 
985
1028
  The other template flags (`--input-mode`, `--structure`, `--reference`,
986
1029
  `--subject`, `--template-brief`, `--song-controls`, `--mechanism-plan`,
1030
+ `--source-record`, `--adaptation-plan`,
987
1031
  `--requested-seconds`, `--pictures-per-scene`, `--product`, `--elements`,
988
1032
  `--voices`) are in `exodus video --help`.
989
1033
 
@@ -0,0 +1,100 @@
1
+ import type { ActionPhaseAnchor } from "../../../../../video/lib/storyboardContract.js";
2
+
3
+ export const TEMPLATE_INTERNAL_PAUSE_SEC: number;
4
+ export const TEMPLATE_PAUSE_KEEP_AFTER_SEC: number;
5
+ export const TEMPLATE_PAUSE_KEEP_BEFORE_SEC: number;
6
+ export const TEMPLATE_SPEECH_LEAD_SEC: number;
7
+ export const TEMPLATE_SPEECH_TAIL_SEC: number;
8
+ export const DIALOGUE_BREATH_LEAD_SEC: number;
9
+ export const DIALOGUE_BREATH_TAIL_SEC: number;
10
+ export const AUTHORED_ACTION_LEAD_SEC: number;
11
+ export const AUTHORED_REACTION_TAIL_SEC: number;
12
+
13
+ export interface SpeechEditWord {
14
+ word?: string;
15
+ w?: string;
16
+ startSec?: number;
17
+ endSec?: number;
18
+ s?: number;
19
+ e?: number;
20
+ lineId?: string;
21
+ }
22
+
23
+ export interface SpeechEditLine {
24
+ lineId?: string;
25
+ text: string;
26
+ asksPause?: boolean;
27
+ cuesBeat?: boolean;
28
+ stageDirection?: string | readonly string[];
29
+ performanceDirection?: string | readonly string[];
30
+ action?: string | readonly string[];
31
+ }
32
+
33
+ export interface SpeechEditWindow {
34
+ startSec?: number;
35
+ endSec?: number;
36
+ s?: number;
37
+ e?: number;
38
+ }
39
+
40
+ /** What a trusted template cut keeps of one talking clip, on the clip's own clock. */
41
+ export interface TemplateSpeechEdit {
42
+ headSec: number;
43
+ tailSec: number;
44
+ cuts: Array<{ startSec: number; endSec: number }>;
45
+ }
46
+
47
+ /** Detection only. Callers apply their own lead/tail seconds. */
48
+ export interface AuthoredBeat {
49
+ timedLeadSec: number;
50
+ timedTailSec: number;
51
+ preLineAction: boolean;
52
+ postLineReaction: boolean;
53
+ }
54
+ export function parseAuthoredBeat(direction: string | readonly string[] | null | undefined): AuthoredBeat;
55
+
56
+ /** True only when both timestamps are finite and the token has no duration. */
57
+ export function isZeroDurationSpeech(word: SpeechEditWord): boolean;
58
+
59
+ /** Template join anchors. Incomplete times stay; proven zero-duration tokens do not. */
60
+ export function templateJoinAnchors(words: readonly SpeechEditWord[]): { firstSec?: number; lastSec?: number };
61
+ /** Structural projection of the canonical scene reservations; contains no dialogue. */
62
+ export interface SpeechEditOptions {
63
+ /** Advisory source-clock findings; never an action observation or quality rejection. */
64
+ notes?: string[];
65
+ sceneIndex?: number;
66
+ editingTreatment?: import("../../../../../video/lib/formatPayload.js").EditingTreatment;
67
+ durationSec?: number;
68
+ span?: { first: number; last: number };
69
+ protectedWindows?: readonly SpeechEditWindow[];
70
+ actionLeadSec?: number;
71
+ actionTailSec?: number;
72
+ lines?: readonly SpeechEditLine[];
73
+ direction?: string | readonly string[];
74
+ actionPhases?: readonly { id: string; required?: boolean; window?: { start: ActionPhaseAnchor; end: ActionPhaseAnchor } }[];
75
+ directorBeats?: readonly { id: string; timing: { start: ActionPhaseAnchor; end: ActionPhaseAnchor; minActionSec: number } }[];
76
+ fps?: number;
77
+ }
78
+
79
+ /** An authored reservation on the measured source clock, NOT an observed action receipt. */
80
+ export interface SpeechEditActionWindow {
81
+ id: string;
82
+ kind: "director-beat" | "action-phase";
83
+ startSec: number;
84
+ endSec: number;
85
+ }
86
+ /** Full-scene proof phases are excluded; director windows remain explicit edit reservations. */
87
+ export function templateActionWindows(words: readonly SpeechEditWord[], opts?: SpeechEditOptions): SpeechEditActionWindow[];
88
+
89
+
90
+
91
+ /**
92
+ * Jump-cut internal pauses over 0.8 s and trim to the first word − 0.10 s
93
+ * and the last word + 0.28 s. Measured director/phase windows protect acting;
94
+ * stage directions supply fallback handles on edges not covered by resolved windows.
95
+ * Null without measured words.
96
+ */
97
+ export function templateSpeechEdit(
98
+ words: readonly SpeechEditWord[],
99
+ opts?: SpeechEditOptions,
100
+ ): TemplateSpeechEdit | null;
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Template talking-clip edit from measured word times.
3
+ * Standalone so first-cut.mjs and scout scribe.ts share one policy.
4
+ * Door 1/3/4 never call this.
5
+ *
6
+ * A word-to-word silence strictly over 0.8 s is jump-cut, leaving 0.18 s
7
+ * after the earlier word and 0.12 s before the later one. The kept picture
8
+ * starts 0.10 s before the first word and ends 0.28 s after the last.
9
+ * An opening/closing action handle widens those edges. A protected window
10
+ * (reveal pause, resolved action hold) is never removed. A pause the script
11
+ * asks for — ellipsis, dash, a direction, or the laugh beat after a cued
12
+ * line — is not jump-cut when the lines align with the words.
13
+ *
14
+ * Words may be {word, startSec, endSec} or {w, s, e}. Windows may be
15
+ * {startSec, endSec} or {s, e}. Pass fps to land on whole frames: kept
16
+ * silence only grows. Null when there is no measured word to trim to.
17
+ */
18
+
19
+ export const TEMPLATE_INTERNAL_PAUSE_SEC = 0.8;
20
+ export const TEMPLATE_PAUSE_KEEP_AFTER_SEC = 0.18;
21
+ export const TEMPLATE_PAUSE_KEEP_BEFORE_SEC = 0.12;
22
+ export const TEMPLATE_SPEECH_LEAD_SEC = 0.1;
23
+ export const TEMPLATE_SPEECH_TAIL_SEC = 0.28;
24
+ export const DIALOGUE_BREATH_LEAD_SEC = 0.5;
25
+ export const DIALOGUE_BREATH_TAIL_SEC = 0.9;
26
+
27
+ const PAUSE_MARK = /…|\.{3,}|[—–]|-{2,}/g;
28
+ const WRITTEN_PAUSE = /…|\.{3}|[—–-]/;
29
+
30
+ const ms = (sec) => Math.round(sec * 1000) / 1000;
31
+ const spoken = (text) => String(text ?? "").toLowerCase().replace(/[^a-z0-9']+/g, "");
32
+ const wordText = (word) => word?.word ?? word?.w ?? "";
33
+ const wordStart = (word) => (Number.isFinite(word?.startSec) ? word.startSec : word?.s);
34
+ const wordEnd = (word) => (Number.isFinite(word?.endSec) ? word.endSec : word?.e);
35
+ const windowStart = (window) => (Number.isFinite(window?.startSec) ? window.startSec : window?.s);
36
+ const windowEnd = (window) => (Number.isFinite(window?.endSec) ? window.endSec : window?.e);
37
+
38
+ /** Heard-word pairs whose silence the script asked for. Empty when the lines do not align. */
39
+ function askedPairs(lines, words) {
40
+ if (!lines?.length) return new Set();
41
+ const pieces = [];
42
+ lines.forEach((line, li) => {
43
+ for (const piece of String(line?.text ?? "").replace(PAUSE_MARK, " $& ").trim().split(/\s+/).filter(Boolean)) {
44
+ pieces.push({ li, piece, spoken: spoken(piece) });
45
+ }
46
+ });
47
+ const heard = [];
48
+ words.forEach((word, i) => {
49
+ if (isZeroDurationSpeech(word)) return;
50
+ heard.push({ i, spoken: spoken(wordText(word)) });
51
+ });
52
+ let h = 0;
53
+ const at = [];
54
+ for (const piece of pieces) {
55
+ if (!piece.spoken) {
56
+ at.push(null);
57
+ continue;
58
+ }
59
+ while (h < heard.length && heard[h].spoken !== piece.spoken) h++;
60
+ if (h >= heard.length) return new Set();
61
+ at.push(heard[h].i);
62
+ h++;
63
+ }
64
+ const pairs = new Set();
65
+ for (let p = 0; p < pieces.length; p++) {
66
+ if (at[p] === null) continue;
67
+ let n = p + 1;
68
+ while (n < pieces.length && at[n] === null) n++;
69
+ if (n >= pieces.length) break;
70
+ const from = at[p];
71
+ const to = at[n];
72
+ const fromHeard = heard.findIndex((entry) => entry.i === from);
73
+ const toHeard = heard.findIndex((entry) => entry.i === to);
74
+ if (toHeard !== fromHeard + 1) continue;
75
+ const between = pieces.slice(p + 1, n).map((piece) => piece.piece).join(" ");
76
+ const fromLine = lines[pieces[p].li];
77
+ const toLine = lines[pieces[n].li];
78
+ if (
79
+ WRITTEN_PAUSE.test(between) ||
80
+ fromLine?.asksPause ||
81
+ toLine?.asksPause ||
82
+ (pieces[p].li !== pieces[n].li && fromLine?.cuesBeat)
83
+ ) {
84
+ pairs.add(`${from}:${to}`);
85
+ }
86
+ }
87
+ return pairs;
88
+ }
89
+
90
+ function subtractWindows(span, windows) {
91
+ let pieces = [span];
92
+ for (const window of windows) {
93
+ const start = windowStart(window);
94
+ const end = windowEnd(window);
95
+ if (!(end > start)) continue;
96
+ const next = [];
97
+ for (const piece of pieces) {
98
+ if (end <= piece.startSec || start >= piece.endSec) {
99
+ next.push(piece);
100
+ continue;
101
+ }
102
+ if (start > piece.startSec) next.push({ startSec: piece.startSec, endSec: ms(start) });
103
+ if (end < piece.endSec) next.push({ startSec: ms(end), endSec: piece.endSec });
104
+ }
105
+ pieces = next;
106
+ }
107
+ return pieces.filter((piece) => piece.endSec > piece.startSec + 1e-6);
108
+ }
109
+
110
+ function mergeSpans(spans) {
111
+ const merged = [];
112
+ for (const span of [...spans].sort((a, b) => a.startSec - b.startSec)) {
113
+ const prev = merged.at(-1);
114
+ if (prev && span.startSec <= prev.endSec) prev.endSec = Math.max(prev.endSec, span.endSec);
115
+ else merged.push({ ...span });
116
+ }
117
+ return merged;
118
+ }
119
+
120
+ /** Fallback lead for pre-line action prose not covered by a resolved edge window. */
121
+ export const AUTHORED_ACTION_LEAD_SEC = 1.2;
122
+ /** Fallback tail for reaction prose not covered by a resolved edge window. */
123
+ export const AUTHORED_REACTION_TAIL_SEC = 1.0;
124
+
125
+ const PRE_LINE_ACTION = /\b(?:cross(?:es)?|grabs?|sits?|taps?|installs?|leans?\s+in|hid(?:e|es|ing))\b|\bsets?\b(?:\s+\S+){0,6}\s+down\b|\btak(?:e|es|ing)\b(?:\s+\S+){0,6}\s+out\b/i;
126
+ const POST_LINE_REACTION = /\b(?:laugh(?:s|ing)?|nods?|smiles?|smiling|grins?|sighs?)\b/i;
127
+ const TIMED_BEAT = /(?:about\s+)?(\d+(?:\.\d+)?)\s*-?\s*(?:s|sec|secs|second|seconds)\b[^.;]{0,60}\b(?:silent\s+)?(?:beat|pause)\b|\b(?:silent\s+)?(?:beat|pause)\b[^.;]{0,60}(?:about\s+)?(\d+(?:\.\d+)?)\s*-?\s*(?:s|sec|secs|second|seconds)\b/i;
128
+
129
+ function directionText(value) {
130
+ if (Array.isArray(value)) return value.map(directionText).filter(Boolean).join(" ");
131
+ return typeof value === "string" ? value : "";
132
+ }
133
+
134
+ /**
135
+ * What a stage direction authors, with no added seconds. Planning and the
136
+ * trim each apply their own allowance, so the same text cannot be counted twice.
137
+ * A numbered beat/pause before the line (or with no "after") is a lead; "after" is a tail.
138
+ */
139
+ export function parseAuthoredBeat(direction) {
140
+ const text = directionText(direction);
141
+ let timedLeadSec = 0;
142
+ let timedTailSec = 0;
143
+ // A period inside 1.25 is not a clause break.
144
+ for (const clause of text.split(/;|(?<!\d)\.(?!\d)/)) {
145
+ const match = clause.match(TIMED_BEAT);
146
+ const seconds = Number(match?.[1] ?? match?.[2]);
147
+ if (!(seconds > 0)) continue;
148
+ if (/\bafter\b/i.test(clause)) timedTailSec = Math.max(timedTailSec, seconds);
149
+ else timedLeadSec = Math.max(timedLeadSec, seconds);
150
+ }
151
+ return {
152
+ timedLeadSec,
153
+ timedTailSec,
154
+ preLineAction: PRE_LINE_ACTION.test(text),
155
+ postLineReaction: POST_LINE_REACTION.test(text),
156
+ };
157
+ }
158
+
159
+ function authoredDirection(opts) {
160
+ return directionText([
161
+ opts.direction,
162
+ ...(opts.lines ?? []).flatMap((line) => [line?.stageDirection, line?.performanceDirection, line?.action]),
163
+ ]);
164
+ }
165
+
166
+ /** Explicit director windows replace fallback handles only on the speech edge they cover. */
167
+ function derivedBeatHandles(opts, windows, firstStart, lastEnd) {
168
+ const plan = parseAuthoredBeat(authoredDirection(opts));
169
+ const coversEdge = (window) => window.kind === "director-beat" || window.kind === "action-phase";
170
+ const leadCovered = windows.some((window) => coversEdge(window) &&
171
+ window.startSec < firstStart && window.endSec >= firstStart);
172
+ const tailCovered = windows.some((window) => coversEdge(window) &&
173
+ window.startSec <= lastEnd && window.endSec > lastEnd);
174
+ return {
175
+ lead: leadCovered ? 0 : Math.max(plan.timedLeadSec, plan.preLineAction ? AUTHORED_ACTION_LEAD_SEC : 0),
176
+ tail: tailCovered ? 0 : Math.max(plan.timedTailSec, plan.postLineReaction ? AUTHORED_REACTION_TAIL_SEC : 0),
177
+ };
178
+ }
179
+
180
+ /** Both timestamps finite and no duration. An incomplete time is not this. */
181
+ export function isZeroDurationSpeech(word) {
182
+ const start = wordStart(word);
183
+ const end = wordEnd(word);
184
+ return Number.isFinite(start) && Number.isFinite(end) && !(end > start);
185
+ }
186
+
187
+ /**
188
+ * Template join anchors. A proven zero-duration token is ignored. A word with
189
+ * only one timestamp stays, so the join does not borrow another word's clock.
190
+ */
191
+ export function templateJoinAnchors(words) {
192
+ const list = words ?? [];
193
+ const kept = list.filter((word) => !isZeroDurationSpeech(word));
194
+ const usable = kept.length ? kept : list;
195
+ const starts = usable.map(wordStart).filter((n) => Number.isFinite(n));
196
+ const ends = usable.map(wordEnd).filter((n) => Number.isFinite(n));
197
+ return {
198
+ firstSec: starts.length ? Math.min(...starts) : undefined,
199
+ lastSec: ends.length ? Math.max(...ends) : undefined,
200
+ };
201
+ }
202
+
203
+ /** A measured word with a real duration. */
204
+ function positiveSpan(word) {
205
+ if (isZeroDurationSpeech(word)) return null;
206
+ const start = wordStart(word);
207
+ const end = wordEnd(word);
208
+ if (!Number.isFinite(start) || !Number.isFinite(end) || !(end > start)) return null;
209
+ return { start, end };
210
+ }
211
+ /**
212
+ * Bind authored intent to the measured source clock, never to guessed speech
213
+ * duration. These windows reserve picture; they do not prove an action happened.
214
+ * Tagged words are authoritative. Legacy untagged words may bind only when the
215
+ * complete supplied lines match the complete transcript in order.
216
+ */
217
+ export function templateActionWindows(words, opts = {}) {
218
+ if (!opts.actionPhases?.length && !opts.directorBeats?.length) return [];
219
+ const list = (words ?? []).filter((word) => !isZeroDurationSpeech(word));
220
+ const byLine = new Map();
221
+ const add = (id, word) => {
222
+ if (typeof id !== "string" || !id) return;
223
+ if (!byLine.has(id)) byLine.set(id, []);
224
+ byLine.get(id).push(word);
225
+ };
226
+ if (list.some((word) => typeof word.lineId === "string" && word.lineId)) {
227
+ for (const word of list) add(word.lineId, word);
228
+ } else {
229
+ const expected = (opts.lines ?? []).flatMap((line) =>
230
+ String(line?.text ?? "").split(/\s+/).map(spoken).filter(Boolean)
231
+ .map((text) => ({ id: line.lineId, text })));
232
+ if (expected.length === list.length && expected.every((entry, i) => entry.text === spoken(wordText(list[i])))) {
233
+ expected.forEach((entry, i) => add(entry.id, list[i]));
234
+ }
235
+ }
236
+ const cap = Number.isFinite(opts.durationSec) && opts.durationSec > 0 ? opts.durationSec : undefined;
237
+ const anchor = (value) => {
238
+ if (value?.boundary === "scene-start") return 0;
239
+ if (value?.boundary === "scene-end") return cap;
240
+ if (value?.edge !== "start" && value?.edge !== "end") return undefined;
241
+ const line = byLine.get(value.lineId);
242
+ if (!line?.length) return undefined;
243
+ const times = line.map(value.edge === "start" ? wordStart : wordEnd);
244
+ // Missing word times are uncertainty, not permission to borrow another word.
245
+ if (!times.every(Number.isFinite)) return undefined;
246
+ return value.edge === "start" ? Math.min(...times) : Math.max(...times);
247
+ };
248
+ const windows = [];
249
+ const note = (code, entry, detail) => opts.notes?.push(
250
+ `${code}: scene ${opts.sceneIndex ?? "unknown"} ${entry.id}: ${detail}; reservation is not observed action`);
251
+ const bind = (entry, window, kind) => {
252
+ if (typeof entry?.id !== "string" || !entry.id) return;
253
+ const start = anchor(window?.start);
254
+ const end = anchor(window?.end);
255
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || !(end > start)) {
256
+ note("beat-reservation-unresolved", entry, "authored anchors have no usable source interval");
257
+ return;
258
+ }
259
+ const endSec = cap === undefined ? end : Math.min(cap, end);
260
+ if (!(endSec > start)) {
261
+ note("beat-reservation-unresolved", entry, "authored interval is outside available source");
262
+ return;
263
+ }
264
+ windows.push({ id: entry.id, kind, startSec: start, endSec });
265
+ if (endSec < end || (window.minActionSec > 0 && endSec - start + 1e-6 < window.minActionSec)) {
266
+ note("beat-reservation-short", entry, `${ms(endSec - start)}s available against ${window.minActionSec ?? ms(end - start)}s requested`);
267
+ }
268
+ };
269
+ for (const phase of opts.actionPhases ?? []) {
270
+ // Full-scene phases scope proof/observation, not an instruction to retain
271
+ // every source frame. Only a separately resolved edit window reserves time.
272
+ if (phase?.window?.start?.boundary === "scene-start" &&
273
+ phase?.window?.end?.boundary === "scene-end") continue;
274
+ if (phase?.required === true) bind(phase, phase.window, "action-phase");
275
+ }
276
+ for (const beat of opts.directorBeats ?? []) {
277
+ if (Number.isFinite(beat?.timing?.minActionSec) && beat.timing.minActionSec > 0) {
278
+ // A shorter measured interval cannot be repaired by inventing source time.
279
+ bind(beat, beat.timing, "director-beat");
280
+ } else if (typeof beat?.id === "string" && beat.id) {
281
+ note("beat-reservation-unresolved", beat, "no positive authored acting minimum");
282
+ }
283
+ }
284
+ return windows;
285
+ }
286
+
287
+
288
+
289
+
290
+ export function templateSpeechEdit(words, opts = {}) {
291
+ const list = words ?? [];
292
+ const fromIndex = opts.span?.first ?? 0;
293
+ const toIndex = opts.span ? opts.span.last : list.length - 1;
294
+ const kept = list.slice(fromIndex, toIndex + 1);
295
+ if (!kept.length) return null;
296
+ const first = kept[0];
297
+ const last = kept[kept.length - 1];
298
+ const firstStart = isZeroDurationSpeech(first)
299
+ ? kept.slice(1).map(positiveSpan).find(Boolean)?.start
300
+ : wordStart(first);
301
+ const lastEnd = isZeroDurationSpeech(last)
302
+ ? [...kept].reverse().slice(1).map(positiveSpan).find(Boolean)?.end
303
+ : wordEnd(last);
304
+ let latestEnd = -Infinity;
305
+ for (const word of kept) {
306
+ if (isZeroDurationSpeech(word)) continue;
307
+ const end = wordEnd(word);
308
+ if (Number.isFinite(end)) latestEnd = Math.max(latestEnd, end);
309
+ }
310
+ const fps = opts.fps;
311
+ const floorFrame = (sec) => (fps ? Math.floor(sec * fps + 1e-6) / fps : sec);
312
+ const ceilFrame = (sec) => (fps ? Math.ceil(sec * fps - 1e-6) / fps : sec);
313
+ const windows = [...(opts.protectedWindows ?? []), ...templateActionWindows(list, opts)];
314
+ const beat = derivedBeatHandles(opts, windows, firstStart, latestEnd);
315
+ // dialogueBreath has a single allowed value, so any value set asks for the longer breath.
316
+ const breath = Boolean(opts.editingTreatment?.dialogueBreath);
317
+ const lead = Math.max(breath ? DIALOGUE_BREATH_LEAD_SEC : TEMPLATE_SPEECH_LEAD_SEC, opts.actionLeadSec ?? 0, beat.lead);
318
+ const tail = Math.max(breath ? DIALOGUE_BREATH_TAIL_SEC : TEMPLATE_SPEECH_TAIL_SEC, opts.actionTailSec ?? 0, beat.tail);
319
+ const cap = opts.durationSec !== undefined && opts.durationSec > 0 ? opts.durationSec : Infinity;
320
+ // A missing time on the boundary word is uncertain: keep that side. When the last word has an end, the tail is the latest measured end plus 0.28 s, so an earlier word that outlasts it is not cut.
321
+ let headSec = Number.isFinite(firstStart) ? Math.max(0, floorFrame(firstStart - lead)) : 0;
322
+ let tailSec = Number.isFinite(lastEnd) && Number.isFinite(latestEnd) ? Math.min(cap, ceilFrame(latestEnd + tail)) : cap;
323
+ for (const window of windows) {
324
+ const start = windowStart(window);
325
+ const end = windowEnd(window);
326
+ if (!(end > start)) continue;
327
+ if (start < headSec) headSec = Math.max(0, start);
328
+ if (end > tailSec && start < cap) tailSec = Math.min(cap, end);
329
+ }
330
+ headSec = ms(Number.isFinite(firstStart) ? Math.min(headSec, firstStart) : headSec);
331
+ tailSec = ms(Number.isFinite(lastEnd) && Number.isFinite(latestEnd) ? Math.max(tailSec, Math.min(cap, latestEnd)) : tailSec);
332
+ if (!Number.isFinite(tailSec) || !(tailSec > headSec)) return null;
333
+
334
+ const asked = askedPairs(opts.lines, list);
335
+ const cuts = [];
336
+ if (opts.editingTreatment?.time === "continuous-dramatic") return { headSec, tailSec, cuts };
337
+ const nodes = [];
338
+ for (let i = fromIndex; i <= toIndex; i++) {
339
+ if (isZeroDurationSpeech(list[i])) continue;
340
+ const span = positiveSpan(list[i]);
341
+ nodes.push(span ? { index: i, barrier: false, ...span } : { index: i, barrier: true });
342
+ }
343
+ let runningEnd = -Infinity;
344
+ for (let p = 0; p + 1 < nodes.length; p++) {
345
+ const earlier = nodes[p];
346
+ const later = nodes[p + 1];
347
+ // An incomplete word blocks its adjoining pairs, not the protection of
348
+ // an earlier word whose measured end still overlaps later words.
349
+ if (!earlier.barrier) runningEnd = Math.max(runningEnd, earlier.end);
350
+ if (earlier.barrier || later.barrier) continue;
351
+ // Same millisecond clock as sentenceGapCuts, so 1.4→2.2 stays 0.8 s and is kept.
352
+ const gap = ms(later.start - runningEnd);
353
+ if (!(gap > TEMPLATE_INTERNAL_PAUSE_SEC)) continue;
354
+ if (asked.has(`${earlier.index}:${later.index}`)) continue;
355
+ const startSec = ms(ceilFrame(runningEnd + TEMPLATE_PAUSE_KEEP_AFTER_SEC));
356
+ const endSec = ms(floorFrame(later.start - TEMPLATE_PAUSE_KEEP_BEFORE_SEC));
357
+ if (!(endSec > startSec)) continue;
358
+ cuts.push(...subtractWindows({ startSec, endSec }, windows));
359
+ }
360
+ return { headSec, tailSec, cuts: mergeSpans(cuts) };
361
+ }
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { readFileSync, rmSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
5
+ import { LOWER_PANEL_TOP, READOUT_INSET_BOX } from "./first-cut-text.mjs";
5
6
 
6
7
  const literal = (lines) => {
7
8
  if (!Array.isArray(lines) || lines.some((line) => typeof line !== "string" || /[{}\\\r\n]/.test(line))) {
@@ -32,6 +33,20 @@ export function measuredTextAss(directives, { W = 1080, H = 1920, style = "" } =
32
33
  };
33
34
  for (const c of directives.captions ?? []) event(c.s, c.e, "Cap", Math.round(c.xShare * W), Math.round(c.yShare * H), c.fs, c.lines);
34
35
  for (const c of [...(directives.cards ?? []), directives.hook, directives.endCard].filter(Boolean)) {
36
+ // Only template-gated proof directives carry this field. The insert is an
37
+ // opaque editorial surface, not a claim to have tracked/generated a screen.
38
+ if (c.proof) {
39
+ const window = textFrameWindow(c.in, c.out);
40
+ if (c.proof.kind === "readout") {
41
+ // Readout proof is an editorial inset, never an opaque replacement for
42
+ // the filmed phone/action. Keep the ground bounded even for old boards.
43
+ const [left, top, right, bottom] = READOUT_INSET_BOX.map((v, i) => Math.round(v * (i % 2 ? H : W)));
44
+ events.push(`Dialogue: -1,${assTime(window.startCs)},${assTime(window.endCs)},Card,,0,0,0,,{\\an7\\pos(0,0)\\bord2\\3c&H665544&\\shad4\\1c&HFFFFFF&\\1a&H00&\\p1}m ${left} ${top} l ${right} ${top} ${right} ${bottom} ${left} ${bottom}{\\p0}`);
45
+ } else {
46
+ const top = c.proof.presentation === "lower-panel" ? Math.round(H * LOWER_PANEL_TOP) : 0;
47
+ events.push(`Dialogue: -1,${assTime(window.startCs)},${assTime(window.endCs)},Card,,0,0,0,,{\\an7\\pos(0,0)\\bord0\\shad0\\1c&HFFFFFF&\\1a&H00&\\p1}m 0 ${top} l ${W} ${top} ${W} ${H} 0 ${H}{\\p0}`);
48
+ }
49
+ }
35
50
  const [x, y] = anchor(c.renderBox, W, H);
36
51
  event(c.in, c.out, c.kind === "end" ? "End" : "Card", x, y, c.fs, c.lines);
37
52
  }