@aicopycoders/exodus 2026.11.500-beta.1 → 2026.11.700-beta.1

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
@@ -40,6 +40,22 @@ npx -y @aicopycoders/exodus@beta doctor
40
40
  `doctor` diagnoses local and dashboard-side issues in one shot — keys, workspace
41
41
  health, CLI currency — and tells you exactly what to fix.
42
42
 
43
+ ### Listen to and approve a run's Song
44
+
45
+ A run that sings its ad holds one Song master. Listen before motion starts:
46
+
47
+ - `video song <runId>` prints the Song's sha256s, its lyric, which lyric lines
48
+ were heard, and whether it can be approved. It never downloads the audio.
49
+ - `video song approve <runId> --master <masterSha256>` approves exactly the
50
+ master you listened to. If the run now holds a different one, nothing is
51
+ approved.
52
+ - `video song import <runId> --file song.mp3 --lyric @lyric.txt --rights "<who
53
+ owns it and consents>" [--from <s> --to <s>]` uses your own recording as the
54
+ Song. The rights statement is kept as written, and the server records you,
55
+ the signed-in member, as the person who confirmed it. Write the lyric one
56
+ line per scene. A line nobody can hear on the recording keeps the Song from
57
+ being approved.
58
+
43
59
  ## Where to go next
44
60
 
45
61
  - `npx -y @aicopycoders/exodus@beta --help` — the full command surface.
@@ -197,7 +197,13 @@ exodus video director <runId> on|off|follow the trial director for
197
197
  exodus video storyboard <runId> read the scene cards
198
198
  exodus video voices <runId> who speaks and with whose voice
199
199
  exodus video voices <runId> --set <character>=<voiceId> give a character a voice
200
+ exodus video quote <runId> a quoting format: the exact prepared requests and prices
201
+ before any clip; approve them with --request-quote <reviewSha256>
200
202
  exodus video approve <runId> keep going
203
+ exodus video song <runId> a song-first run: the Song master to listen to
204
+ exodus video song approve <runId> --master <sha256> approve the master you listened to
205
+ exodus video song import <runId> --file <audio> --lyric <text|@file> --rights "…" [--from <s> --to <s>]
206
+ use the member's own recording as the Song
201
207
  exodus video retry-frame <runId> --node <nodeId> --scene <n> redo one still at the pixel gate
202
208
  (a beta tester leaves --node off)
203
209
  exodus video broll <runId> B-roll run: the shots, and the script lines by id
@@ -212,6 +218,8 @@ exodus video retry-clip <runId> --scene <n> [--node <nodeId>] [--note "…"] [--
212
218
  exodus video revoice <runId> --all | --scene <n> redo only the voice; no new video
213
219
  … make the cut (your choice of tool)
214
220
  exodus video upload <runId> --file ./ad-<runId>/cut.mp4 attach it
221
+ exodus video review <runId> --file ./ad-<runId>/cut.mp4 --accept | --reject
222
+ a final-review format: YOUR review of that exact final cut
215
223
  exodus video approve <runId> make it the ad
216
224
  ```
217
225
 
@@ -0,0 +1,190 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+
6
+ const literal = (lines) => {
7
+ if (!Array.isArray(lines) || lines.some((line) => typeof line !== "string" || /[{}\\\r\n]/.test(line))) {
8
+ throw new Error("Text contains ASS controls or invalid literal lines");
9
+ }
10
+ return lines.join("\\N");
11
+ };
12
+ /** ASS centiseconds select exactly the SAME delivered frames as the heard
13
+ * interval. Never round a boundary onto an extra frame or lose its last one.
14
+ * Heard seconds themselves stay unchanged in the plan and evidence. */
15
+ export function textFrameWindow(start, end) {
16
+ const startFrame = Math.ceil(start * 24 - 1e-6);
17
+ const endFrame = Math.ceil(end * 24 - 1e-6);
18
+ return { startFrame, frames: endFrame - startFrame, startCs: Math.floor(startFrame * 100 / 24), endCs: Math.floor(endFrame * 100 / 24) };
19
+ }
20
+ const assTime = (cs) => `${Math.floor(cs / 360000)}:${String(Math.floor(cs / 6000) % 60).padStart(2, "0")}:${String(Math.floor(cs / 100) % 60).padStart(2, "0")}.${String(cs % 100).padStart(2, "0")}`;
21
+ const anchor = (box, W, H) => [Math.round((box[0] + box[2]) * W / 2), Math.round((box[1] + box[3]) * H / 2)];
22
+
23
+ /** Same literal serializer, styles and geometry for measurement and final burn. */
24
+ export function measuredTextAss(directives, { W = 1080, H = 1920, style = "" } = {}) {
25
+ const thick = /thick black outline/i.test(style);
26
+ const events = [];
27
+ const event = (s, e, name, x, y, fs, lines) => {
28
+ if (!(Number.isFinite(s) && Number.isFinite(e) && e > s && fs > 0)) throw new Error("Invalid text interval or font size");
29
+ const window = textFrameWindow(s, e);
30
+ if (window.frames <= 0) throw new Error("Text interval contains no delivered video frame");
31
+ events.push(`Dialogue: 0,${assTime(window.startCs)},${assTime(window.endCs)},${name},,0,0,0,,{\\q2\\pos(${x},${y})\\fs${fs}}${literal(lines)}`);
32
+ };
33
+ 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
+ for (const c of [...(directives.cards ?? []), directives.hook, directives.endCard].filter(Boolean)) {
35
+ const [x, y] = anchor(c.renderBox, W, H);
36
+ event(c.in, c.out, c.kind === "end" ? "End" : "Card", x, y, c.fs, c.lines);
37
+ }
38
+ return [
39
+ "[Script Info]", "ScriptType: v4.00+", `PlayResX: ${W}`, `PlayResY: ${H}`, "WrapStyle: 2", "ScaledBorderAndShadow: yes", "",
40
+ "[V4+ Styles]",
41
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
42
+ `Style: Cap,Helvetica,60,&H00FFFFFF,&H00FFFFFF,&H00000000,&H90000000,-1,0,0,0,100,100,0,0,1,${thick ? 7 : 1.5},${thick ? 4 : 2},5,0,0,0,1`,
43
+ "Style: Card,Helvetica,60,&H00141414,&H00141414,&H00FFFFFF,&H50000000,-1,0,0,0,100,100,0,0,3,18,4,5,0,0,0,1",
44
+ "Style: End,Helvetica,60,&H00FFFFFF,&H00FFFFFF,&H20101010,&H00000000,-1,0,0,0,100,100,2,0,3,40,0,5,0,0,0,1", "",
45
+ "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text", ...events, "",
46
+ ].join("\n");
47
+ }
48
+
49
+ /** Resolve an observed renderer face, never a fontconfig-only guess. Some
50
+ * providers report -1 instead of a collection index; the exact observed file
51
+ * and a UNIQUE PostScript name across ALL its physical faces still prove it. */
52
+ export function fontSelectionEvidence(stderr, { file, index, faces }) {
53
+ if (!faces.length || faces.some((face) => !Number.isSafeInteger(face.index) || face.index < 0 || typeof face.postscriptName !== "string" || !/^[^\s,|]+$/.test(face.postscriptName))) return null;
54
+ const selected = faces.filter((face) => face.index === index);
55
+ if (selected.length !== 1 || faces.filter((face) => face.postscriptName === selected[0].postscriptName).length !== 1) return null;
56
+ const lines = stderr.split("\n").filter((line) => line.includes("fontselect:"));
57
+ if (!lines.length) return null;
58
+ const evidence = [];
59
+ for (const line of lines) {
60
+ const observed = / -> (.*), (-?\d+), ([^,\r\n]+)\s*$/.exec(line);
61
+ if (!observed || observed[1] !== file || observed[3].trim() !== selected[0].postscriptName) return null;
62
+ const reportedIndex = Number(observed[2]);
63
+ if (reportedIndex !== index && reportedIndex !== -1) return null;
64
+ evidence.push({ reportedIndex, physicalIndex: index, postscriptName: selected[0].postscriptName });
65
+ }
66
+ return evidence;
67
+ }
68
+
69
+ /** Real fontconfig + libass raster measurements. No guessed glyph widths or fallback bands. */
70
+ export function createTextRenderer({ dir, W = 1080, H = 1920 }) {
71
+ const run = (bin, args, extra = {}) => spawnSync(bin, args, { cwd: dir, maxBuffer: W * H * 3 + (1 << 20), ...extra });
72
+ const version = run("ffmpeg", ["-version"]).stdout?.toString().split("\n")[0] ?? "";
73
+ const filters = run("ffmpeg", ["-hide_banner", "-filters"]).stdout?.toString() ?? "";
74
+ const libass = /^\s*\S+\s+subtitles\s/m.test(filters);
75
+ const fontQuery = ["-f", "%{family}|%{file}|%{style}|%{index}", "Helvetica:weight=bold"];
76
+ const face = run("fc-match", fontQuery);
77
+ let font = null;
78
+ let fontFile = null;
79
+ let fontIndex = null;
80
+ let charset = [];
81
+ let faces = [];
82
+ if (face.status === 0) {
83
+ const resolved = face.stdout.toString().trim();
84
+ const file = resolved.split("|")[1];
85
+ const index = resolved.split("|")[3];
86
+ try {
87
+ const hash = createHash("sha256").update(readFileSync(file)).digest("hex");
88
+ if (!/^\d+$/.test(index ?? "")) throw new Error("The resolved font has no measured face index");
89
+ const chars = run("fc-query", ["-i", index, "-f", "%{charset}", file]);
90
+ const allFaces = run("fc-query", ["-f", "%{index}|%{postscriptname}\n", file]);
91
+ if (allFaces.status === 0) faces = allFaces.stdout.toString().trim().split("\n").map((row) => {
92
+ const [faceIndex, postscriptName = ""] = row.trim().split("|");
93
+ return { index: Number(faceIndex), postscriptName };
94
+ });
95
+ if (chars.status === 0) {
96
+ charset = chars.stdout.toString().trim().split(/\s+/).map((entry) => {
97
+ const [a, b] = entry.split("-").map((x) => Number.parseInt(x, 16));
98
+ return [a, b ?? a];
99
+ }).filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b));
100
+ if (charset.length) font = { requested: "Helvetica", resolved: `${resolved}|sha256:${hash}` };
101
+ if (font) fontFile = file;
102
+ if (font) fontIndex = index;
103
+ }
104
+ } catch { /* Missing font file is missing measurement, not permission to substitute one. */ }
105
+ }
106
+ const cache = new Map();
107
+ const backgrounds = new Map();
108
+ let n = 0;
109
+ const measureText = (request) => {
110
+ const key = JSON.stringify(request);
111
+ if (cache.has(key)) return cache.get(key);
112
+ const measure = () => {
113
+ if (!version || !libass || !font || request.W !== W || request.H !== H) return null;
114
+ const missingGlyphs = [...new Set(Array.from(request.lines.join("")))].filter((char) => {
115
+ if (/\s/u.test(char)) return false;
116
+ const cp = char.codePointAt(0);
117
+ return !charset.some(([a, b]) => cp >= a && cp <= b);
118
+ });
119
+ if (missingGlyphs.length) return null;
120
+ const caption = request.kind === "caption";
121
+ const entry = { kind: request.kind, lines: request.lines, fs: request.fs, renderBox: request.box, in: 0, out: 1 };
122
+ const directives = caption
123
+ ? { captions: [{ ...entry, xShare: request.xShare, yShare: request.yShare, s: 0, e: 1 }] }
124
+ : { cards: [entry] };
125
+ const name = `.text-measure-${process.pid}-${++n}.ass`;
126
+ const file = path.join(dir, name);
127
+ const bounds = { x: W, y: H, right: -1, bottom: -1 };
128
+ const selections = [];
129
+ try {
130
+ // Decode the blank raster through the same filter/conversion as the
131
+ // text. Limited-range YUV white can become RGB 253, not nominal 255.
132
+ // Cache only its proven uniform RGB, never a guessed tolerance.
133
+ if (backgrounds.size < 2) {
134
+ writeFileSync(file, measuredTextAss({}, { W, H }));
135
+ for (const color of ["black", "white"]) {
136
+ const blank = run("ffmpeg", [
137
+ "-hide_banner", "-loglevel", "error", "-filter_threads", "1", "-f", "lavfi", "-i", `color=c=${color}:s=${W}x${H}:r=24:d=1`,
138
+ "-vf", `subtitles=filename=${name}`, "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1",
139
+ ]);
140
+ if (blank.status !== 0 || blank.stdout?.length !== W * H * 3) return null;
141
+ const rgb = [blank.stdout[0], blank.stdout[1], blank.stdout[2]];
142
+ for (let at = 0; at < blank.stdout.length; at++) {
143
+ if (blank.stdout[at] !== rgb[at % 3]) return null;
144
+ }
145
+ backgrounds.set(color, rgb);
146
+ }
147
+ }
148
+ writeFileSync(file, measuredTextAss(directives, { W, H, style: request.style }));
149
+ for (const color of ["black", "white"]) {
150
+ const res = run("ffmpeg", [
151
+ "-hide_banner", "-loglevel", "verbose", "-filter_threads", "1", "-f", "lavfi", "-i", `color=c=${color}:s=${W}x${H}:r=24:d=1`,
152
+ "-vf", `subtitles=filename=${name}`, "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1",
153
+ ]);
154
+ if (res.status !== 0 || res.stdout?.length !== W * H * 3 || /Glyph .* not found|failed to find.*font/iu.test(res.stderr?.toString() ?? "")) return null;
155
+ const observed = fontSelectionEvidence(res.stderr?.toString() ?? "", { file: fontFile, index: Number(fontIndex), faces });
156
+ if (!observed) return null;
157
+ selections.push(...observed);
158
+ const pixels = res.stdout;
159
+ const bg = backgrounds.get(color);
160
+ for (let y = 0, at = 0; y < H; y++) {
161
+ for (let x = 0; x < W; x++, at += 3) {
162
+ if (pixels[at] === bg[0] && pixels[at + 1] === bg[1] && pixels[at + 2] === bg[2]) continue;
163
+ bounds.x = Math.min(bounds.x, x); bounds.y = Math.min(bounds.y, y);
164
+ bounds.right = Math.max(bounds.right, x); bounds.bottom = Math.max(bounds.bottom, y);
165
+ }
166
+ }
167
+ }
168
+ } finally { rmSync(file, { force: true }); }
169
+ if (bounds.right < bounds.x || bounds.bottom < bounds.y) return null;
170
+ return {
171
+ renderer: { ffmpeg: version, libass: "present" },
172
+ font: { ...font, resolved: `${font.resolved}|libass:${JSON.stringify([...new Map(selections.map((entry) => [JSON.stringify(entry), entry])).values()])}` },
173
+ lines: [...request.lines],
174
+ inkRect: { x: bounds.x, y: bounds.y, w: bounds.right - bounds.x + 1, h: bounds.bottom - bounds.y + 1 }, coverage: { missingGlyphs: [] },
175
+ };
176
+ };
177
+ const value = measure();
178
+ cache.set(key, value);
179
+ return value;
180
+ };
181
+ const assertFont = () => {
182
+ if (!font || !fontFile) return false;
183
+ const current = run("fc-match", fontQuery);
184
+ if (current.status !== 0) return false;
185
+ try {
186
+ return `${current.stdout.toString().trim()}|sha256:${createHash("sha256").update(readFileSync(fontFile)).digest("hex")}` === font.resolved;
187
+ } catch { return false; }
188
+ };
189
+ return { measureText, libass, font, version, assertFont };
190
+ }
@@ -0,0 +1,120 @@
1
+ // B32–B34 consumer contract. No source mutation, policy table or width estimate.
2
+ export type Box = [number, number, number, number];
3
+ export interface TextHold { code: string; id: string; reason: string; required: true; inherited?: true }
4
+ export interface HeardWord { text: string; start: number; end: number; lineId?: string }
5
+ export interface Avoidance { box: Box; in?: number; out?: number }
6
+ export interface SourceIdentity { id: string; sha256: string }
7
+ export interface MeasurementRequest {
8
+ kind: string; lines: string[]; fs: number; W: number; H: number;
9
+ style?: string; xShare: number; yShare?: number; box: Box; maxWidthPx: number;
10
+ }
11
+ export interface RasterMeasurement {
12
+ /** Actual executable identity and actual subtitles-filter availability. */
13
+ renderer: { ffmpeg: string; libass: true | "present" };
14
+ /** Actual fontconfig resolution used by the measured burn, never a guess. */
15
+ font: { requested: string; resolved: string };
16
+ lines: string[];
17
+ /** Absolute frame pixels: union of actual ink, shadow, outline and opaque box. */
18
+ inkRect: { x: number; y: number; w: number; h: number };
19
+ coverage: { missingGlyphs: string[] };
20
+ }
21
+ /** Synchronous trusted consumer capability: render the exact request using the
22
+ * same ffmpeg executable, fontconfig resolution, ASS style/spacing/decorations
23
+ * and geometry as the final burn. Use two contrasting backgrounds so black ink
24
+ * and opaque boxes cannot disappear. Return null if not actually measured.
25
+ * Cache identity MUST include every request field, including style/position.
26
+ * This certifies geometry, NOT a human's reading speed or semantic approval. */
27
+ export type MeasureText = (request: MeasurementRequest) => RasterMeasurement | null;
28
+ export interface CaptionStyle { style?: string; wordsPerLine?: { median?: number }; place?: [number, number]; box?: Box }
29
+ export interface CaptionScreen {
30
+ /** Literal source words only. Renderer owns escaped ASS serialization. */
31
+ text: string; plain: string; lines: string[]; fs: number;
32
+ s: number; e: number; xShare: number; yShare: number; box: Box;
33
+ measurement: RasterMeasurement;
34
+ }
35
+ export interface TextItem {
36
+ id: string; kind?: string; text: string; required?: boolean; in?: number; out?: number;
37
+ box?: Box; placement?: string; provenance?: "post" | "physical-readout" | "authentic-lettering";
38
+ /** Authored question boundary is not clamped to this explanatory heard line. */
39
+ within?: { start: number; end: number };
40
+ /** Supplied authored readability requirement; never computed from string length.
41
+ * If this cannot be met in the authored interval, hold rather than retime. */
42
+ minReadableSec?: number;
43
+ opening?: boolean; cueLineId?: string;
44
+ /** Untrusted legacy metadata is not observation proof or fallback authority. */
45
+ evidence?: unknown; fallback?: unknown;
46
+ }
47
+ export interface TextCard {
48
+ n?: number; id: string; kind: string; label: string; lines: string[]; fs: number;
49
+ /** Measured actual ink rectangle. */
50
+ box: Box;
51
+ /** Authored geometry used for the raster and final burn. Do not recenter on ink. */
52
+ renderBox: Box;
53
+ in: number; out: number; moved: false; measurement: RasterMeasurement;
54
+ }
55
+ export interface Observation {
56
+ source: SourceIdentity; text: string; box: Box;
57
+ frame: { time: number; sha256: string };
58
+ /** Required at clock zero when this is an opening readout. */
59
+ opening?: { time: number; sha256: string; text: string; box: Box } | null;
60
+ value?: string; unit?: string; cueLineId?: string;
61
+ }
62
+ /** Trusted media observer capability, not user/item receipt deserialization.
63
+ * Must obtain frame/opening pixels from this exact hashed source file and
64
+ * report actual visible text/box. Planner separately validates source hashes,
65
+ * authored frame window, opening clock, heard cue, adjacent exact value+unit.
66
+ * No observer means hold; this helper never substitutes a deterministic insert. */
67
+ export type VerifyObservation = (request: { item: TextItem; source?: SourceIdentity }) => Observation | null;
68
+ export interface Readout {
69
+ id: string; provenance: string; status: "observed" | "hold"; claimsObserved: boolean;
70
+ observation: Observation | null;
71
+ }
72
+ export interface OutputPermission {
73
+ /** Exact selected format binding, any of ALL20; no name-based policy. */
74
+ formatId: string;
75
+ /** Selected Skeleton binding, stamped by the frozen format resolver. */
76
+ skeletonId?: string;
77
+ ending: { kind: string; mode: "native" | "asset"; assetRequired?: true } | null;
78
+ endCard: boolean; offer: boolean;
79
+ }
80
+ export interface Selection {
81
+ /** Supply only parseFormatPayload(run.formatPayload).outputPermission from
82
+ * the frozen selected run; item/user-authored objects are not authority. */
83
+ outputPermission?: OutputPermission;
84
+ ending?: { kind: string; mode: "native" | "asset"; asset?: string };
85
+ endCard?: Omit<TextItem, "id">;
86
+ offer?: Omit<TextItem, "id"> & { photo?: { real?: boolean; id?: string } };
87
+ }
88
+ export interface Permissions {
89
+ treatment: string; captions: boolean; requiredText: true; endCard: boolean;
90
+ ending: { kind: string | null; status: "unselected" | "native" | "supplied" | "hold" };
91
+ offer: { text: string; photo: string } | null; holds: TextHold[];
92
+ }
93
+ export interface CaptionOptions {
94
+ cap?: CaptionStyle | null; names?: string[]; lyricLines?: string[];
95
+ /** Actual cut boundaries in the same heard clock. */
96
+ cuts?: number[]; avoid?: Avoidance[]; W: number; H: number; totalSec?: number | null; measureText?: MeasureText;
97
+ }
98
+ export interface CardOptions {
99
+ avoid?: Avoidance[]; captionRects?: Avoidance[]; W: number; H: number;
100
+ totalSec?: number | null; endCardAllowed?: boolean; measureText?: MeasureText;
101
+ source?: SourceIdentity; words?: HeardWord[]; verifyObservation?: VerifyObservation;
102
+ }
103
+ export interface PlanTextInput extends CardOptions {
104
+ treatment: string; words?: HeardWord[];
105
+ captions?: { on?: boolean; cap?: CaptionStyle; lyricLines?: string[]; names?: string[] };
106
+ items?: TextItem[]; selection?: Selection; libass: boolean; cuts?: number[];
107
+ inheritedHolds?: Array<{ code: string; id: string; reason: string }>;
108
+ }
109
+ export interface TextPlan {
110
+ /** Required text not delivered if false. Caller must carry holds, not publish a pass. */
111
+ ok: boolean; holds: TextHold[]; notes: string[];
112
+ skipped: Array<{ id: string; code: string; reason: string }>;
113
+ permissions: Permissions; readouts: Readout[];
114
+ directives: { captions: CaptionScreen[]; cards: TextCard[]; hook: TextCard | null; endCard: TextCard | null };
115
+ }
116
+ export function planText(input: PlanTextInput): TextPlan;
117
+ export function planCaptionScreens(words: HeardWord[], options: CaptionOptions): { screens: CaptionScreen[]; holds: TextHold[]; notes: string[] };
118
+ export function planCards(items: TextItem[], options: CardOptions): { cards: TextCard[]; hook: TextCard | null; endCard: TextCard | null; readouts: Readout[]; holds: TextHold[]; skipped: TextPlan["skipped"]; notes: string[]; reservations: Avoidance[] };
119
+ export function outputPermissions(input: { treatment: string; captions?: boolean; selection?: Selection }): Permissions;
120
+ export const captionFontPx: (cap: CaptionStyle | null, H: number) => number;
@@ -0,0 +1,247 @@
1
+ // B32–B34: literal text and authored clocks only. This module performs no I/O.
2
+ // The consumer supplies its actual libass raster measurement and trusted media
3
+ // observation capabilities. Neither an item receipt nor a font-width estimate
4
+ // is evidence. Missing capabilities produce holds, never source mutations.
5
+ const hasText = (v) => typeof v === "string" && v.trim().length > 0;
6
+ const squash = (s) => String(s ?? "").replace(/\s+/gu, " ").trim();
7
+ const CONTROL = /[{}\\\u0000-\u001f\u007f]/u;
8
+ const validBox = (b) => Array.isArray(b) && b.length === 4 && b.every(Number.isFinite) && b[0] >= 0 && b[1] >= 0 && b[2] <= 1 && b[3] <= 1 && b[0] < b[2] && b[1] < b[3];
9
+ const overlapsTime = (a, b) => (a.in ?? -Infinity) < (b.out ?? Infinity) && (b.in ?? -Infinity) < (a.out ?? Infinity);
10
+ const meets = (a, b) => a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3];
11
+ const inside = (a, b) => a[0] >= b[0] && a[1] >= b[1] && a[2] <= b[2] && a[3] <= b[3];
12
+ const hold = (code, id, reason) => ({ code, id, reason, required: true });
13
+ const core = (s) => String(s).toLowerCase().replace(/[^\p{L}\p{N}%°]+/gu, "");
14
+ const UNIT = /^(mg|mcg|µg|ug|g|kg|lb|lbs|oz|ml|l|mmoll|iu|units?|%|percent|hours?|minutes?|seconds?|days?|weeks?|months?|years?|people|customers|dollars?|cm|mm|ft|mph|kcal|cal|times)$/u;
15
+ const NEGATOR = /^(not|no|never|none|nothing|nobody|nowhere|neither|nor|without|cannot)$/u;
16
+ const AUX = /^(do|does|did|is|are|was|were|will|would|can|could|should|must|has|have|had|may|might)$/u;
17
+ const FUNC = /^(a|an|the|of|to|in|on|at|for|with|and|or|but|my|your|our|his|her|their|its|from|by|as|into|than|that|if|so)$/u;
18
+ const endSentence = (s) => /[.!?…]["'”’)]*$/u.test(s) && !/^(dr|mr|mrs|ms|prof|st|mt)\.$/iu.test(s);
19
+ const FONT_SHARE = { card: .036, hook: .026, end: .045, offer: .036, "question-sticker": .036 };
20
+ const MAX_LINES = { card: 3, hook: 2, end: 3, offer: 4, "question-sticker": 3 };
21
+ export const captionFontPx = (cap, H) => Math.round(H * (/thick black outline/iu.test(cap?.style ?? "") ? .05 : .034));
22
+
23
+ // Numeric punctuation is serialized without inserted spaces; no character,
24
+ // digit, case, apostrophe, negation or name is rewritten or removed.
25
+ function literalWords(words) {
26
+ return words.map((w) => squash(w.text)).join(" ").replace(/(?<=\d)\s+([,.])\s+(?=\d)/gu, "$1").replace(/(?<=[\p{L}\p{N}])\s+([-–])\s+(?=[\p{L}\p{N}])/gu, "$1");
27
+ }
28
+
29
+ // No glyph widths or line-height guesses. A result is accepted only if the
30
+ // same renderer reports exact lines, resolved face, glyph coverage and ink.
31
+ function measured(request, measureText) {
32
+ if (typeof measureText !== "function") return null;
33
+ let m;
34
+ try { m = measureText(request); } catch { return null; }
35
+ const r = m?.inkRect;
36
+ if (!hasText(m?.renderer?.ffmpeg) || ![true, "present"].includes(m?.renderer?.libass) || m?.font?.requested !== "Helvetica" || !hasText(m?.font?.resolved) || !Array.isArray(m?.coverage?.missingGlyphs) || m.coverage.missingGlyphs.length || !Array.isArray(m.lines) || m.lines.length !== request.lines.length || m.lines.some((l, i) => l !== request.lines[i]) || !r || ![r.x, r.y, r.w, r.h].every(Number.isFinite) || r.w <= 0 || r.h <= 0) return null;
37
+ return { box: [r.x / request.W, r.y / request.H, (r.x + r.w) / request.W, (r.y + r.h) / request.H], measurement: m };
38
+ }
39
+
40
+ function fitText(text, { kind, fs: initialFs, box, xShare, yShare, style, W, H, maxLines, measureText }) {
41
+ const words = text.split(" ");
42
+ // Try authored geometry only. Balanced word-count wraps are candidates, not
43
+ // measurements; every accepted candidate is actually rasterized in full.
44
+ for (let fs = initialFs; fs >= Math.ceil(initialFs * .6); fs = Math.min(fs - 1, Math.floor(fs * .94))) {
45
+ for (let n = 1; n <= Math.min(maxLines, words.length); n++) {
46
+ const lines = [];
47
+ for (let i = 0; i < n; i++) lines.push(words.slice(Math.floor(i * words.length / n), Math.floor((i + 1) * words.length / n)).join(" "));
48
+ const request = { kind, lines, fs, W, H, style, xShare, yShare, box, maxWidthPx: (box[2] - box[0]) * W };
49
+ const m = measured(request, measureText);
50
+ if (!m) return { code: "measurement-missing" };
51
+ if (validBox(m.box) && inside(m.box, box)) return { lines, fs, ...m };
52
+ }
53
+ }
54
+ return { code: "text-overflow" };
55
+ }
56
+
57
+ export function planCaptionScreens(words, { cap = null, names = [], lyricLines = [], cuts = [], avoid = [], W, H, totalSec = null, measureText } = {}) {
58
+ const holds = [], notes = [];
59
+ const fail = (code, reason) => ({ screens: [], holds: [hold(code, "captions", reason)], notes });
60
+ if (!Array.isArray(words) || !words.length) return fail("word-times-missing", "captions require heard words on the cut clock");
61
+ for (let i = 0; i < words.length; i++) {
62
+ const w = words[i];
63
+ if (!hasText(w?.text) || !Number.isFinite(w.start) || !Number.isFinite(w.end) || w.start < 0 || w.end <= w.start || (i && w.start < words[i - 1].end) || (totalSec !== null && w.end > totalSec)) return fail("timing-invalid", `word ${i} has invalid heard timing`);
64
+ if (CONTROL.test(w.text)) return fail("literal-unrenderable", `word ${i} contains a renderer control character; source is not altered`);
65
+ if (cuts.some((t) => t > w.start && t < w.end)) return fail("word-crosses-cut", `word ${i} crosses a cut; no invented word clock`);
66
+ }
67
+ const glue = Array(words.length).fill(false), hard = Array(words.length).fill(false);
68
+ const raw = words.map((w) => squash(w.text)), c = raw.map(core);
69
+ for (let i = 0; i < words.length - 1; i++) {
70
+ const neg = (k) => NEGATOR.test(c[k]) || /n['’]t$/iu.test(raw[k]);
71
+ glue[i] = (/\d/u.test(raw[i]) && UNIT.test(c[i + 1])) || neg(i) || (AUX.test(c[i]) && neg(i + 1)) || FUNC.test(c[i]) || /^[$€£]$/u.test(raw[i]) || (/^[-–,.]$/u.test(raw[i + 1]) && /\d/u.test(raw[i])) || (/^[-–,.]$/u.test(raw[i]) && i > 0 && /\d/u.test(raw[i - 1])) || (/^\p{Lu}/u.test(raw[i]) && /^\p{Lu}/u.test(raw[i + 1]) && c[i] !== "i");
72
+ }
73
+ for (const name of names) {
74
+ const p = squash(name).split(" ").map(core);
75
+ for (let i = 0; i + p.length <= words.length; i++) if (p.every((t, k) => t === c[i + k])) for (let k = 0; k < p.length - 1; k++) glue[i + k] = true;
76
+ }
77
+ let from = 0;
78
+ for (const line of lyricLines) {
79
+ const p = squash(line).split(" ").map(core);
80
+ let at = -1;
81
+ for (let i = from; i + p.length <= words.length; i++) if (p.every((t, k) => t === c[i + k])) { at = i; break; }
82
+ if (at < 0) return fail("lyric-not-heard", `lyric phrase not found in heard words: ${line}`);
83
+ const end = at + p.length - 1;
84
+ if (at) hard[at - 1] = true;
85
+ hard[end] = true;
86
+ for (let i = at; i < end; i++) glue[i] = true;
87
+ from = end + 1;
88
+ }
89
+ // Source boundaries win BEFORE creating semantic units.
90
+ for (let i = 0; i < words.length - 1; i++) {
91
+ if (words[i + 1].start - words[i].end > .8 || cuts.some((t) => t >= words[i].end && t <= words[i + 1].start) || endSentence(raw[i])) hard[i] = true;
92
+ if (hard[i]) glue[i] = false;
93
+ }
94
+ const units = [];
95
+ from = 0;
96
+ for (let i = 0; i < words.length; i++) if (i === words.length - 1 || !glue[i]) { units.push({ a: from, b: i }); from = i + 1; }
97
+ const groups = [], per = Math.max(1, Math.round(cap?.wordsPerLine?.median ?? 3));
98
+ let cur = null;
99
+ for (const u of units) {
100
+ if (cur && (hard[cur.b] || cur.b - cur.a + 1 >= per || u.b - cur.a + 1 > per + 3)) { groups.push(cur); cur = null; }
101
+ cur = cur ? { a: cur.a, b: u.b } : u;
102
+ }
103
+ if (cur) groups.push(cur);
104
+ const box = cap?.box;
105
+ if (box === undefined) return fail("geometry-missing", "captions require explicit authored box geometry");
106
+ if (!validBox(box)) return fail("geometry-invalid", "caption box geometry is invalid");
107
+ if (cap.place !== undefined && (!Array.isArray(cap.place) || cap.place.length !== 2 || !cap.place.every((y) => Number.isFinite(y) && y >= box[1] && y <= box[3]) || cap.place[0] > cap.place[1])) return fail("geometry-invalid", "explicit caption placement is outside its authored box");
108
+ const xShare = (box[0] + box[2]) / 2;
109
+ const yShare = cap.place === undefined ? (box[1] + box[3]) / 2 : (cap.place[0] + cap.place[1]) / 2;
110
+ const screens = [];
111
+ for (const [i, g] of groups.entries()) {
112
+ const plain = literalWords(words.slice(g.a, g.b + 1));
113
+ const m = fitText(plain, { kind: "caption", fs: captionFontPx(cap, H), box, xShare, yShare, style: cap?.style, W, H, maxLines: 2, measureText });
114
+ if (m.code) { holds.push(hold(m.code, `caption ${i + 1}`, "no trusted raster measurement fits the authored caption geometry")); continue; }
115
+ const s = words[g.a].start, e = words[g.b].end;
116
+ if (avoid.some((a) => validBox(a.box) && overlapsTime({ in: s, out: e }, a) && meets(m.box, a.box))) { holds.push(hold("caption-geometry", `caption ${i + 1}`, "measured caption intersects reserved pixels; no invented relocation")); continue; }
117
+ screens.push({ text: plain, plain, lines: m.lines, fs: m.fs, s, e, xShare, yShare, box: m.box, measurement: m.measurement });
118
+ }
119
+ return { screens: holds.length ? [] : screens, holds, notes };
120
+ }
121
+
122
+ // Only the selected frozen format/Skeleton contract grants ending permission.
123
+ // The format identifier is a binding, not a name allowlist. Any of ALL20 uses
124
+ // the same explicit permission interface; nothing is selected automatically.
125
+ export function outputPermissions({ treatment, captions = false, selection = {} }) {
126
+ const holds = [];
127
+ const p = selection.outputPermission;
128
+ const selected = !!(selection.ending || selection.endCard || selection.offer);
129
+ const bound = hasText(p?.formatId) && p.formatId === treatment;
130
+ if (selected && !bound) holds.push(hold("output-permission-missing", "permissions", "selected output requires its frozen format/Skeleton permission contract"));
131
+ let ending = { kind: null, status: "unselected" };
132
+ if (selection.ending) {
133
+ const e = selection.ending;
134
+ ending = { kind: e.kind, status: "hold" };
135
+ if (!bound || e.kind !== p?.ending?.kind || e.mode !== p?.ending?.mode || !["native", "asset"].includes(e.mode)) holds.push(hold("ending-not-permitted", "ending", "ending does not match the explicitly selected output permission"));
136
+ else if ((e.mode === "asset" || p.ending.assetRequired === true) && !hasText(e.asset)) holds.push(hold("ending-asset-missing", "ending", "selected ending requires its supplied asset"));
137
+ else ending.status = e.mode === "native" ? "native" : "supplied";
138
+ }
139
+ let endCard = false, offer = null;
140
+ if (selection.endCard) {
141
+ if (!bound || p.endCard !== true) holds.push(hold("end-card-not-permitted", "end-card", "selected format/Skeleton contract does not permit this end card"));
142
+ else if (!hasText(selection.endCard.text)) holds.push(hold("text-missing", "end-card", "selected card has no literal text"));
143
+ else endCard = true;
144
+ }
145
+ if (selection.offer) {
146
+ const o = selection.offer;
147
+ if (!bound || p.offer !== true) holds.push(hold("offer-not-permitted", "offer", "selected format/Skeleton contract does not permit this offer"));
148
+ else if (!hasText(o.text)) holds.push(hold("text-missing", "offer", "selected offer has no literal text"));
149
+ else if (o.photo?.real !== true || !hasText(o.photo?.id)) holds.push(hold("offer-needs-real-photo", "offer", "selected offer requires a real product photo"));
150
+ else offer = { text: squash(o.text), photo: o.photo.id };
151
+ }
152
+ return { treatment, captions: captions === true, requiredText: true, endCard, ending, offer, holds };
153
+ }
154
+
155
+ function observe(item, { source, words = [], verifyObservation }) {
156
+ // verifyObservation is a capability owned by the actual media consumer. Item
157
+ // evidence/receipt strings are deliberately NEVER passed off as trusted proof.
158
+ if (typeof verifyObservation !== "function") return null;
159
+ let o;
160
+ try { o = verifyObservation({ item, source }); } catch { return null; }
161
+ const hash = (s) => typeof s === "string" && /^[a-f\d]{64}$/iu.test(s);
162
+ if (!hasText(source?.id) || !hash(source?.sha256) || o?.source?.id !== source.id || o?.source?.sha256 !== source.sha256 || !hash(o?.frame?.sha256) || !Number.isFinite(o?.frame?.time) || o.frame.time < item.in || o.frame.time >= item.out || squash(o.text) !== squash(item.text) || !validBox(o.box) || !inside(o.box, item.box) || !inside(item.box, o.box)) return null;
163
+ if (item.opening && (!hash(o?.opening?.sha256) || o.opening.time !== 0 || item.in !== 0 || squash(o.opening.text) !== squash(item.text) || !validBox(o.opening.box) || !inside(o.opening.box, item.box) || !inside(item.box, o.opening.box))) return null;
164
+ if (item.provenance === "physical-readout") {
165
+ const cue = words.filter((w) => w.lineId === item.cueLineId);
166
+ if (!hasText(item.cueLineId) || o.cueLineId !== item.cueLineId || !cue.length || cue.some((w) => !Number.isFinite(w.start) || !Number.isFinite(w.end)) || !cue.some((w) => w.start < item.out && w.end > item.in) || !hasText(o.value) || !hasText(o.unit)) return null;
167
+ const pair = `${o.value.trim()} ${o.unit.trim()}`;
168
+ // Token adjacency and equality, not substring checks: 1/g != 10/mg.
169
+ const adjacent = (s) => {
170
+ const tokens = squash(s).split(" ");
171
+ const needle = pair.split(" ");
172
+ return tokens.some((_, i) => needle.every((t, k) => tokens[i + k] === t));
173
+ };
174
+ if (!adjacent(item.text) || !adjacent(literalWords(cue))) return null;
175
+ }
176
+ return o;
177
+ }
178
+
179
+ export function planCards(items, { avoid = [], captionRects = [], W, H, totalSec = null, endCardAllowed = false, measureText, source, words, verifyObservation } = {}) {
180
+ const holds = [], skipped = [], readouts = [], notes = [], reservations = [], cards = [];
181
+ const placed = [...captionRects];
182
+ const fail = (item, code, reason) => item.required === true || ["physical-readout", "authentic-lettering"].includes(item.provenance) ? holds.push(hold(code, item.id, reason)) : skipped.push({ id: item.id, code, reason });
183
+ const valid = [];
184
+ for (const item of items) {
185
+ if (!hasText(item.text)) { fail(item, "text-missing", "no approved literal text"); continue; }
186
+ if (CONTROL.test(item.text)) { fail(item, "literal-unrenderable", "renderer control characters are held, never stripped"); continue; }
187
+ if (!Number.isFinite(item.in) || !Number.isFinite(item.out) || item.out <= item.in) { fail(item, "timing-missing", "explicit authored in/out are required"); continue; }
188
+ if (item.in < 0 || (totalSec !== null && item.out > totalSec)) { fail(item, "timing-out-of-range", "authored interval lies outside the cut"); continue; }
189
+ if (item.box === undefined) { fail(item, "geometry-missing", "text requires explicit authored rectangle geometry"); continue; }
190
+ const box = item.box;
191
+ if (!validBox(box)) { fail(item, "geometry-invalid", "invalid authored box"); continue; }
192
+ const normalized = { ...item, box };
193
+ if (["physical-readout", "authentic-lettering"].includes(item.provenance)) {
194
+ // Reserve before all post graphics, even if this proof is missing/held.
195
+ reservations.push({ box, in: item.in, out: item.out });
196
+ const o = observe(normalized, { source, words, verifyObservation });
197
+ readouts.push({ id: item.id, provenance: item.provenance, status: o ? "observed" : "hold", claimsObserved: !!o, observation: o });
198
+ if (!o) fail(item, item.provenance === "physical-readout" ? "readout-unobserved" : "lettering-unobserved", "no trusted same-file frame/cue/opening observation with exact literal tokens");
199
+ continue;
200
+ }
201
+ if (item.provenance && item.provenance !== "post") { fail(item, "provenance-unknown", "unknown text provenance"); continue; }
202
+ valid.push(normalized);
203
+ }
204
+ for (const item of valid.sort((a, b) => Number(b.required === true) - Number(a.required === true))) {
205
+ const kind = Object.hasOwn(FONT_SHARE, item.kind) ? item.kind : "card";
206
+ if (kind === "end" && !endCardAllowed) { fail(item, "end-card-not-selected", "no explicit selected end-card permission"); continue; }
207
+ if (item.minReadableSec !== undefined && (!Number.isFinite(item.minReadableSec) || item.minReadableSec <= 0 || item.out - item.in < item.minReadableSec)) { fail(item, "text-timing", "authored window fails its supplied minimum readable duration; not retimed"); continue; }
208
+ if (["hook", "end"].includes(kind) && cards.some((c) => c.kind === kind)) { fail(item, "text-slot-conflict", "multiple authored items target a singleton renderer slot; none is silently dropped"); continue; }
209
+ const text = squash(item.text);
210
+ const m = fitText(text, { kind, fs: Math.round(H * FONT_SHARE[kind]), box: item.box, xShare: (item.box[0] + item.box[2]) / 2, yShare: (item.box[1] + item.box[3]) / 2, W, H, maxLines: MAX_LINES[kind], measureText });
211
+ if (m.code) { fail(item, m.code, "no trusted raster measurement fits the authored box"); continue; }
212
+ if ([...avoid, ...reservations, ...placed].some((a) => validBox(a.box) && overlapsTime(item, a) && meets(m.box, a.box))) { fail(item, "geometry-blocked", "measured text intersects reserved pixels; no invented relocation"); continue; }
213
+ const card = { id: item.id, kind, label: text, lines: m.lines, fs: m.fs, box: m.box, renderBox: item.box, in: item.in, out: item.out, moved: false, measurement: m.measurement };
214
+ placed.push(card); cards.push(card);
215
+ }
216
+ return { cards: cards.filter((c) => !["hook", "end"].includes(c.kind)).map((c, i) => ({ n: i + 1, ...c })), hook: cards.find((c) => c.kind === "hook") ?? null, endCard: cards.find((c) => c.kind === "end") ?? null, readouts, holds, skipped, notes, reservations };
217
+ }
218
+
219
+ export function planText({ treatment, words = [], captions = {}, items = [], avoid = [], selection = {}, libass = false, W, H, totalSec = null, inheritedHolds = [], measureText, source, verifyObservation, cuts = [] }) {
220
+ const holds = inheritedHolds.map((h) => ({ ...h, required: true, inherited: true }));
221
+ const permissions = outputPermissions({ treatment, captions: captions.on === true, selection });
222
+ holds.push(...permissions.holds);
223
+ const directives = { captions: [], cards: [], hook: null, endCard: null };
224
+ const result = { ok: false, holds, notes: [], skipped: [], permissions, readouts: [], directives };
225
+ if (!(Number.isInteger(W) && W > 0 && Number.isInteger(H) && H > 0)) { holds.push(hold("geometry-missing", "frame", "known frame dimensions are required")); return result; }
226
+ const all = [];
227
+ for (const item of items) {
228
+ if (["end", "offer"].includes(item.kind)) {
229
+ const reason = "ending/offer cards must come from the explicit frozen selection, not a global item";
230
+ if (item.required === true) holds.push(hold("output-not-selected", item.id, reason));
231
+ else result.skipped.push({ id: item.id, code: "output-not-selected", reason });
232
+ } else all.push(item);
233
+ }
234
+ if (permissions.endCard) all.push({ ...selection.endCard, id: "end-card", kind: "end", required: true });
235
+ if (permissions.offer) all.push({ ...selection.offer, id: "offer", kind: "offer", required: true });
236
+ const cp = planCards(all, { avoid, W, H, totalSec, endCardAllowed: permissions.endCard, measureText, source, words, verifyObservation });
237
+ holds.push(...cp.holds); result.skipped.push(...cp.skipped); result.readouts = cp.readouts;
238
+ directives.cards = cp.cards; directives.hook = cp.hook; directives.endCard = cp.endCard;
239
+ if (captions.on === true) {
240
+ const cardAvoid = [...cp.cards, ...(cp.hook ? [cp.hook] : []), ...(cp.endCard ? [cp.endCard] : []), ...cp.reservations];
241
+ const p = planCaptionScreens(words, { cap: captions.cap, names: captions.names, lyricLines: captions.lyricLines, cuts, avoid: [...avoid, ...cardAvoid], W, H, totalSec, measureText });
242
+ holds.push(...p.holds); directives.captions = p.screens;
243
+ }
244
+ if (!libass && (captions.on === true || all.some((i) => !["physical-readout", "authentic-lettering"].includes(i.provenance)))) holds.push(hold("libass-missing", "burn", "actual subtitles filter is unavailable; text is not delivered"));
245
+ result.ok = holds.length === 0;
246
+ return result;
247
+ }