commit d301776055748f7c2152800940811ab11adb285d
parent daa62081e9044b283bd1b2e8a626572391638e30
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 22:31:49 -0500
Merge lane/analysis-ending: a report video can end on its data -- an analysis item draws a named run of the ledger's stated weights with a shaded band, a pace table whose pounds and days are computed from ledger rows, a status row and one reading line, in the deck's faces, calmly (the line draws, the rows land), silent for up to 8 s or with a clip of the cut heard under it and cited; a bound is drawn as a bound and said in words, a typed number without a row is warned, a row that is not his or not in the ledger is refused, sound from words cut out of the clip is refused, and a page that overflows is refused by the build's measure; umtool timeline add-analysis / set-analysis set it on the draft or a take, Play draws it, and a cut without one builds as before
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
33 files changed, 2285 insertions(+), 48 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **umtool: a report video can end on an analysis item, built from the ledger.** A new timeline entry, `{type: "analysis"}`, draws a full-frame ending on the deck's fonts and colours. It has a chart of a named run of his weights with a shaded band and marks, a pace table, status rows and one reading line. The line draws in and the rows land; there is no slam, hit or camera move. Every figure comes from a ledger row. A loss ("down 31.5") is placed against the run's start, the same weight a loss goal's base uses. A pace row's pounds and days are computed, never typed. A bound ("under 300") is drawn as a hollow point, and a pace row ending on one says it in words that stay true, "MORE THAN 10.5 lb lost" or "AT MOST 8.5 lb lost". A number typed into the words is a lint warning. The page is measured before it is encoded, and an item that overflows the frame is refused. With `audio`, a clip's sound plays under the item and its citation and QR code are shown, but not its picture. Without audio the item is silent for at most 8 seconds. `umtool lint` names the row behind every refusal. `umtool timeline <p> [--take <t>] add-analysis | set-analysis` writes one into the draft or a take, with an undo point, and `--dry-run` prints every figure with its row. Play the cut draws the item as the build does, but silently. A cut without an analysis item builds exactly as before.
- **umtool: a build and a take refuse a picked read that says an anonymous author's handle or name.** `umtool lint` reported it, but the lint a build enforces (and so every take's render) did not, so a recorded "@realguy is lying" rendered with the card anonymised and the audio saying the handle. The enforced lint now carries the same error in the same words; `--no-lint` is still the only override, and a video with no anonymous character lints exactly as before. Also: a video with anonymous characters whose `video.manifest.json` is missing or unreadable is refused rather than read with an empty set; a read collapses a status link to an anonymous author's post; a `--post-take` part takes its words from what the source take said; and the words sent to a model lose an anonymous author's display name, bare handle, `/i/web/status/` links and percent-encoded handles too.
- **umtool: anonymity covers the whole project, every link, the podcast and the previews; old reads keep their speed.** Re-checking the anonymous characters found several gaps. An item that named one in another variant, or one dropped by a ruling, `--only`, a window or a take, left the author in clear. The deck's corner QR on an anonymous author's post item still led to the real post. Links were rewritten with the status id kept. The podcast's show notes and the chrome preview, still and onscreen routes had no pass at all. Now:
- The set is built from the whole project manifest (and a take's), and the build, the chrome composer, the podcast, Play, Present and the previews all take it from one function.
diff --git a/umtool/app/api/report/chrome/teasers/route.ts b/umtool/app/api/report/chrome/teasers/route.ts
@@ -1,5 +1,6 @@
import { composeTeaserPreviews } from "@/lib/report/onscreen.mjs";
-import { resolveReport, teaserPreviewSrc } from "@/lib/report/serve.mjs";
+import { analysisPreviewSrc, resolveReport, teaserPreviewSrc } from "@/lib/report/serve.mjs";
+import { analysisSeconds } from "umtool-report-to-video/analysis-plan";
import { selectVariant } from "umtool-report-to-video/build-video";
import { teaserSeconds, transitionOf } from "umtool-report-to-video/deck";
import { cachedTakeManifest, takePlayDir, writePlayManifest } from "@/lib/report/takeManifest.mjs";
@@ -43,7 +44,8 @@ export async function POST(request: Request) {
}
const selected = selectVariant(manifest, r.variant);
const render = (selected.render ?? {}) as Record<string, unknown>;
- const timeline = ((selected.timeline ?? []) as Record<string, unknown>[]).filter((e) => e && e.type === "teaser");
+ // An analysis item (analysis-plan.mjs) is a full-frame page as a teaser is: composed and served the same way.
+ const timeline = ((selected.timeline ?? []) as Record<string, unknown>[]).filter((e) => e && (e.type === "teaser" || e.type === "analysis"));
const composed = await composeTeaserPreviews(target, r.variant, timeline);
const D = transitionOf(render);
const fps = typeof render.fps === "number" ? render.fps : 30;
@@ -55,7 +57,9 @@ export async function POST(request: Request) {
teasers: composed.map((c) => {
const e = timeline.find((x) => x.id === c.id)!;
return c.ok
- ? { id: c.id, seconds: teaserSeconds(e, D, fps), width, height, src: `${teaserPreviewSrc(r.project.id, r.variant, c.id, take)}?v=${stamp}` }
+ ? e.type === "analysis"
+ ? { id: c.id, seconds: analysisSeconds(e), width, height, src: `${analysisPreviewSrc(r.project.id, r.variant, c.id, take)}?v=${stamp}` }
+ : { id: c.id, seconds: teaserSeconds(e, D, fps), width, height, src: `${teaserPreviewSrc(r.project.id, r.variant, c.id, take)}?v=${stamp}` }
: { id: c.id, error: c.error ?? "did not compose" };
}),
},
diff --git a/umtool/components/projects/review/playCore.tsx b/umtool/components/projects/review/playCore.tsx
@@ -164,7 +164,8 @@ export function usePlayCore(view: PlayViewData, { showRejected = false }: { show
// THE TEASERS (lane leaflit-labels): each text card's own page, composed for preview (POST
// /api/report/chrome/teasers) and laid full frame while it is on screen -- the build's card, not a placeholder.
// Composed again whenever the manifest moved (its token), with or without a deck.
- const teaserKey = useMemo(() => view.entries.filter((e) => e.type === "teaser").map((e) => e.id).join("\n"), [view.entries]);
+ // An analysis item's page too (analysis-plan.mjs): full frame, silent in Play.
+ const teaserKey = useMemo(() => view.entries.filter((e) => e.type === "teaser" || e.type === "analysis").map((e) => e.id).join("\n"), [view.entries]);
// THE INTRO (lane intro-play): its page composed for preview (POST /api/report/chrome/intro), again when the manifest moved.
const introPage = useIntroPage(project, take, view.entries.some((e) => e.type === "intro"), view.token);
const [teaserPages, setTeaserPages] = useState<Record<string, TeaserPage | { id: string; error: string }>>({});
@@ -279,7 +280,7 @@ export function usePlayCore(view: PlayViewData, { showRejected = false }: { show
const vstage = hasVideoEntries ? videoStageAt(plan, entryOf, t) : null;
const videoNow = vstage?.video ? { ...vstage, video: vstage.video } : null;
// A teaser plays its own page (TeaserCardPlayer), once composed; until then -- or if it did not compose -- a placeholder.
- const teaserPage = item && entry?.type === "teaser" ? teaserPages[item.id] : undefined;
+ const teaserPage = item && (entry?.type === "teaser" || entry?.type === "analysis") ? teaserPages[item.id] : undefined;
const teaserNow = item && teaserPage && "src" in teaserPage ? { item, page: teaserPage } : null;
// THE INTRO (lane intro-play): the build's own page and its sound (IntroCardPlayer), once composed; until then -- or if
// it did not compose -- a placeholder that says so.
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -117,6 +117,7 @@ Inbox cannot disagree about what is wrong with one.
| `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) |
| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) |
| `timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\|cover] [--bass dB] [--gain dB] [--enter cut\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-video <id> <key>=<value>…` | **a video entry** ([report-video.md](report-video.md#a-video-entry)): a file of the project (`src`, relative; probed, its `fileSeconds` written) played FULL FRAME with its own sound, nothing drawn over it, at the end unless `--after` (`-`: the start), into the cut or the take's timeline only (`--take`, an undo point of the take's); `set-video` sets `from= to= fit= audio.bass= audio.gain= enter=cut\|<out>,<in> enter.out= enter.in= holdLast= deck=hidden\|shown title= note= src=` (`key=` clears). `--dry-run`: the entry and its place, nothing written. `--json`: `{ok, op, take?, inserted\|updated {id, at, entry}, revision?}`. **Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage** |
+| `timeline <project> [--take <t>] add-analysis <json\|@file> [--id ID] [--after <id>\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-analysis <id> <json\|@file> [--dry-run] [--json]` | **an analysis item** ([report-video.md](report-video.md#the-analysis-item)): an ending drawn from the LEDGER, full frame -- a chart of a named run of his weights (`series`: `{rows}` or `{from, to}`; a delta against the run's start), a `band`, `marks`, a `pace` table (pounds and days computed; a row ending on a bound says it in words: "MORE THAN 10.5 lb lost", "AT MOST 8.5 lb lost"), `status`, ONE `reading`, a `footnote`; `audio: {clip, start, end}` plays that clip's sound under it (its citation and QR drawn, its picture not), else silent for `seconds` (7, at most 8). Into the cut or the take's timeline only (`--take`, an undo point of the take's), at the end unless `--after` (`-`: the start); refused for a row the ledger lacks and everything the lint refuses (**exit 1**). `set-analysis` replaces the keys given (`null` removes one). `--dry-run`: every figure with its row, nothing written. `--json`: `{ok, op, take?, inserted\|updated, warnings, figures, revision?}` |
| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one |
| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` |
| `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) |
@@ -357,6 +358,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `timeline <project> groups promote <gid> [--label LABEL]` | a group opens a subsection | form · *draft* |
| `timeline <project> add-video <src> [--from N] [--to N] [--fit contain\|cover] [--bass N] [--gain N] [--enter ENTER] [--hold N] [--title TITLE] [--id ID] [--after AFTER] [--dry-run] [--take TAKE]` | a video entry: a project file full frame | form · *draft* |
| `timeline <project> set-video <id> key=value… [--take TAKE]` | a video entry's knobs | form · *draft* |
+| `timeline <project> add-analysis <item> [--id ID] [--after AFTER] [--dry-run] [--take TAKE]` | an analysis item: an ending drawn from the ledger | form · *draft* |
+| `timeline <project> set-analysis <id> <patch> [--dry-run] [--take TAKE]` | an analysis item's keys (null removes one) | form · *draft* |
| `scenes <project> <clip> [--black-min N] [--threshold N] [--pix-th N] [--pad N] [--from N] [--to N]` | scene cuts and black spans in a clip's fetched window | form · *project* |
| `posts add <project> <post> [--attach ATTACH] [--flag FLAG] [--author AUTHOR] [--id ID] [--thread] [--crop N] [--dry-run]` | a post card from the posts archive | form · *draft* |
| `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -2402,6 +2402,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr
| [Counter](#counter) `counter` | A running tally of named series in the deck, each cell stepping as a mark's stamp lands. (drawn in the deck's page) | `render.chrome.deck.counter` |
| [Claim checks](#claim-checks) `claims` | His explicit claims against the record on the rail: a count over a window, a goalpost moved. (drawn in the deck's page) | `render.chrome.deck.claims` |
| [Section title](#section-title) `section-title` | The current section's name (the marker that opened it) on one quiet line under the rail. (drawn in the deck's page) | `render.chrome.deck.sectionTitle` |
+| [Analysis item](#analysis-item) `analysis` | An ending built from the ledger: a chart of a named run of his weights, a pace table, a status row and one reading line, as its own segment. (a segment cut into the timeline) | -- |
| [Teaser](#teaser) `teaser` | A full-frame card of lines popping in on the beat, inserted as its own segment. (a segment cut into the timeline) | -- |
| [Intro](#intro) `intro` | The brand sting the cut opens with, a site's name swapped in on the chime. (a segment cut into the timeline) | `render.intro` |
| [Blur](#blur) `blur` | A clip's picture blurred at its encode, a caption on it, the sound as recorded. (a filter on the footage) | `render.blur` |
@@ -2532,6 +2533,14 @@ The current section's name on one quiet line centred under the rail (`render.chr
| `deck.sectionTitle.fade` | 0–2 s: the old title out over its first half, the new in over the second (0: a cut) · default 0.4 | `umtool look <p> deck.sectionTitle.fade=0.6` |
| `deck.sectionTitle.color` | `auto` (the subtitle's muted grey, lifted toward the deck's fg only as far as it needs to read at 4.5:1 at that opacity) · `section` (its section's colour, fitted to 4.5:1) · a `#hex` · a palette key (`fg`, `muted`, `accent`, `amber`, `dim`) · default `auto` | `umtool look <p> deck.sectionTitle.color=section` |
+### Analysis item
+
+A timeline entry `{ type: "analysis", … }` (analysis-plan.mjs; [report-video.md](report-video.md#the-analysis-item)): a full-frame ending drawn from the LEDGER -- a chart of a named run of his weights (`series`: rows, or a span; a delta resolved against the run's start), a shaded `band`, `marks`, a `pace` table whose pounds and days are computed, `status` rows and ONE `reading` -- the line drawing in, the rows landing; with `audio` a clip's sound under it (its citation and QR on the page, its picture not), else silent for `seconds` (7, at most 8). Every figure traces to a ledger row (the dashed line too: `mark: {row}`); a bound ("< 300") is drawn hollow and a pace row ending on one says it in words ("MORE THAN 10.5 lb lost", "AT MOST 8.5 lb lost"); a number typed into the words is a lint warning.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| an `analysis` entry | `title`, `kicker`, `series`, `band`, `marks`, `pace`, `status`, `reading`, `footnote`, `mark`, `audio?`, `seconds?` | `umtool timeline <p> [--take <t>] add-analysis @<file>` · `set-analysis <id> @<file>` (or the JSON itself) |
+
### Teaser
A timeline entry `{ type: "teaser", lines, … }`: a full-frame card whose lines pop in on the beat, cut in as its own segment (deck.mjs `validateTeaser`; [report-video.md](report-video.md)).
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -456,6 +456,99 @@ umtool timeline <p> --take mid-22 add-video posts-media/…/2117366108705767779_
umtool timeline <p> --take mid-22 set-video video audio.bass=10 enter=0.8,0.4
```
+### The analysis item
+
+```jsonc
+{ "type": "analysis", "id": "analysis",
+ "kicker": "THE KETO RUN · EVERY WEIGHT HE STATED",
+ "title": "What his own numbers say",
+ "series": { "rows": ["w91", "w87", "w93", "w104", "w115", "w118", "w122", "w137"] }, // or { "from": "<date|row>", "to": "<date|row>" }
+ "band": { "from": "2026-10-23", "to": "2026-11-03", "label": "WORLD SERIES" }, // an event's dates, TYPED; inside the series
+ "marks": [{ "row": "w118", "label": "offers the scale video", "quote": "…" }], // a point of the series
+ "pace": [{ "from": "2026-09-24", "to": "2026-10-15" }, { "from": "w122", "to": "w137", "note": "…" }],
+ "status": [{ "label": "SCALE VIDEO", "value": "NOT POSTED", "note": "offered 23 Oct", "color": "red", "row": "p01" }],
+ "reading": "By his own numbers the loss is steady — and it stalled …", // ONE line, required
+ "footnote": "All figures are his own statements; no weigh-in has been shown.",
+ "mark": { "row": "w115" }, // the dashed line at that row's value
+ "audio": { "clip": "c46", "start": 4112.6, "end": 4127.1 }, // optional: that clip's sound under it
+ "seconds": 7 } // without audio; at most 8
+```
+
+An ending built from **data, not a clip** (`analysis-plan.mjs`, `chrome-analysis.mjs`): the whole frame,
+on the deck's ground, faces and colours -- a chart of a named run of his weights with a shaded band, a
+pace table, status rows and one reading line. Calm, not a trailer: the title fades in, the axes and
+the band, the line draws point to point in date order (each point and its mark as the line reaches
+it), the pace rows land one by one, then the status, then the reading. No slam, no hit, no camera move.
+
+**Every figure is a ledger row's.** The ledger is the live one (`video.manifest.json` → `ledger`; a
+variant reads its whole measure record). A series row is a weight of HIS on the value track --
+`current`, `past` (at its `asOf`) or `delta`, which is resolved against **the run's start** exactly as a
+loss goal's base is (measure-slice.mjs `runStartAt`: a remembered weight within `bandGapDays` before the
+run's first loss claim) and names that row; a `{from, to}` span that takes a delta with no such start is
+refused, naming the rows to give as `rows` instead. Of two weights for one day the line takes the one said
+last. A pace row's ends are row ids, or dates with exactly ONE series point on them (two on one day: name
+one by id); its **pounds and days are computed**, never typed. A mark draws its row's figure and day, then
+your words. The dashed line (`mark`) is a row's: `{ "row": "w115" }` draws it at that row's value, labelled
+with the number ("300" for w115's "< 300"); a bare number is refused. A status row may name its row (`row`,
+HIS -- another speaker's is refused). A row the ledger lacks, another speaker's row, a non-weight row, a band
+outside the series or a pace end with no point refuses the item. **The band's dates are typed** -- an event's
+dates (the World Series), not ledger rows.
+
+**Numbers typed into words are said.** In the title, the kicker, the reading, the footnote, the band's
+label, a mark's label, a pace row's note and a status row's label, value and note, every date ("23 Oct",
+"Oct 23, 2026", "Oct 2026", "2026-10-23") is taken out and then ANY digit left is a lint warning naming the
+field -- "In 2026 he lost 75 lb" warns for "2026" and "75" (a year counts as a date only beside a month).
+A field that names a row (a mark, a status row with `row`) may say that row's own figure ("under 300" on
+w115), and a date there that is not the row's is said too.
+
+**A bound is never an exact figure.** A row with a qualifier (`<`, `>`; "under 300") is drawn as a hollow
+point, and the line's stretches to and from it are dotted. A pace row ending on a bound says so in WORDS,
+unsigned, in the direction that stays true whatever the real change was: ending on `< 300` it is **"MORE
+THAN 10.5 lb lost"**, starting on it **"AT MOST 8.5 lb lost"** (for a gain, "MORE THAN / AT MOST n lb
+gained"); its sub-line says which end ("to < 300"). Opposite bounds at both ends draw "—"; an approximate end
+(`≈`) draws "about −9 lb"; every exact row keeps its sign ("−0.7 lb"). `--dry-run` and the lint say the same
+words and name the bounded row ("w110 310.5 → w115 < 300").
+
+**Its sound.** With `audio`, the named clip's sound over `[start, end]` plays under the item. The span must
+lie inside what the cut KEEPS of that clip -- within its `cutStart`–`cutEnd` (its `start`–`end` without a
+cut) and in none of its `gaps` -- and be at most 30 s; anything else is refused. It is read from the window
+the clip's own segment is cut from (the build's `analysisAudioSource`: a window on disk first, the piece that
+holds the span for a clip fetched in pieces), so a full build fetches nothing the clip does not and
+`--chrome-only` reads only what is on disk; a span that would start before that file does is refused. It
+plays at the clip's own level (its cut record's loudness gain under `render.loudness`, then its own
+`audio.gain`), faded in and out over 0.3 s. Its picture is not shown; its citation ("HEARD: channel · title ·
+date · clock") and its QR are, at the foot. The item lasts exactly the span. The lint warns when the cut
+also plays that span (the words heard twice). Without audio the item is **silent for `seconds`** (default 7,
+at most 8: no dead air); a short one's motion is scaled to leave a 1.5 s hold. Works with no model anywhere.
+
+**What fits.** The side panel holds **5 rows** (pace and status together; pace at most 5, status at most 2);
+the reading **two lines** -- about 185 characters, 160 beside the QR; the title 44, the kicker 64, the band's
+label 28, a mark's line 46, a pace note 24, a status label 20, value 12, note 36, the footnote 120. The lint
+refuses past those (an estimate on the deck's condensed faces); the build then MEASURES the page at its last
+frame in the browser (`?measure`) and refuses any box that leaves the frame, a table row wider than the panel
+or whose words and figure overlap, the table running into the reading, the QR or the citation over the
+table, the reading or the footnote, and a mark over the table. The normal case -- four pace rows, one status
+row, a two-line reading, the QR -- has clear room.
+
+**Its segment** is composed and rendered once (`chrome/analysis-<id>/`, cached by its page key, as a
+teaser's is) and encoded with its sound; `segments/<id>.analysis.json` keys the frames, the sound (the
+source file, its offset, its gain) and the encode, so an unchanged item is not encoded again, and
+`--chrome-only` rebuilds it from the cache; a `--cut-window` preview lays it as any segment. The deck is away
+over it (full frame). It draws in the deck's faces: a cut without `render.fontRegular` and `render.fontBold`
+is refused early. No vertical form: a 9:16 cut, or `--vertical` on a landscape one, refuses it before
+anything is spent. Its date axis is by days alone (`trailLayout`'s `dayShare: 1`), whatever share the
+by-date trail gives its weights: a span's width says its days. `umtool ledger rm` refuses
+a row an analysis item draws, naming the item. A cut without an analysis item builds byte for byte as
+before. **Play the cut** draws its page as the build does (composed for preview by `POST
+/api/report/chrome/teasers`, as a teaser's), seeked on the cut clock -- silent: the sound under it is the
+render's.
+
+```sh
+umtool timeline <p> --take rev9-a10 add-analysis @first-use.json --after c99 --dry-run # every figure with its row
+umtool timeline <p> --take rev9-a10 add-analysis @first-use.json --after c99
+umtool timeline <p> --take rev9-a10 set-analysis analysis '{"audio": null, "seconds": 7}'
+```
+
### Post items: a post as an entry of the cut
A post card laid OVER a clip (`posts[]`, the deck's feed and popups) says what was
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -2102,6 +2102,34 @@ pt.timeline = pt.timeline.map((e) => (e.id === "k01"
writeFileSync(ptFile, JSON.stringify(pt, null, 2) + "\n");
}
+// AN ANALYSIS ITEM in Play the cut (play-teaser.spec.ts, lane analysis-ending): the Play cut with its card k01
+// replaced by an analysis item a01 drawn from a small measure ledger (silent, 6 s), shown as the build draws it.
+{
+const { dir: playAnalysisDir } = makePlayCutFixture({
+ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"),
+ name: "play-analysis-fixture", title: "The Play Analysis Fixture",
+});
+const paFile = path.join(playAnalysisDir, "video.manifest.json");
+const pa = JSON.parse(readFileSync(paFile, "utf8"));
+const W = (id, population, date, value, extra = {}) => ({ id, scope: "weight", population, date, value, ...extra });
+pa.ledgerSchema = {
+ kind: "measure", unit: "lb", bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }],
+ fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], render: "cell" }],
+};
+pa.ledger = [
+ W("w1", "delta", "2026-07-23", -5), W("w2", "past", "2026-08-03", 349, { asOf: "2026-07-19" }), W("w3", "delta", "2026-09-04", -31.5),
+ W("w4", "current", "2026-09-24", 310.5), W("w5", "current", "2026-10-15", 300, { qualifier: "<" }), W("w6", "current", "2026-10-26", 291.5, { asOf: "2026-10-23" }),
+];
+pa.timeline = pa.timeline.map((e) => (e.id === "k01"
+ ? {
+ type: "analysis", id: "a01", seconds: 6, title: "What his own numbers say", kicker: "THE RUN",
+ series: { rows: ["w2", "w3", "w4", "w5", "w6"] }, pace: [{ from: "w4", to: "w5" }, { from: "w5", to: "w6" }],
+ reading: "The loss is steady.", mark: { row: "w5" },
+ }
+ : e));
+writeFileSync(paFile, JSON.stringify(pa, null, 2) + "\n");
+}
+
// THE INTRO, PLAYABLE (intro-play.spec.ts, lane intro-play): the Play cut opening on a title-card intro with a
// sound of its own, and a whole-cut version v1 the spec switches the intro off and on in. WRITABLE, its own.
makeIntroPlayFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture });
diff --git a/umtool/e2e/play-teaser.spec.ts b/umtool/e2e/play-teaser.spec.ts
@@ -70,3 +70,31 @@ test("a teaser card that carries a mark plays as the build draws it: its lines,
await expect(root(page)).toHaveAttribute("data-play-item", "c01");
await expect(card(page)).toHaveCount(0);
});
+
+// AN ANALYSIS ITEM (lane analysis-ending): its own page (chrome-analysis.mjs) composed for preview by the same route
+// and laid full frame, seeked on the cut clock -- the build's figures from the fixture's ledger, a bound said over/under.
+test("an analysis item plays as the build draws it: its page full frame, its pace rows computed from the ledger", async ({ page }) => {
+ const P = "reports/play-analysis-fixture";
+ const item = page.locator('[data-play-teaser="a01"]');
+ const f = page.frameLocator('[data-testid="play-teaser-iframe"]');
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(P, { clip: "a01", at: 5.5 }));
+ await expect(root(page)).toHaveAttribute("data-play-item", "a01", { timeout: 30_000 });
+ await expect(item).toHaveAttribute("data-play-teaser-ready", "1", { timeout: 30_000 });
+ await expect(page.locator("[data-play-placeholder]")).toHaveCount(0);
+ await expect(f.locator(".ttl")).toHaveText("What his own numbers say");
+ // A bound in words, unsigned: ending on w5's "< 300" more than 10.5 lb lost, starting on it at most 8.5 lb lost.
+ await expect(f.locator('[data-k="r0"] .v')).toHaveText("MORE THAN10.5 lblost");
+ await expect(f.locator('[data-k="r1"] .v')).toHaveText("AT MOST8.5 lblost");
+ await expect(f.locator('[data-k="r0"] .ls')).toHaveText("21 days · to < 300");
+ // Landed by now (the rows land after the line): seeked, not a still of its first frame.
+ await expect.poll(() => f.locator('[data-k="rd"]').evaluate((el) => Number(getComputedStyle(el).opacity)), { timeout: 10_000 }).toBeGreaterThan(0.9);
+ // Shown, not only loaded: the page's frame is visible on the stage.
+ await expect(item).toHaveAttribute("data-play-teaser-ready", "1");
+ await expect(page.locator('[data-play-teaser="a01"] iframe')).toBeVisible();
+ await page.screenshot({ path: test.info().outputPath("play-analysis.png") });
+ // Out of it (c01): no page on screen.
+ await page.locator('[data-play-row="c01"]').press("Enter");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ await expect(item).toHaveCount(0);
+});
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -964,6 +964,8 @@ export const GROUPS = [
"**the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said)"],
["`timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\\|cover] [--bass dB] [--gain dB] [--enter cut\\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-video <id> <key>=<value>…`",
"**a video entry** ([report-video.md](report-video.md#a-video-entry)): a file of the project (`src`, relative; probed, its `fileSeconds` written) played FULL FRAME with its own sound, nothing drawn over it, at the end unless `--after` (`-`: the start), into the cut or the take's timeline only (`--take`, an undo point of the take's); `set-video` sets `from= to= fit= audio.bass= audio.gain= enter=cut\\|<out>,<in> enter.out= enter.in= holdLast= deck=hidden\\|shown title= note= src=` (`key=` clears). `--dry-run`: the entry and its place, nothing written. `--json`: `{ok, op, take?, inserted\\|updated {id, at, entry}, revision?}`. **Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage**"],
+ ["`timeline <project> [--take <t>] add-analysis <json\\|@file> [--id ID] [--after <id>\\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-analysis <id> <json\\|@file> [--dry-run] [--json]`",
+ "**an analysis item** ([report-video.md](report-video.md#the-analysis-item)): an ending drawn from the LEDGER, full frame -- a chart of a named run of his weights (`series`: `{rows}` or `{from, to}`; a delta against the run's start), a `band`, `marks`, a `pace` table (pounds and days computed; a row ending on a bound says it in words: \"MORE THAN 10.5 lb lost\", \"AT MOST 8.5 lb lost\"), `status`, ONE `reading`, a `footnote`; `audio: {clip, start, end}` plays that clip's sound under it (its citation and QR drawn, its picture not), else silent for `seconds` (7, at most 8). Into the cut or the take's timeline only (`--take`, an undo point of the take's), at the end unless `--after` (`-`: the start); refused for a row the ledger lacks and everything the lint refuses (**exit 1**). `set-analysis` replaces the keys given (`null` removes one). `--dry-run`: every figure with its row, nothing written. `--json`: `{ok, op, take?, inserted\\|updated, warnings, figures, revision?}`"],
["`timeline <project> insert (--after <id\\|-> \\| --to-section N \\| --group G) post:<channel>/<postId> [--id ID]`",
"**one post item** among the cut's entries, made as `posts reel` makes one"],
["`timeline <project> insert (--after <id\\|-> \\| --to-section N \\| --group G) post-json:<json>\\|post-json:@<file> [--id ID]`",
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -478,6 +478,10 @@ function timeline() {
num("--hold"), opt("--title"), opt("--id"), opt("--after"), dry(), takeOpt(),
]),
tl("set-video", "draft", "a video entry's knobs", [id(), pairs({ help: "from= to= fit= audio.gain= …, one per line" }), takeOpt()], B(["video"], { id: "{id}" })),
+ tl("add-analysis", "draft", "an analysis item: an ending drawn from the ledger", [
+ arg("item", { type: "text", atFile: true, help: "the item as JSON (@file: from a terminal)" }), opt("--id"), opt("--after"), dry(), takeOpt(),
+ ]),
+ tl("set-analysis", "draft", "an analysis item's keys (null removes one)", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" }), dry(), takeOpt()]),
];
}
diff --git a/umtool/lib/report/analysisCli.test.mjs b/umtool/lib/report/analysisCli.test.mjs
@@ -0,0 +1,146 @@
+// `umtool timeline <p> [--take <t>] add-analysis | set-analysis` (timelineCli.mjs analysisVerb): an analysis item into
+// the draft or a take's timeline only, checked against the ledger as the build checks it, every write an undo point;
+// --dry-run prints every figure with its row and writes nothing.
+//
+// Run with: node --test lib/report/analysisCli.test.mjs
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { draftTake } from "./takeMaker.mjs";
+import { resolveTakeManifest } from "./takeManifest.mjs";
+import { timelineCommand } from "./timelineCli.mjs";
+import { ledgerCommand } from "./ledgerCli.mjs";
+
+const W = (id, population, date, value, extra = {}) => ({ id, scope: "weight", population, date, value, ...extra });
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "fixture",
+ title: "Fixture",
+ render: { width: 640, height: 360, fps: 15, transition: 0, fontRegular: "/fonts/Regular.ttf", fontBold: "/fonts/Bold.ttf" },
+ ledgerSchema: {
+ kind: "measure", unit: "lb", bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }],
+ fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], render: "cell" }],
+ },
+ ledger: [
+ W("w83", "delta", "2026-07-23", -5),
+ W("w91", "past", "2026-08-03", 349, { asOf: "2026-07-19" }),
+ W("w104", "delta", "2026-09-04", -31.5),
+ W("w110", "current", "2026-09-24", 310.5),
+ W("w115", "current", "2026-10-15", 300, { qualifier: "<" }),
+ W("w118", "current", "2026-10-26", 291.5, { asOf: "2026-10-23" }),
+ ],
+ timeline: [
+ { type: "clip", id: "c01", channel: "chan", video: "vid", start: 100, end: 160, cite: 100 },
+ { type: "clip", id: "c02", channel: "chan", video: "vid", start: 200, end: 260, cite: 200 },
+ ],
+};
+const ITEM = {
+ title: "What his numbers say", kicker: "THE RUN",
+ series: { rows: ["w91", "w104", "w110", "w115", "w118"] },
+ pace: [{ from: "w110", to: "w115" }, { from: "w115", to: "w118" }],
+ reading: "The loss is steady.",
+};
+
+async function project() {
+ const root = await mkdtemp(path.join(tmpdir(), "analysis-cli-"));
+ const reportsRoot = path.join(root, "reports");
+ const dir = path.join(reportsRoot, "proj");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n");
+ await writeFile(path.join(root, "item.json"), JSON.stringify(ITEM));
+ const out = [];
+ const err = [];
+ const run = (...args) => timelineCommand(args, { root: reportsRoot, out: (s) => out.push(s), err: (s) => err.push(s) });
+ return { root, dir, run, out, err, file: `@${path.join(root, "item.json")}` };
+}
+const manifestOf = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+
+test("add-analysis --dry-run prints every figure with its row and writes nothing", async () => {
+ const p = await project();
+ try {
+ const before = await readFile(path.join(p.dir, "video.manifest.json"), "utf8");
+ assert.equal(await p.run("proj", "add-analysis", p.file, "--after", "c01", "--dry-run"), 0, p.err.join("\n"));
+ const text = p.out.join("\n");
+ assert.match(text, /would add analysis analysis at 1 \(after c01\) in proj:/);
+ assert.match(text, /point w104: 317\.5 on 2026-09-04 \(-31\.5 from w91 349\)/);
+ assert.match(text, /pace\[0\] 24 Sep → 15 Oct: MORE THAN 10\.5 lb lost \(w110 310\.5 → w115 < 300\), 21 days -- a bound: w115/);
+ assert.match(text, /pace\[1\] 15 → 23 Oct: AT MOST 8\.5 lb lost/);
+ assert.match(text, /warning: .*pace\[0\] ends on a bound/);
+ assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), before);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("add-analysis and set-analysis on the draft: written, an undo point each, refused for a row the ledger lacks", async () => {
+ const p = await project();
+ try {
+ assert.equal(await p.run("proj", "add-analysis", p.file, "--id", "end", "--json"), 0, p.err.join("\n"));
+ const j = JSON.parse(p.out.join("\n"));
+ assert.equal(j.inserted.id, "end");
+ assert.equal(j.inserted.at, 2);
+ let m = await manifestOf(p.dir);
+ assert.deepEqual(m.timeline.map((e) => e.id), ["c01", "c02", "end"]);
+ assert.equal(m.timeline[2].type, "analysis");
+ const snaps = await readdir(path.join(p.dir, "revisions")).catch(() => []);
+ assert.ok(snaps.some((f) => /auto-before-insert/.test(f)), snaps.join(", "));
+
+ p.out.length = 0;
+ assert.equal(await p.run("proj", "set-analysis", "end", JSON.stringify({ footnote: "His own words.", kicker: null })), 0, p.err.join("\n"));
+ assert.match(p.out.join("\n"), /set analysis end at 2 in proj/);
+ m = await manifestOf(p.dir);
+ assert.equal(m.timeline[2].footnote, "His own words.");
+ assert.equal("kicker" in m.timeline[2], false);
+ assert.ok((await readdir(path.join(p.dir, "revisions"))).some((f) => /auto-before-analysis/.test(f)));
+
+ // Refusals are exit 1 (cli.md): an id already in the cut, a patch that changes the id.
+ assert.equal(await p.run("proj", "add-analysis", p.file, "--id", "end"), 1);
+ assert.match(p.err.join("\n"), /end is already in proj/);
+ assert.equal(await p.run("proj", "set-analysis", "end", JSON.stringify({ id: "zz" })), 1);
+ assert.match(p.err.join("\n"), /does not change its id/);
+ // A ledger row the item draws cannot be removed from under it (umtool ledger rm).
+ const lines = [];
+ assert.equal(await ledgerCommand(["proj", "rm", "w115"], { root: path.dirname(p.dir), out: (s) => lines.push(s), err: (s) => lines.push(s) }), 1);
+ assert.match(lines.join("\n"), /w115 is still named: analysis item end draws it/);
+ p.err.length = 0;
+ assert.equal(await p.run("proj", "set-analysis", "end", JSON.stringify({ series: { rows: ["w91", "w999"] } })), 1);
+ assert.match(p.err.join("\n"), /series row w999 is not in the ledger/);
+ assert.equal(await p.run("proj", "set-analysis", "c01", "{}"), 1);
+ assert.equal(await p.run("proj", "add-analysis", JSON.stringify({ ...ITEM, seconds: 12 }), "--id", "x"), 1);
+ assert.match(p.err.join("\n"), /held 12 s with no audio/);
+ // The item's audio clip cannot be taken out from under it.
+ p.err.length = 0;
+ assert.equal(await p.run("proj", "set-analysis", "end", JSON.stringify({ audio: { clip: "c02", start: 210, end: 224 } })), 0, p.err.join("\n"));
+ assert.equal(await p.run("proj", "remove", "c02"), 1);
+ assert.match(p.err.join("\n"), /audio\.clip c02 is not an entry of the cut/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("--take: into the take's timeline only, with the take's own undo point", async () => {
+ const p = await project();
+ try {
+ await draftTake(p.dir, { id: "tk", label: "Take", patch: {} });
+ const master = await readFile(path.join(p.dir, "video.manifest.json"), "utf8");
+ assert.equal(await p.run("proj", "--take", "tk", "add-analysis", p.file, "--after", "c01"), 0, p.err.join("\n"));
+ assert.match(p.out.join("\n"), /added analysis analysis at 1 in take tk of proj/);
+ assert.match(p.out.join("\n"), /undo point: takes\/tk\//);
+ assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), master, "the draft is untouched");
+ let m = (await resolveTakeManifest(p.dir, "tk")).manifest;
+ assert.deepEqual(m.timeline.map((e) => e.id), ["c01", "analysis", "c02"]);
+ p.out.length = 0;
+ assert.equal(await p.run("proj", "--take", "tk", "set-analysis", "analysis", JSON.stringify({ reading: "Steady, then a stall." })), 0, p.err.join("\n"));
+ m = (await resolveTakeManifest(p.dir, "tk")).manifest;
+ assert.equal(m.timeline[1].reading, "Steady, then a stall.");
+ assert.equal(await p.run("proj", "--take", "tk", "undo"), 0, p.err.join("\n"));
+ m = (await resolveTakeManifest(p.dir, "tk")).manifest;
+ assert.equal(m.timeline[1].reading, "The loss is steady.");
+ assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), master);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/ledgerRows.mjs b/umtool/lib/report/ledgerRows.mjs
@@ -20,6 +20,7 @@
import {
EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, STAMP_NOTE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields,
} from "umtool-report-to-video/ledger-totals";
+import { analysisRowRefs } from "umtool-report-to-video/analysis-plan";
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const DATE_RE = /^\d{4}(?:-\d{2}(?:-\d{2})?)?$/;
@@ -191,6 +192,8 @@ export function ledgerRowOf(manifest, base, patch, { unset = [] } = {}) {
export function ledgerRowReferences(manifest, id) {
const out = [];
for (const e of manifest.timeline ?? []) if (typeof e?.claim === "string" && e.claim.trim() === id) out.push(`timeline entry ${e.id} pins it (claim)`);
+ // An analysis item draws the rows it names (analysis-plan.mjs): its series, marks, pace ends, status rows, its line.
+ for (const e of manifest.timeline ?? []) if (e?.type === "analysis" && analysisRowRefs(e).includes(id)) out.push(`analysis item ${e.id} draws it (series, a mark, a pace end, a status row or its line)`);
const refs = isMeasureLedger(manifest) ? measureSchema(manifest.ledgerSchema).fields.filter((f) => f.kind === "rowRef").map((f) => f.key) : [];
for (const r of manifest.ledger ?? []) {
if (!isObj(r) || r.id === id) continue;
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -42,6 +42,7 @@ import { LOOK_KEYS, applyLookPatch, basicOn, lookOf } from "yt-dlp-transcript-co
import { sideErrors } from "yt-dlp-transcript-common/lib/report/vertical.mjs";
import { validateRoom } from "umtool-report-to-video/room";
import { applyVideoPatch, validateVideoEntries, validateVideoEntry } from "umtool-report-to-video/video-entry";
+import { analysisContext, analysisProblems, applyAnalysisPatch, validateAnalysisEntries } from "umtool-report-to-video/analysis-plan";
import { applySectionEnter } from "./sections.mjs";
import { citeUrlAt, parseClipSpec } from "./clipEditorModel.mjs";
import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, placeIn, reanchorMarkers, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs";
@@ -2261,6 +2262,8 @@ function structureErrors(manifest) {
...validateTeasers(manifest),
// A video entry (video-entry.mjs): a file of the project played full frame.
...validateVideoEntries(manifest),
+ // An analysis item (analysis-plan.mjs): its rows in the ledger, its audio clip in the cut.
+ ...validateAnalysisEntries(manifest),
...validateNarration(manifest),
...validateDrafted(manifest),
...validatePublish(manifest),
@@ -4322,6 +4325,33 @@ export async function updateVideoEntry(dir, id, patch, { token = null, at = null
}
/**
+ * SET an analysis item's keys (analysis-plan.mjs applyAnalysisPatch: a key replaced, `null` removed), checked as the
+ * build checks it against the manifest's ledger and cut; one undo point.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {Record<string, unknown>} patch
+ * @param {{ token?: string | null, at?: number | null }} [opts]
+ */
+export async function updateAnalysisEntry(dir, id, patch, { token = null, at = null } = {}) {
+ if (!patch || typeof patch !== "object" || !Object.keys(patch).length) throw new Error("nothing to change");
+ return structural(dir, "analysis", token, (m) => setAnalysisIn(m, id, patch, at));
+}
+
+/** The analysis write's mutation, over a manifest (the draft's or a take's). */
+export function setAnalysisIn(m, id, patch, at = null) {
+ const i = entryIndex(m.timeline, id, at);
+ const e = m.timeline[i];
+ if (e.type !== "analysis") throw new Error(`${id} is a ${e.type ?? "non-analysis"} entry, not an analysis item`);
+ const next = applyAnalysisPatch(e, patch);
+ const probe = { ...m, timeline: m.timeline.map((x, k) => (k === i ? next : x)) };
+ const errors = analysisProblems(next, analysisContext(probe)).errors;
+ if (errors.length) throw new StructureRefused(errors);
+ m.timeline[i] = next;
+ return { id, at: i, entry: next };
+}
+
+/**
* Patch one teaser: its lines, beat, dip, tail and tail wait. A key given as
* null (or "") is removed; a key not given is kept. Checked with the build's
* validateTeaser (which checks the dip too) against the patched entry.
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -54,7 +54,7 @@ import {
readCues,
} from "../projects/report.mjs";
import { normalizePostPatches, splitOnscreenRow } from "./manifest.mjs";
-import { INTRO_PREVIEW_FILES, deckPreviewDir, feedPreviewDir, finalePreviewDir, introPreviewDir, postsPreviewDir, stampPreviewDir, teaserPreviewDir } from "./serve.mjs";
+import { INTRO_PREVIEW_FILES, analysisPreviewDir, deckPreviewDir, feedPreviewDir, finalePreviewDir, introPreviewDir, postsPreviewDir, stampPreviewDir, teaserPreviewDir } from "./serve.mjs";
import { ensureWriteDir } from "./storage.mjs";
/** The schedule document deck.mjs defines, built or estimated. */
@@ -660,10 +660,11 @@ export const TEASER_SEEK_SCRIPT = `<script data-play-seek="">
})();
</script>`;
-/** The page with Play's seek before its `</body>`. */
-export const withTeaserSeek = (html) => {
+/** The page with Play's seek before its `</body>`; `id` the page's timeline (an analysis item's is "analysis"). */
+export const withTeaserSeek = (html, id = "teaser") => {
+ const script = id === "teaser" ? TEASER_SEEK_SCRIPT : TEASER_SEEK_SCRIPT.replace('__timelines["teaser"]', `__timelines[${JSON.stringify(id)}]`);
const at = html.lastIndexOf("</body>");
- return at < 0 ? html + TEASER_SEEK_SCRIPT : `${html.slice(0, at)}${TEASER_SEEK_SCRIPT}\n ${html.slice(at)}`;
+ return at < 0 ? html + script : `${html.slice(0, at)}${script}\n ${html.slice(at)}`;
};
/**
@@ -682,20 +683,21 @@ export const withTeaserSeek = (html) => {
*/
export async function composeTeaserPreviews(project, variant, timeline, { compose = composeChrome } = {}) {
const outDir = path.join(project.dir, "out", variant);
- const teasers = (timeline ?? []).filter((e) => e?.type === "teaser" && typeof e.id === "string");
+ // An analysis item (analysis-plan.mjs) is a full-frame page too: its own region, the same handshake.
+ const teasers = (timeline ?? []).filter((e) => (e?.type === "teaser" || e?.type === "analysis") && typeof e.id === "string");
const out = [];
for (const e of teasers) {
- const want = teaserPreviewDir(project.dir, variant, e.id);
+ const want = e.type === "analysis" ? analysisPreviewDir(project.dir, variant, e.id) : teaserPreviewDir(project.dir, variant, e.id);
try {
await serialised(want, async () => {
/** @type {Record<string, unknown>} */
- const args = { manifestPath: manifestOf(project), outDir, variant, region: "teaser", segment: e.id, preview: true };
+ const args = { manifestPath: manifestOf(project), outDir, variant, region: e.type, segment: e.id, preview: true };
const r = await compose(/** @type {any} */ (args));
if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
throw new Error(`compose-chrome wrote the teaser preview to ${r.projDir}, not ${want}`);
}
const file = path.join(want, "index.html");
- await writeFile(file, withTeaserSeek(await readFile(file, "utf8")), "utf8");
+ await writeFile(file, withTeaserSeek(await readFile(file, "utf8"), e.type), "utf8");
});
out.push({ id: e.id, ok: true });
} catch (err) {
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -935,6 +935,17 @@ export const teaserPreviewDir = (projectDir, variant, segment) =>
export const teaserPreviewSrc = (projectId, variant, segment, take = null) =>
`${previewBase(projectId, variant, take)}/${TEASER_PREVIEW_PREFIX}${encodeURIComponent(segment)}/index.html`;
+// An ANALYSIS item's preview page (Play the cut): compose-chrome's `analysis-preview-<id>/`, as a teaser's.
+const ANALYSIS_PREVIEW_PREFIX = "analysis-preview-";
+
+/** The preview project of one analysis entry. */
+export const analysisPreviewDir = (projectDir, variant, segment) =>
+ path.join(projectDir, "out", variant, "chrome", `${ANALYSIS_PREVIEW_PREFIX}${segment}`);
+
+/** @type {(projectId: string, variant: string, segment: string, take?: string | null) => string} */
+export const analysisPreviewSrc = (projectId, variant, segment, take = null) =>
+ `${previewBase(projectId, variant, take)}/${ANALYSIS_PREVIEW_PREFIX}${encodeURIComponent(segment)}/index.html`;
+
// THE INTRO's preview page (`render.intro`; Play's first segment, Present's
// first slide, the Cut tab's intro editor): report-to-video intro.mjs's own
// page, written beside GSAP (and the words' face) under
@@ -1006,6 +1017,12 @@ export function previewDirFor(projectDir, variant, rest, segmentIds) {
if (!new Set(segmentIds).has(seg)) return null;
return { dir: teaserPreviewDir(projectDir, variant, seg), rest: rest.slice(1) };
}
+ if (typeof head === "string" && head.startsWith(ANALYSIS_PREVIEW_PREFIX)) {
+ const seg = head.slice(ANALYSIS_PREVIEW_PREFIX.length);
+ if (!seg || /[\/\\\0]/.test(seg) || seg === "." || seg === "..") return null;
+ if (!new Set(segmentIds).has(seg)) return null;
+ return { dir: analysisPreviewDir(projectDir, variant, seg), rest: rest.slice(1) };
+ }
if (typeof head === "string" && head.startsWith(POSTS_PREVIEW_PREFIX)) {
const seg = head.slice(POSTS_PREVIEW_PREFIX.length);
if (!seg || /[\/\\\0]/.test(seg) || seg === "." || seg === "..") return null;
diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs
@@ -46,6 +46,7 @@ import {
patchClipEntry,
removeIn,
replaceManifest,
+ setAnalysisIn,
} from "./manifest.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
@@ -408,6 +409,15 @@ export async function updateTakeVideoEntry(projectDir, id, entryId, patch, { tok
);
}
+/**
+ * SET an analysis item's keys in a TAKE's timeline (manifest.mjs setAnalysisIn), checked as the build checks it
+ * against the take's ledger and cut; an undo point of the take's.
+ */
+export async function updateTakeAnalysisEntry(projectDir, id, entryId, patch, { token = null, at = null, now = new Date() } = {}) {
+ if (!patch || typeof patch !== "object" || !Object.keys(patch).length) throw new Error("nothing to change");
+ return editTakeTimeline(projectDir, id, "analysis", token, (m) => applyStructural(m, (x) => setAnalysisIn(x, entryId, patch, at)), { now });
+}
+
/** A take's label: one line, at most this long. */
export const TAKE_LABEL_MAX = 200;
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -18,6 +18,7 @@
// umtool timeline <project> remove <id> | duplicate <id>
// umtool timeline <project> post <json|@file> | post-remove <id>
// umtool timeline <project> teaser <id> <patch-json|@file>
+// umtool timeline <project> [--take <t>] add-analysis <json|@file> | set-analysis <id> <json|@file>
// umtool timeline <project> undo
// umtool timeline <project> sections | section-move <id…> --to-section N [--start]
// | section-add --after <id> [--label L] [--color C] | section-boundary <k> --after <id>
@@ -93,6 +94,7 @@ import {
redoStructural,
updateClip,
updateTeaser,
+ updateAnalysisEntry,
updateVideoEntry,
upsertPost,
} from "./manifest.mjs";
@@ -192,6 +194,14 @@ export const TIMELINE_USAGE = [
" at the end unless --after (`-`: the start); --from/--to source seconds (no --to: the file's end)",
" umtool timeline <project> [--take <t>] set-video <id> <key>=<value>… from= to= fit= audio.bass= audio.gain=",
" enter=cut|<out>,<in> enter.out= enter.in= holdLast= deck=hidden|shown title= note= src= (`key=` clears)",
+ " umtool timeline <project> [--take <t>] add-analysis <json|@file> [--id ID] [--after <id>|-] [--dry-run] [--json]",
+ " an ANALYSIS ITEM: an ending drawn from the ledger -- a chart of a named run of his weights",
+ " (series: {rows} or {from, to}), band, marks, pace, status, ONE reading, footnote, mark, audio",
+ " ({clip, start, end}: that clip's sound under it) or seconds (silent, at most 8); every figure",
+ " computed from its ledger row; at the end unless --after (`-`: the start); --dry-run prints",
+ " every figure with its row, nothing written",
+ " umtool timeline <project> [--take <t>] set-analysis <id> <json|@file> [--dry-run] [--json]",
+ " its keys replaced (null removes one), checked again against the ledger; an undo point",
" umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo | insert <spec> --after <id>|-]",
" a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),",
" each write with an undo point of the take's own; the project's manifest is untouched",
@@ -201,7 +211,7 @@ export const TIMELINE_USAGE = [
].join("\n");
const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"];
-const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "removed", "restore", "import-item", "duplicate", "post", "post-remove", "teaser", "undo", "redo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"];
+const VERBS = ["ls", "insert", "add-video", "set-video", "add-analysis", "set-analysis", "move", "place", "remove", "reject", "wrong-speaker", "removed", "restore", "import-item", "duplicate", "post", "post-remove", "teaser", "undo", "redo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"];
const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"];
const VALUED = new Set(["--as", "--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]);
/** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */
@@ -569,6 +579,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
const project = await projectOf(projectArg, root);
// A video entry (video-entry.mjs), into the cut or a take's timeline.
if (verb === "add-video" || verb === "set-video") return await videoVerb(project, verb, rest, flags, { out, json });
+ // An analysis item (analysis-plan.mjs), into the cut or a take's timeline.
+ if (verb === "add-analysis" || verb === "set-analysis") return await analysisVerb(project, verb, rest, flags, { out, json });
if (flags.has("--take")) {
// A write into a take's patch: a supported path (12 Nov; takeDeprecation.mjs) -- never the draft.
return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json });
@@ -1094,6 +1106,97 @@ async function probeSeconds(file) {
}
/**
+ * `umtool timeline <p> [--take <t>] add-analysis <json|@file> …` and `set-analysis <id> <json|@file>`: an ANALYSIS
+ * ITEM (analysis-plan.mjs) put into the cut -- or the take's timeline only -- checked against the cut's ledger as the
+ * build checks it, each write an undo point. `--dry-run`: the entry, its place and every figure it draws with its row,
+ * nothing written. Exit 0 · 1 refused (no such take or entry; a row the ledger lacks, …) · 2 usage.
+ */
+async function analysisVerb(project, verb, rest, flags, { out, json }) {
+ const A = await import("umtool-report-to-video/analysis-plan");
+ const take = flags.has("--take") ? String(flags.get("--take")) : null;
+ const dry = flags.has("--dry-run");
+ const edit = take ? await import("./takeEdit.mjs") : null;
+ let manifest;
+ if (take) {
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ manifest = (await resolveTakeManifest(project.dir, take)).manifest;
+ } else {
+ manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ }
+ const timeline = manifest.timeline ?? [];
+ const where = take ? `take ${take} of ${project.id}` : project.id;
+ // The item checked as the build checks it, in the cut as it will be: its errors refuse, its warnings are said.
+ const judge = (entry, tl) => {
+ const ctx = A.analysisContext({ ...manifest, timeline: tl });
+ const { errors, warnings } = A.analysisProblems(entry, ctx);
+ if (errors.length) throw new Error(errors.join("; "));
+ return { warnings, figures: A.analysisFigures(A.analysisPlan(entry, ctx)) };
+ };
+ let entry;
+ let at;
+ let after = null;
+ let judged;
+ if (verb === "add-analysis") {
+ const raw = await jsonArg(rest[0], "add-analysis");
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new CliError("add-analysis takes the item as a JSON object (or @file)");
+ if (raw.type !== undefined && raw.type !== "analysis") throw new Error(`add-analysis adds an analysis item, not a ${raw.type}`);
+ const { type: _t, id: rawId, ...keys } = raw;
+ void _t;
+ const id = flags.has("--id") ? String(flags.get("--id")) : typeof rawId === "string" && rawId ? rawId : "analysis";
+ if (timeline.some((e) => e?.id === id)) throw new Error(`${id} is already in ${where} (--id another, or set-analysis ${id})`);
+ entry = { type: "analysis", id, ...keys };
+ const afterArg = flags.has("--after") ? String(flags.get("--after")) : null;
+ after = afterArg === null ? (timeline.length ? timeline[timeline.length - 1].id : null) : afterArg === "-" || afterArg === "" ? null : afterArg;
+ if (after && !timeline.some((e) => e?.id === after)) throw new Error(`no entry ${after} in ${where}`);
+ at = after ? timeline.findIndex((e) => e?.id === after) + 1 : 0;
+ judged = judge(entry, [...timeline.slice(0, at), entry, ...timeline.slice(at)]);
+ } else {
+ const id = rest[0];
+ if (!id) throw new CliError("set-analysis needs the analysis item's id, then its keys as JSON (or @file)");
+ const patch = await jsonArg(rest[1], "set-analysis");
+ at = timeline.findIndex((e) => e?.id === id);
+ if (at < 0) throw new Error(`no entry ${id} in ${where}`);
+ if (timeline[at].type !== "analysis") throw new Error(`${id} is a ${timeline[at].type ?? "non-analysis"} entry, not an analysis item`);
+ // A patch that changes its id or type is refused (exit 1), as the build refuses what it breaks.
+ entry = A.applyAnalysisPatch(timeline[at], patch);
+ judged = judge(entry, timeline.map((e, k) => (k === at ? entry : e)));
+ if (!dry) {
+ const r = take
+ ? await edit.updateTakeAnalysisEntry(project.dir, take, id, patch, { token: await edit.takeToken(project.dir, take) })
+ : await withEditNotes(project, async () => updateAnalysisEntry(project.dir, id, patch, { token: await manifestToken(project.dir) }));
+ return analysisDone(r, { verb, take, where, judged, out, json, project });
+ }
+ }
+ if (dry) {
+ if (json) out(JSON.stringify({ ok: true, op: verb, dryRun: true, ...(take ? { take } : {}), at, ...(verb === "add-analysis" ? { after } : {}), entry, ...judged }, null, 2));
+ else {
+ out(`would ${verb === "add-analysis" ? `add analysis ${entry.id} at ${at}${after ? ` (after ${after})` : " (the start)"}` : `set ${entry.id}`} in ${where}:`);
+ for (const f of judged.figures) out(` ${f}`);
+ for (const w of judged.warnings) out(`warning: ${w}`);
+ }
+ return 0;
+ }
+ const r = take
+ ? await edit.insertTakeEntry(project.dir, take, after, entry, { token: await edit.takeToken(project.dir, take) })
+ : await withEditNotes(project, async () => insertEntry(project.dir, after, entry, { token: await manifestToken(project.dir) }));
+ return analysisDone(r, { verb, take, where, judged, out, json, project });
+}
+
+function analysisDone(result, { verb, take, where, judged, out, json, project }) {
+ const r = result?.result ?? result;
+ if (json) {
+ out(JSON.stringify({ ok: true, op: verb, ...(take ? { take } : {}), [verb === "add-analysis" ? "inserted" : "updated"]: { id: r.id, at: r.at, entry: r.entry },
+ warnings: judged.warnings, figures: judged.figures, ...(result?.revision ? { revision: result.revision.rel } : {}) }, null, 2));
+ return 0;
+ }
+ out(`${verb === "add-analysis" ? "added analysis" : "set analysis"} ${r.id} at ${r.at} in ${where}`);
+ for (const w of judged.warnings) out(`warning: ${w}`);
+ if (take && result?.revision) out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`);
+ return 0;
+}
+
+/**
* `umtool timeline <p> [--take <t>] add-video <src> …` and `set-video <id> k=v…`: a VIDEO ENTRY
* (video-entry.mjs) put into the cut -- or the take's timeline only -- through the timeline's writers,
* checked as the build checks it. `--dry-run`: the entry and where it goes, nothing written.
diff --git a/umtool/report-to-video/analysis-build.test.mjs b/umtool/report-to-video/analysis-build.test.mjs
@@ -0,0 +1,169 @@
+// The analysis item in the build: its sound (the clip's span under it, or the teaser's silence), its encode, its
+// length in the schedule, the deck away over it, its chapter -- and its errors among the build's validators.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import { analysisAudioGraph, analysisEncodeArgs, chapterTitle, teaserAudioGraph } from "./build-video.mjs";
+import { estimatedDuration, estimateSchedule, hidesDeck, resolveDeck } from "./deck.mjs";
+import { validatorErrors, lintManifest, qrsOf } from "./lint.mjs";
+
+const FONTS = { fontRegular: new URL("./fonts/IBMPlexMono-Regular.ttf", import.meta.url).pathname, fontBold: new URL("./fonts/IBMPlexMono-Bold.ttf", import.meta.url).pathname };
+const render = { width: 1920, height: 1080, fps: 30, audioRate: 48000, audioChannels: 2, crf: 20, preset: "fast", audioBitrate: "192k", ...FONTS };
+
+test("the sound: the clip's span laid on its clock, levelled, faded, padded to the item; silent: the teaser's silence", () => {
+ const g = analysisAudioGraph({ seconds: 14.5, render, audio: { clip: "c46" }, gain: -2.5 });
+ assert.equal(g, "[1:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,volume=-2.5dB,alimiter=limit=0.891:level=0:latency=1," +
+ "afade=t=in:d=0.3,afade=t=out:st=14.2:d=0.3,apad=whole_dur=14.5,aformat=sample_rates=48000:channel_layouts=stereo[ta]");
+ assert.doesNotMatch(analysisAudioGraph({ seconds: 14.5, render, audio: { clip: "c46" } }), /volume=/);
+ assert.equal(analysisAudioGraph({ seconds: 7, render }), teaserAudioGraph([], { seconds: 7, render }));
+});
+
+test("the encode: the frames, then the clip's span as input 1, then the graph", () => {
+ const args = analysisEncodeArgs({ framesDir: "/f", seconds: 14.5, render, audio: "[1:a]anull[ta]", sound: { path: "/raw/c.mp4", from: 1.2, seconds: 14.5 }, outPath: "/o.mp4" });
+ const i = args.indexOf("-i");
+ const j = args.indexOf("-i", i + 1);
+ assert.equal(args[i + 1], "/f/frame_%06d.png");
+ assert.deepEqual(args.slice(j - 4, j + 2), ["-ss", "1.200", "-t", "14.500", "-i", "/raw/c.mp4"]);
+ assert.ok(args.indexOf("-filter_complex") > j);
+ const silent = analysisEncodeArgs({ framesDir: "/f", seconds: 7, render, audio: "x[ta]", outPath: "/o.mp4" });
+ assert.equal(silent.filter((a) => a === "-i").length, 1);
+});
+
+const SCHEMA = { kind: "measure", tracks: [{ key: "weight", role: "value" }] };
+const manifest = (extra = {}) => ({
+ render: { ...render, chrome: { deck: {} } },
+ ledgerSchema: SCHEMA,
+ ledger: [
+ { id: "w1", scope: "weight", population: "current", date: "2026-09-01", value: 310 },
+ { id: "w2", scope: "weight", population: "current", date: "2026-10-01", value: 300 },
+ ],
+ timeline: [
+ { type: "clip", id: "c1", video: "v1", start: 10, end: 40 },
+ { type: "analysis", id: "an", title: "The run", series: { rows: ["w1", "w2"] }, reading: "It went down.", ...extra },
+ ],
+ provenance: { siteOrigin: "https://example.pages.dev", channelSlug: "chan" },
+});
+
+test("in the schedule: its length, full frame (the deck away), named by its title", async () => {
+ const m = manifest();
+ const e = m.timeline[1];
+ assert.equal(estimatedDuration(e, m.render), 7);
+ assert.equal(estimatedDuration({ ...e, audio: { clip: "c1", start: 12, end: 26.5 } }, m.render), 14.5);
+ assert.equal(hidesDeck(e, resolveDeck(m.render)), true);
+ const seg = estimateSchedule(m).segments.find((s) => s.id === "an");
+ assert.equal(seg.title, "The run");
+ assert.equal(seg.qrUrl, null);
+ assert.equal(await chapterTitle(e, 1, {}), "The run");
+});
+
+test("the build's validators and the lint: its errors, its warnings, its code measured", () => {
+ assert.deepEqual(validatorErrors(manifest()).filter((x) => /analysis/.test(x)), []);
+ const bad = manifest({ series: { rows: ["w1", "w9"] }, seconds: 9 });
+ const errs = validatorErrors(bad);
+ assert.ok(errs.some((x) => /series row w9 is not in the ledger/.test(x)), errs.join("\n"));
+ assert.ok(errs.some((x) => /held 9 s with no audio/.test(x)));
+ const heard = manifest({ audio: { clip: "c1", start: 12, end: 26.5 } });
+ const { warnings } = lintManifest(heard, { whole: heard, exists: () => true });
+ assert.ok(warnings.some((w) => /its words are heard twice/.test(w)), warnings.join("\n"));
+ const q = qrsOf(heard).find((x) => x.id === "an");
+ assert.ok(q && /example\.pages\.dev/.test(q.url) && q.px === 210, JSON.stringify(q));
+});
+
+test("the build measures the page: what fits passes, a reading or a table past its room is named", { skip: !existsSync(process.env.CHROME ?? "/usr/bin/chromium") && "no chromium" }, async () => {
+ const { measureAnalysisPage } = await import("./build-video.mjs");
+ const { analysisHtml } = await import("./chrome-analysis.mjs");
+ const m = manifest({ audio: { clip: "c1", start: 12, end: 26.5 }, pace: [{ from: "w1", to: "w2" }], status: [{ label: "SCALE VIDEO", value: "NOT POSTED", color: "red" }] });
+ const e = m.timeline[1];
+ const ctx = { ledger: m.ledger, schema: m.ledgerSchema, timeline: m.timeline, render: m.render };
+ const dir = await mkdtemp(path.join(tmpdir(), "analysis-measure-"));
+ try {
+ const page = (html) => writeFile(path.join(dir, "index.html"), html);
+ const html = analysisHtml(e, ctx, { cite: "HEARD: chan · a stream · 1:08:32", qrSrc: "qr.png" });
+ await page(html);
+ assert.deepEqual(await measureAnalysisPage(dir, m.render), []);
+ // A reading past its room (the plan refuses it first; the page is the build's last word).
+ await page(html.replace("It went down.", "word ".repeat(120)));
+ const long = await measureAnalysisPage(dir, m.render);
+ assert.ok(long.some((x) => /the reading leaves the frame|the QR overlaps the reading/.test(x)), long.join("\n"));
+ // A table past the panel's room runs under the code.
+ const row = '<div class="row"><div class="l"><div class="lt">1 → 2 OCT</div><div class="ls">1 days</div></div><div class="v">−1 lb</div></div>';
+ await page(html.replace('<div class="side">', `<div class="side">${row.repeat(8)}`));
+ const tall = await measureAnalysisPage(dir, m.render);
+ assert.ok(tall.some((x) => /the QR overlaps table row \d|the table runs into/.test(x)), tall.join("\n"));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the first use's shape WITH audio passes the build's own validator block (buildVideo) and the lint", async () => {
+ const { buildVideo } = await import("./build-video.mjs");
+ const W = (id, population, date, value, extra = {}) => ({ id, scope: "weight", population, date, value, ...extra });
+ const schema = { kind: "measure", unit: "lb", bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }],
+ fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], render: "cell" }] };
+ const m = {
+ schemaVersion: 1, slug: "fu", title: "First use", provenance: { siteOrigin: "https://example.pages.dev", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, ...FONTS }, ledgerSchema: schema,
+ ledger: [W("w83", "delta", "2026-07-23", -5), W("w91", "past", "2026-08-03", 349, { asOf: "2026-07-19" }), W("w104", "delta", "2026-09-04", -31.5), W("w110", "current", "2026-09-24", 310.5), W("w113", "delta", "2026-10-06", -47),
+ W("w115", "current", "2026-10-15", 300, { qualifier: "<" }), W("w118", "current", "2026-10-26", 291.5, { asOf: "2026-10-23" }),
+ W("w122", "delta", "2026-11-03", -58.2), W("w137", "current", "2026-11-07", 288.5), { id: "p01", scope: "weight", population: "promise", date: "2026-10-23" }],
+ timeline: [
+ { type: "teaser", id: "t1", lines: ["One"] },
+ { type: "clip", id: "c46", video: "v1", start: 4111.4, end: 4158.8, cutStart: 4112.6, cutEnd: 4158.5, gaps: [{ from: 4127.15, to: 4132.45 }] },
+ { type: "analysis", id: "analysis", kicker: "THE KETO RUN · EVERY WEIGHT HE STATED", title: "What his own numbers say",
+ series: { rows: ["w91", "w110", "w115", "w118", "w122", "w137"] }, band: { from: "2026-10-23", to: "2026-11-03", label: "WORLD SERIES" },
+ marks: [{ row: "w91", label: "he starts" }, { row: "w115", label: "" }, { row: "w118", label: "offers the scale video" }],
+ pace: [{ from: "2026-09-24", to: "2026-10-15" }, { from: "2026-10-15", to: "2026-10-23" }, { from: "2026-10-23", to: "2026-11-03", note: "the World Series" }, { from: "2026-11-03", to: "2026-11-07" }],
+ status: [{ label: "SCALE VIDEO", value: "NOT POSTED", note: "offered 23 Oct", color: "red", row: "p01" }],
+ reading: "By his own numbers the loss is steady — and it stalled for two weeks around the World Series, exactly when the scale video was promised.",
+ footnote: "All figures are his own statements; no weigh-in has been shown.", mark: { row: "w115" },
+ audio: { clip: "c46", start: 4112.6, end: 4127.1 } },
+ ],
+ };
+ assert.deepEqual(validatorErrors(m), []);
+ assert.deepEqual(lintManifest(m, { whole: m, exists: () => true }).errors, []);
+ const dir = await mkdtemp(path.join(tmpdir(), "analysis-first-use-"));
+ try {
+ const manifestPath = path.join(dir, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify(m));
+ // A fetch of the teaser is a no-op AFTER the build's validators: the block that refused `audio` on a non-clip.
+ assert.deepEqual(await buildVideo({ manifestPath, opts: { noNetwork: true, skipFetch: true }, fetchOnly: "t1" }), { out: null, failures: [] });
+ // A vertical build refuses it before anything is spent.
+ await assert.rejects(buildVideo({ manifestPath, opts: { noNetwork: true, skipFetch: true, vertical: true }, fetchOnly: "t1" }), /vertical: analysis is an analysis item, which has no vertical form/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("without the deck's faces an analysis item is refused before anything is spent", () => {
+ const m = manifest();
+ m.render = { width: 1920, height: 1080, fps: 30 };
+ assert.ok(validatorErrors(m).some((x) => /an analysis item draws in the deck's faces -- the cut needs render\.fontRegular and render\.fontBold/.test(x)));
+});
+
+test("--cut-window over an analysis item: the whole cut's segments, then the window laid -- it builds", { skip: (!existsSync(process.env.CHROME ?? "/usr/bin/chromium") || spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status !== 0) && "no chromium or ffmpeg" }, async () => {
+ const { buildVideo } = await import("./build-video.mjs");
+ const W = (id, population, date, value) => ({ id, scope: "weight", population, date, value });
+ const m = {
+ schemaVersion: 1, slug: "win", title: "Window", provenance: { siteOrigin: "https://example.pages.dev", channelSlug: "chan" },
+ render: { width: 640, height: 360, fps: 10, transition: 0, audioRate: 48000, audioChannels: 2, ...FONTS },
+ ledgerSchema: { kind: "measure", unit: "lb", tracks: [{ key: "weight", role: "value" }] },
+ ledger: [W("w1", "current", "2026-09-01", 310), W("w2", "current", "2026-10-01", 300)],
+ timeline: [{ type: "analysis", id: "an", title: "The run", series: { rows: ["w1", "w2"] }, pace: [{ from: "w1", to: "w2" }], reading: "It went down.", seconds: 4 }],
+ };
+ const dir = await mkdtemp(path.join(tmpdir(), "analysis-window-"));
+ try {
+ const manifestPath = path.join(dir, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify(m));
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true, skipFetch: true, cutWindow: { at: 1, dur: 2 } } });
+ assert.match(r.out, /win\.window\.mp4$/);
+ const probe = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", r.out], { encoding: "utf8" });
+ assert.ok(Math.abs(Number(probe.stdout) - 2) < 0.25, probe.stdout);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/analysis-plan.mjs b/umtool/report-to-video/analysis-plan.mjs
@@ -0,0 +1,624 @@
+// THE ANALYSIS ITEM'S PLAN (lane analysis-ending, 12 Nov): an ending built
+// from the ledger, not from a clip -- a chart of a named run of his weights
+// with a shaded band, a pace table, a status row and ONE reading line,
+// inserted into the cut as a timeline entry of its own:
+//
+// { "type": "analysis", "id": "an1", "title": "What his own numbers say",
+// "kicker": "THE KETO RUN · EVERY WEIGHT HE STATED",
+// "series": { "rows": ["w91", "w87", …] } // or { "from": "<date|row>", "to": "<date|row>" }
+// "band": { "from": "2026-10-23", "to": "2026-11-03", "label": "WORLD SERIES" }, // an event's dates, typed
+// "marks": [{ "row": "w118", "label": "offers the scale video", "quote": "…" }],
+// "pace": [{ "from": "2026-09-24", "to": "2026-10-15", "note": "…" }],
+// "status": [{ "label": "SCALE VIDEO", "value": "NOT POSTED", "note": "offered 23 Oct", "color": "red", "row": "p01" }],
+// "reading": "…", "footnote": "…", "mark": { "row": "w115" },
+// "audio": { "clip": "c46", "start": 4112.6, "end": 4127.1 }, // optional
+// "seconds": 7 } // without audio; at most 8
+//
+// DATA, NOT DRAWING. Every figure on screen is computed here from a ledger
+// row and carries that row's id: a point's weight (a `delta` resolved against
+// the run's start, measure-slice.mjs runStartAt -- the base a loss goal reads),
+// a mark's figure and date, a pace row's pounds and days, the dashed line's
+// value. A number TYPED into the words (a title, a label, a note, the reading)
+// is a lint warning naming the field -- dates aside ("23 Oct", "Oct 2026") --
+// unless the field names a row and the number is that row's.
+//
+// A BOUND IS NEVER AN EXACT FIGURE. A point whose row is a bound ("< 300") is
+// drawn hollow (as the trail draws a qualified weight); a pace row that ends on
+// one says it in words, unsigned and in the right direction: ending on
+// "< 300" it is "MORE THAN 10.5 lb lost", starting on it "AT MOST 8.5 lb lost".
+//
+// PURE: the entry, the ledger, the schema and the timeline in, plain data out.
+import { dateKey } from "./ledger-shared.mjs";
+import { dayNumber, fmtSigned, fmtWeight } from "./measure-draw.mjs";
+import { isUsable, runStartOf, speakerOf } from "./measure-slice.mjs";
+import { measureQualifier, measureSchema, plotDate } from "./measure-totals.mjs";
+import { playEdges } from "./mute.mjs";
+import { gapsOf } from "./gaps.mjs";
+import { trailLayout, trailLine } from "./trail-plan.mjs";
+
+/** The item's length: the silent default and ceiling (no dead air), the floor any item has, the longest audio. */
+export const ANALYSIS_SECONDS = Object.freeze({ silent: 7, silentMax: 8, min: 4, audioMax: 30 });
+
+/** How many rows each table holds on the frame (`rows`: pace and status together, the side panel's room). */
+export const ANALYSIS_LIMITS = Object.freeze({ pace: 5, status: 2, rows: 5, marks: 6, series: 120 });
+
+/**
+ * What each word field holds, in characters -- the lint's estimate of the frame (the deck's condensed faces at
+ * 1280x720 units); the build measures the page itself and refuses what leaves the frame or overlaps (chrome-analysis.mjs).
+ * `reading` with the audio's QR beside it is `readingQr`.
+ */
+export const ANALYSIS_TEXT = Object.freeze({
+ title: 44, kicker: 64, bandLabel: 28, mark: 46, quote: 100, paceNote: 24, statusLabel: 20, statusValue: 12, statusNote: 36,
+ reading: 185, readingQr: 160, footnote: 120,
+});
+
+/** The palette roles a status figure may be drawn in (or a #hex). */
+export const ANALYSIS_COLORS = Object.freeze(["accent", "amber", "red", "fg", "muted"]);
+
+/** The keys an analysis entry may carry. */
+export const ANALYSIS_KEYS = Object.freeze([
+ "type", "id", "title", "kicker", "series", "band", "marks", "pace", "status", "reading", "footnote", "mark", "audio", "seconds",
+ "onscreen", "note", "drafted",
+]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const isIso = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v);
+const r2 = (v) => Math.round(v * 100) / 100;
+const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+/** "2026-10-23" as "23 Oct". */
+export function dayMonth(iso) {
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? ""));
+ return m ? `${Number(m[3])} ${MON[Number(m[2]) - 1]}` : "";
+}
+
+/** A span's two dates as the pace table says them: "24 Sep → 15 Oct", one month once: "15 → 23 Oct". */
+export function spanWords(a, b) {
+ const [da, db] = [dayMonth(a), dayMonth(b)];
+ const [na, ma] = da.split(" ");
+ const [nb, mb] = db.split(" ");
+ return ma === mb ? `${na} → ${nb} ${mb}` : `${da} → ${db}`;
+}
+
+// ---------------------------------------------------------------------------
+// Numbers typed into words.
+// ---------------------------------------------------------------------------
+
+const MONTH = "(jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\\.?";
+const YEAR = "((?:19|20)\\d{2})";
+/** The date tokens a text may carry, strictest first: ISO, day month [year], month day [year], month year. */
+const DATE_TOKENS = [
+ { re: /\b(\d{4})-(\d{2})-(\d{2})\b/gi, of: (m) => ({ y: Number(m[1]), mon: Number(m[2]) - 1, d: Number(m[3]) }) },
+ { re: new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+${MONTH}(?:,?\\s+${YEAR})?\\b`, "gi"), of: (m) => ({ d: Number(m[1]), mon: monthIndex(m[2]), y: m[3] ? Number(m[3]) : null }) },
+ { re: new RegExp(`\\b${MONTH}\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+${YEAR})?\\b`, "gi"), of: (m) => ({ d: Number(m[2]), mon: monthIndex(m[1]), y: m[3] ? Number(m[3]) : null }) },
+ { re: new RegExp(`\\b${MONTH}\\s+${YEAR}\\b`, "gi"), of: (m) => ({ d: null, mon: monthIndex(m[1]), y: Number(m[2]) }) },
+];
+function monthIndex(word) {
+ return MON.findIndex((m) => String(word).toLowerCase().startsWith(m.toLowerCase()));
+}
+
+/**
+ * A text's typed numbers: its date tokens (each `{ text, d, mon, y }`) taken out, then every number left
+ * (`numbers`, as written). A year counts as part of a date only beside a month; a bare "2026" is a number.
+ */
+export function typedNumbers(text) {
+ let rest = String(text ?? "");
+ const dates = [];
+ for (const { re, of } of DATE_TOKENS) {
+ rest = rest.replace(re, (...m) => {
+ dates.push({ text: m[0], ...of(m) });
+ return " ";
+ });
+ }
+ return { dates, numbers: rest.match(/\d+(?:[.,]\d+)?/g) ?? [] };
+}
+
+/** Does a date token name this day (an ISO date)? A token without a year matches any year. */
+function dateIs(tok, iso) {
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? ""));
+ if (!m) return false;
+ return (tok.d === null || tok.d === Number(m[3])) && tok.mon === Number(m[2]) - 1 && (tok.y === null || tok.y === Number(m[1]));
+}
+
+/**
+ * The warnings a typed field earns: a number left once its dates are taken out -- unless `row` backs it and the
+ * number is that row's figure (`figures`, the row's value and any value it is drawn as); with a row, a date that is
+ * not the row's (its date or its asOf) is said too.
+ */
+function numberWarnings(where, text, { row = null, figures = [] } = {}) {
+ if (typeof text !== "string" || !text) return [];
+ const { dates, numbers } = typedNumbers(text);
+ const out = [];
+ const okFigure = (n) => figures.some((f) => Number.isFinite(f) && Math.abs(Math.abs(f) - Math.abs(Number(n.replace(",", ".")))) < 0.051);
+ const stray = row ? numbers.filter((n) => !okFigure(n)) : numbers;
+ if (stray.length) {
+ out.push(`${where} "${text}" has ${stray.map((n) => `"${n}"`).join(", ")} typed -- ${row ? `not ${row.id}'s figure; ` : ""}the item's figures are drawn from ledger rows${row ? "" : " (name the row, or take it out)"}`);
+ }
+ if (row) {
+ const wrong = dates.filter((d) => !dateIs(d, row.date) && !dateIs(d, row.asOf));
+ if (wrong.length) out.push(`${where} "${text}" says ${wrong.map((d) => `"${d.text}"`).join(", ")} -- not ${row.id}'s date (${dayMonth(row.date)}${row.asOf ? `, as of ${dayMonth(row.asOf)}` : ""})`);
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Bounds.
+// ---------------------------------------------------------------------------
+
+/**
+ * The bound a pace row's figure is, from its two ends' qualifiers: the true change against the computed one. Ending
+ * on "< v" (the weight was under v) the change is LESS than computed (more lost); starting on it, MORE (less lost);
+ * ">" the other way. Both ends bounding opposite ways: no bound can be said ("unknown"). Null: exact.
+ *
+ * @returns {null | "lt" | "gt" | "unknown"}
+ */
+export function paceBound(qa, qb) {
+ const dirs = [];
+ if (qa === "<") dirs.push("gt");
+ if (qa === ">") dirs.push("lt");
+ if (qb === "<") dirs.push("lt");
+ if (qb === ">") dirs.push("gt");
+ if (!dirs.length) return null;
+ return dirs.every((d) => d === dirs[0]) ? dirs[0] : "unknown";
+}
+
+/**
+ * A pace row's figure in words: `{ lead, figure, tail, text }`. Exact: the signed change ("−0.7 lb"). A bound,
+ * unsigned and in words that stay true whatever the real change was -- the change LESS than computed is "MORE THAN
+ * 10.5 lb lost" (or "AT MOST n lb gained"), MORE than computed "AT MOST 8.5 lb lost" (or "MORE THAN n lb gained");
+ * opposite bounds "—". An "about" end ("≈"): "about −9 lb".
+ */
+export function paceWords(lb, bound, approx = false) {
+ const n = `${fmtWeight(Math.abs(lb))} lb`;
+ let w;
+ if (bound === "unknown") w = { lead: null, figure: "—", tail: null };
+ else if (bound === "lt") w = lb < 0 ? { lead: "MORE THAN", figure: n, tail: "lost" } : { lead: "AT MOST", figure: n, tail: "gained" };
+ else if (bound === "gt") w = lb <= 0 ? { lead: "AT MOST", figure: n, tail: "lost" } : { lead: "MORE THAN", figure: n, tail: "gained" };
+ else if (approx) w = { lead: "about", figure: `${fmtSigned(lb)} lb`, tail: null };
+ else w = { lead: null, figure: `${fmtSigned(lb)} lb`, tail: null };
+ return { ...w, text: [w.lead, w.figure, w.tail].filter(Boolean).join(" ") };
+}
+
+/** A point as the dry-run and the lint name it: "w115 < 300", "w101 ≈324", "w110 310.5". */
+const endWords = (p) => `${p.row} ${p.qualifier === "<" || p.qualifier === ">" ? `${p.qualifier} ` : p.qualifier ?? ""}${fmtWeight(p.value)}`;
+
+// ---------------------------------------------------------------------------
+
+/** The item's length: the audio's span, else `seconds` (default ANALYSIS_SECONDS.silent). */
+export function analysisSeconds(entry) {
+ const a = entry?.audio;
+ if (isObj(a) && Number.isFinite(Number(a.start)) && Number.isFinite(Number(a.end)) && Number(a.end) > Number(a.start)) {
+ return r2(Number(a.end) - Number(a.start));
+ }
+ const s = Number(entry?.seconds);
+ return Number.isFinite(s) && s > 0 ? s : ANALYSIS_SECONDS.silent;
+}
+
+/** The ledger a cut's analysis reads: the variant's whole measure record (selectVariant keeps it), else the ledger. */
+export const analysisLedger = (manifest) => (Array.isArray(manifest?.measureLedger) ? manifest.measureLedger : manifest?.ledger ?? []);
+
+/** The context an item's plan reads, from the cut's manifest. */
+export const analysisContext = (manifest) => ({
+ ledger: analysisLedger(manifest), schema: manifest?.ledgerSchema ?? null, timeline: manifest?.timeline ?? [], render: manifest?.render ?? {},
+});
+
+/** Every analysis entry's errors, as the build refuses them. */
+export function validateAnalysisEntries(manifest) {
+ const items = (manifest?.timeline ?? []).filter((e) => e?.type === "analysis");
+ const errors = items.flatMap((e) => analysisProblems(e, analysisContext(manifest)).errors);
+ // Its page draws in the deck's faces (instrumentFonts): a cut without them is refused before anything is spent.
+ const r = manifest?.render ?? {};
+ if (items.length && (!r.fontRegular || !r.fontBold)) errors.push(`timeline ${items[0].id} (analysis): an analysis item draws in the deck's faces -- the cut needs render.fontRegular and render.fontBold`);
+ return errors;
+}
+
+/** Every analysis entry's warnings, as the lint says them. */
+export function analysisWarnings(manifest, { only = null } = {}) {
+ return (manifest?.timeline ?? []).filter((e) => e?.type === "analysis" && (!only || e.id === only)).flatMap((e) => analysisProblems(e, analysisContext(manifest)).warnings);
+}
+
+/**
+ * The ledger rows an analysis entry names (series rows, marks, pace ends given as ids, status rows, the dashed
+ * line's row) -- what `umtool ledger rm` counts as a reference.
+ */
+export function analysisRowRefs(entry) {
+ const out = new Set();
+ const add = (v) => { if (typeof v === "string" && v && !isIso(v)) out.add(v); };
+ if (Array.isArray(entry?.series?.rows)) entry.series.rows.forEach(add);
+ add(entry?.series?.from);
+ add(entry?.series?.to);
+ for (const m of Array.isArray(entry?.marks) ? entry.marks : []) add(m?.row);
+ for (const p of Array.isArray(entry?.pace) ? entry.pace : []) { add(p?.from); add(p?.to); }
+ for (const s of Array.isArray(entry?.status) ? entry.status : []) add(s?.row);
+ add(entry?.mark?.row);
+ return [...out];
+}
+
+/**
+ * An analysis entry with `patch` laid over it, key by key: a key given replaces the entry's, `null` removes it, a key
+ * not given is kept. Its `type` and `id` are not a patch's to change. Throws a sentence for a patch that is not an object.
+ */
+export function applyAnalysisPatch(entry, patch) {
+ if (!isObj(patch)) throw new Error("an analysis patch is a JSON object of the entry's keys");
+ for (const k of ["type", "id"]) if (k in patch && patch[k] !== entry?.[k]) throw new Error(`an analysis patch does not change its ${k}`);
+ const next = JSON.parse(JSON.stringify(entry));
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null) delete next[k];
+ else next[k] = JSON.parse(JSON.stringify(v));
+ }
+ return next;
+}
+
+/**
+ * Every reason the item cannot be drawn (`errors`) and what is said about it (`warnings`), each naming the entry and
+ * the row. `ctx`: `{ ledger, schema, timeline, render }` -- the WHOLE ledger (analysisLedger), the ledger's schema,
+ * the cut's timeline.
+ */
+export function analysisProblems(entry, ctx) {
+ return resolve(entry, ctx).problems;
+}
+
+/**
+ * The plan: the points (each `{ n, row, value, day, date, said, kind, qualifier, bound, base? }`), the line through
+ * them (trailLine: one point a day, the one said last, in date order), the axes laid in `box` (trailLayout, one
+ * cluster: `lo`/`hi`, `X`/`Y`, `grid`, `months`, the dashed line's `mark`), the band, the marks, the pace rows, the
+ * status rows, the words, the audio and the seconds. Throws the errors (analysisProblems) when there are any.
+ */
+export function analysisPlan(entry, ctx, box = { x0: 70, x1: 800, y0: 150, y1: 560 }) {
+ const r = resolve(entry, ctx);
+ if (r.problems.errors.length) throw new Error(r.problems.errors.join("; "));
+ const { points } = r;
+ const line = trailLine(points);
+ const mark = r.mark ? r.mark.value : null;
+ // By days alone (dayShare 1): on this chart a span's width says its days, the band and the months included.
+ const L = trailLayout(points, box, { thr: Infinity, mark, dayShare: 1 });
+ const pos = new Map(points.map((p) => [p.n, { x: L.X(p.day), y: L.Y(p.value) }]));
+ const step = L.hi - L.lo > 60 ? 20 : 10;
+ const grid = [];
+ for (let v = Math.ceil(L.lo / step) * step; v <= L.hi; v += step) if (v !== mark) grid.push({ v, y: L.Y(v) });
+ const c = L.clusters[0];
+ const months = [];
+ if (c) {
+ const d0 = new Date(c.from * 86400000);
+ let y = d0.getUTCFullYear(), m = d0.getUTCMonth() + 1;
+ for (;; m += 1) {
+ if (m > 11) { m = 0; y += 1; }
+ const day = Date.UTC(y, m, 1) / 86400000;
+ if (day > c.to) break;
+ if (day >= c.from) months.push({ day, x: L.X(day), text: m === 0 ? `JAN ${y}` : MON[m].toUpperCase() });
+ }
+ }
+ const band = r.band ? { ...r.band, x0: L.X(r.band.fromDay), x1: L.X(r.band.toDay) } : null;
+ const marks = r.marks.map((k) => ({ ...k, at: pos.get(k.n) }));
+ return {
+ title: String(entry.title ?? "").trim(),
+ kicker: String(entry.kicker ?? "").trim(),
+ reading: String(entry.reading ?? "").trim(),
+ footnote: String(entry.footnote ?? "").trim(),
+ points, line: line.map((p) => p.n), pos,
+ layout: { lo: L.lo, hi: L.hi, X: L.X, Y: L.Y, grid, months, mark, markRow: r.mark?.row ?? null, markLabel: r.mark?.label ?? null, markY: mark !== null ? L.Y(mark) : null },
+ band, marks, pace: r.pace, status: r.status, audio: r.audio, seconds: analysisSeconds(entry),
+ first: points.length ? line[0] : null, last: points.length ? line[line.length - 1] : null,
+ };
+}
+
+/** The figures the plan draws, one line each with its row -- what `--dry-run` prints. */
+export function analysisFigures(plan) {
+ const out = [];
+ for (const p of plan.points) {
+ out.push(`point ${p.row}: ${p.qualifier ?? ""}${fmtWeight(p.value)} on ${p.date}${p.base ? ` (${p.raw} from ${p.base.row} ${fmtWeight(p.base.value)})` : ""}${p.bound ? " -- a bound, drawn hollow" : ""}`);
+ }
+ if (plan.layout.mark !== null) out.push(`line ${plan.layout.markLabel} (${plan.layout.markRow}), dashed`);
+ if (plan.band) out.push(`band ${plan.band.from} → ${plan.band.to} "${plan.band.label}" (typed dates)`);
+ plan.pace.forEach((x, i) => out.push(
+ `pace[${i}] ${x.span}: ${x.text} (${endWords(x.from)} → ${endWords(x.to)}), ${x.days} days${x.boundRows.length ? ` -- a bound: ${x.boundRows.join(", ")}` : ""}`,
+ ));
+ plan.marks.forEach((k, i) => out.push(`marks[${i}] ${k.row}: ${k.text}`));
+ plan.status.forEach((s, i) => out.push(`status[${i}] ${s.label}: ${s.value}${s.note ? ` · ${s.note}` : ""}${s.row ? ` (${s.row})` : ""}`));
+ if (plan.audio) out.push(`audio ${plan.audio.clip} ${plan.audio.start}–${plan.audio.end} (${plan.seconds} s)`);
+ else out.push(`silent, ${plan.seconds} s`);
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+
+function resolve(entry, { ledger = [], schema = null, timeline = [], render = {} } = {}) {
+ const errors = [];
+ const warnings = [];
+ const id = entry?.id ?? "?";
+ const at = `timeline ${id} (analysis)`;
+ const out = { problems: { errors, warnings }, points: [], band: null, marks: [], pace: [], status: [], audio: null, mark: null };
+ if (!isObj(entry)) { errors.push(`${at}: not an object`); return out; }
+ for (const k of Object.keys(entry)) if (!ANALYSIS_KEYS.includes(k)) errors.push(`${at}: unknown key "${k}"`);
+ if (!String(entry.title ?? "").trim()) errors.push(`${at}: title is empty`);
+ if (typeof entry.reading !== "string" || !entry.reading.trim()) errors.push(`${at}: reading is empty -- the item says ONE reading`);
+ if (render && (Number(render.height) > Number(render.width) || render.format === "vertical")) {
+ errors.push(`${at}: an analysis item has no vertical form -- a 9:16 cut cannot carry it`);
+ }
+ const fits = (where, text, max) => {
+ const s = String(text ?? "").trim();
+ if (s.length > max) errors.push(`${at}: ${where} is ${s.length} characters -- at most ${max} fit the frame (the lint's estimate; the build measures the page)`);
+ };
+
+ const s = measureSchema(schema ?? {});
+ const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null;
+ const rows = (ledger ?? []).filter((r) => isObj(r) && typeof r.id === "string");
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ const order = new Map(rows.map((r, i) => [r.id, i]));
+
+ // ---- the series ----------------------------------------------------------
+ const series = entry.series;
+ const weightRow = (r) => r.scope === valueTrack && ["current", "past", "delta"].includes(r.population);
+ let picked = [];
+ let spanMode = false;
+ if (isObj(series) && Array.isArray(series.rows)) {
+ if (!series.rows.length) errors.push(`${at}: series.rows is empty`);
+ if (series.rows.length > ANALYSIS_LIMITS.series) errors.push(`${at}: series.rows has ${series.rows.length} rows (at most ${ANALYSIS_LIMITS.series})`);
+ const seen = new Set();
+ for (const rid of series.rows) {
+ const r = byId.get(String(rid));
+ if (!r) { errors.push(`${at}: series row ${rid} is not in the ledger`); continue; }
+ if (seen.has(r.id)) { errors.push(`${at}: series row ${rid} is named twice`); continue; }
+ seen.add(r.id);
+ if (!weightRow(r)) { errors.push(`${at}: series row ${rid} is not a weight (${r.scope}/${r.population}) -- a series is current, past or delta rows of the ${valueTrack ?? "value"} track`); continue; }
+ if (speakerOf(r) !== null) { errors.push(`${at}: series row ${rid} is ${speakerOf(r)}'s, not his`); continue; }
+ if (!isUsable(r)) warnings.push(`${at}: series row ${rid} is unresolved -- in no tally, drawn because the item names it`);
+ picked.push(r);
+ }
+ } else if (isObj(series) && (series.from !== undefined || series.to !== undefined)) {
+ spanMode = true;
+ const a = endDay(series.from, byId), b = endDay(series.to, byId);
+ if (!a.ok) errors.push(`${at}: series.from ${a.why}`);
+ if (!b.ok) errors.push(`${at}: series.to ${b.why}`);
+ if (a.ok && b.ok) {
+ if (b.day < a.day) errors.push(`${at}: series.to (${b.date}) is before series.from (${a.date})`);
+ picked = rows.filter((r) => weightRow(r) && speakerOf(r) === null && isUsable(r) && Number.isFinite(Number(r.value)) &&
+ dayNumber(plotDate(r)) >= a.day && dayNumber(plotDate(r)) <= b.day);
+ if (!picked.length) errors.push(`${at}: no weight of his between ${a.date} and ${b.date}`);
+ }
+ } else errors.push(`${at}: series is { rows: [ids] } or { from, to }`);
+
+ const points = [];
+ const baseless = [];
+ for (const r of picked) {
+ const raw = Number(r.value);
+ if (r.value === null || r.value === "" || !Number.isFinite(raw)) { errors.push(`${at}: series row ${r.id} has no number`); continue; }
+ const date = dateKey(plotDate(r));
+ const day = dayNumber(date);
+ if (!Number.isFinite(day)) { errors.push(`${at}: series row ${r.id} has no date`); continue; }
+ const q = measureQualifier(r, s);
+ let value = raw;
+ let base = null;
+ if (r.population === "delta") {
+ base = runStartOf(rows, schema, r.date);
+ if (!base) {
+ if (spanMode) baseless.push(r);
+ else errors.push(`${at}: series row ${r.id} is a delta (${raw}) with no run start in the record to resolve it against`);
+ continue;
+ }
+ value = r2(base.value + raw);
+ }
+ points.push({
+ row: r.id, value, raw, day, date, said: r.date ?? date, population: r.population,
+ kind: r.population === "past" ? "remembered" : r.population === "delta" ? "delta" : "stated",
+ qualifier: q, bound: q === "<" || q === ">", ...(base ? { base: { row: base.row, value: base.value } } : {}),
+ });
+ }
+ if (baseless.length) {
+ const ok = picked.filter((r) => !baseless.includes(r)).map((r) => r.id);
+ errors.push(`${at}: series {from, to} takes ${baseless.map((r) => `${r.id} (${r.value})`).join(", ")} -- deltas with no run start in the record to resolve them against; name the rows instead: "series": { "rows": [${ok.map((x) => `"${x}"`).join(", ")}] }`);
+ }
+ // `t` is the order he SAID them (date, then the ledger's order): of two weights for one day the line takes the later.
+ points.sort((p, q) => dateKey(p.said).localeCompare(dateKey(q.said)) || order.get(p.row) - order.get(q.row));
+ points.forEach((p, i) => { p.t = i; p.n = i; });
+ out.points = points;
+ const firstDay = points.length ? Math.min(...points.map((p) => p.day)) : NaN;
+ const lastDay = points.length ? Math.max(...points.map((p) => p.day)) : NaN;
+ // A pace end: a row id, or a date with exactly one point of the series on it.
+ const pointOf = (v) => {
+ if (typeof v !== "string" || !v.trim()) return { ok: false, why: "is missing" };
+ if (isIso(v)) {
+ const on = points.filter((p) => p.day === dayNumber(v));
+ if (!on.length) return { ok: false, why: `${v}: no point of the series on that day` };
+ if (on.length > 1) return { ok: false, why: `${v}: ${on.map((p) => p.row).join(", ")} are all on that day -- name one by id` };
+ return { ok: true, p: on[0] };
+ }
+ const p = points.find((x) => x.row === v);
+ if (p) return { ok: true, p };
+ return { ok: false, why: byId.has(v) ? `${v} is not a point of the series` : `${v} is not in the ledger` };
+ };
+
+ // ---- the dashed line: a row's value --------------------------------------
+ if (entry.mark !== undefined && entry.mark !== null) {
+ const m = entry.mark;
+ if (!isObj(m) || typeof m.row !== "string") errors.push(`${at}: mark is { "row": "<id>" } -- the dashed line at that row's value (a bare number is not backed by a row)`);
+ else {
+ const r = byId.get(m.row);
+ const v = Number(r?.value);
+ if (!r) errors.push(`${at}: mark.row ${m.row} is not in the ledger`);
+ else if (speakerOf(r) !== null) errors.push(`${at}: mark.row ${m.row} is ${speakerOf(r)}'s, not his`);
+ else if (r.scope !== valueTrack || r.population === "delta" || r.value === null || r.value === "" || !Number.isFinite(v)) {
+ errors.push(`${at}: mark.row ${m.row} has no weight to draw a line at (${r.scope}/${r.population})`);
+ } else out.mark = { row: r.id, value: v, label: fmtWeight(v) };
+ }
+ }
+
+ // ---- the band: an event's dates, typed -------------------------------------
+ if (entry.band !== undefined && entry.band !== null) {
+ const b = entry.band;
+ if (!isObj(b)) errors.push(`${at}: band is { from, to, label }`);
+ else {
+ const a = endDay(b.from, byId), z = endDay(b.to, byId);
+ if (!a.ok) errors.push(`${at}: band.from ${a.why}`);
+ if (!z.ok) errors.push(`${at}: band.to ${z.why}`);
+ if (a.ok && z.ok) {
+ if (z.day < a.day) errors.push(`${at}: band.to (${z.date}) is before band.from (${a.date})`);
+ else if (points.length && (a.day < firstDay || z.day > lastDay)) {
+ errors.push(`${at}: band ${a.date} → ${z.date} is outside the series (${isoOf(firstDay)} → ${isoOf(lastDay)})`);
+ } else out.band = { from: a.date, to: z.date, fromDay: a.day, toDay: z.day, label: String(b.label ?? "").trim() };
+ }
+ warnings.push(...numberWarnings(`${at}: band.label`, b.label));
+ fits("band.label", b.label, ANALYSIS_TEXT.bandLabel);
+ }
+ }
+
+ // ---- the marks -----------------------------------------------------------
+ const marks = Array.isArray(entry.marks) ? entry.marks : entry.marks === undefined ? [] : null;
+ if (marks === null) errors.push(`${at}: marks is a list`);
+ else {
+ if (marks.length > ANALYSIS_LIMITS.marks) errors.push(`${at}: ${marks.length} marks (at most ${ANALYSIS_LIMITS.marks})`);
+ marks.forEach((m, i) => {
+ if (!isObj(m)) { errors.push(`${at}: marks[${i}] is { row, label, quote? }`); return; }
+ const f = pointOf(String(m.row ?? ""));
+ if (!f.ok) { errors.push(`${at}: marks[${i}].row ${f.why}`); return; }
+ const label = String(m.label ?? "").trim();
+ const row = byId.get(f.p.row);
+ warnings.push(...numberWarnings(`${at}: marks[${i}].label`, label, { row, figures: [f.p.value, f.p.raw] }));
+ const quote = typeof m.quote === "string" ? m.quote.trim() : "";
+ const rowQuote = String(row?.quote ?? "");
+ if (quote && rowQuote && !quoteIn(quote, rowQuote)) warnings.push(`${at}: marks[${i}].quote is not in ${f.p.row}'s quote -- say whose words they are`);
+ fits(`marks[${i}].quote`, quote, ANALYSIS_TEXT.quote);
+ const fig = `${f.p.qualifier === "<" || f.p.qualifier === ">" || f.p.qualifier === "≈" ? `${f.p.qualifier} ` : ""}${fmtWeight(f.p.value)}`;
+ const text = `${fig} · ${dayMonth(f.p.date)}${label ? ` · ${label}` : ""}`;
+ fits(`marks[${i}] ("${text}")`, text, ANALYSIS_TEXT.mark);
+ out.marks.push({ i, row: f.p.row, n: f.p.n, label, quote, text });
+ });
+ }
+
+ // ---- the pace ------------------------------------------------------------
+ const pace = Array.isArray(entry.pace) ? entry.pace : entry.pace === undefined ? [] : null;
+ if (pace === null) errors.push(`${at}: pace is a list`);
+ else {
+ if (pace.length > ANALYSIS_LIMITS.pace) errors.push(`${at}: ${pace.length} pace rows (at most ${ANALYSIS_LIMITS.pace})`);
+ pace.forEach((x, i) => {
+ if (!isObj(x)) { errors.push(`${at}: pace[${i}] is { from, to, note? }`); return; }
+ const a = pointOf(x.from), b = pointOf(x.to);
+ if (!a.ok) errors.push(`${at}: pace[${i}].from ${a.why}`);
+ if (!b.ok) errors.push(`${at}: pace[${i}].to ${b.why}`);
+ if (!a.ok || !b.ok) return;
+ const days = b.p.day - a.p.day;
+ if (days <= 0) { errors.push(`${at}: pace[${i}] ends (${b.p.date}) on or before it starts (${a.p.date})`); return; }
+ const lb = r2(b.p.value - a.p.value);
+ const bound = paceBound(a.p.bound ? a.p.qualifier : null, b.p.bound ? b.p.qualifier : null);
+ const approx = a.p.qualifier === "≈" || b.p.qualifier === "≈";
+ const words = paceWords(lb, bound, approx);
+ const boundRows = [a.p, b.p].filter((p) => p.bound).map((p) => p.row);
+ const note = String(x.note ?? "").trim();
+ warnings.push(...numberWarnings(`${at}: pace[${i}].note`, note));
+ fits(`pace[${i}].note`, note, ANALYSIS_TEXT.paceNote);
+ if (bound) warnings.push(`${at}: pace[${i}] ends on a bound (${[a.p, b.p].filter((p) => p.bound).map(endWords).join(", ")}) -- drawn as ${words.text}`);
+ out.pace.push({
+ i, span: spanWords(a.p.date, b.p.date), from: pick(a.p), to: pick(b.p), lb, days, note,
+ bound, boundRows, approx, lead: words.lead, figure: words.figure, tail: words.tail, text: words.text,
+ });
+ });
+ }
+
+ // ---- the status ----------------------------------------------------------
+ const status = Array.isArray(entry.status) ? entry.status : entry.status === undefined ? [] : null;
+ if (status === null) errors.push(`${at}: status is a list`);
+ else {
+ if (status.length > ANALYSIS_LIMITS.status) errors.push(`${at}: ${status.length} status rows (at most ${ANALYSIS_LIMITS.status})`);
+ status.forEach((x, i) => {
+ if (!isObj(x)) { errors.push(`${at}: status[${i}] is { label, value, note, color, row? }`); return; }
+ const color = x.color === undefined || x.color === null || x.color === "" ? "fg" : String(x.color);
+ if (!ANALYSIS_COLORS.includes(color) && !/^#[0-9a-fA-F]{6}$/.test(color)) errors.push(`${at}: status[${i}].color "${color}" is ${ANALYSIS_COLORS.join(", ")} or a #rrggbb`);
+ const rid = x.row === undefined || x.row === null || x.row === "" ? null : String(x.row);
+ const row = rid ? byId.get(rid) ?? null : null;
+ if (rid && !row) errors.push(`${at}: status[${i}].row ${rid} is not in the ledger`);
+ else if (row && speakerOf(row) !== null) errors.push(`${at}: status[${i}].row ${rid} is ${speakerOf(row)}'s, not his -- a status names his own row`);
+ if (!String(x.label ?? "").trim() || !String(x.value ?? "").trim()) errors.push(`${at}: status[${i}] needs a label and a value`);
+ const figures = row ? [Number(row.value)] : [];
+ for (const k of ["label", "value", "note"]) warnings.push(...numberWarnings(`${at}: status[${i}].${k}`, String(x[k] ?? "").trim(), { row: row && speakerOf(row) === null ? row : null, figures }));
+ fits(`status[${i}].label`, x.label, ANALYSIS_TEXT.statusLabel);
+ fits(`status[${i}].value`, x.value, ANALYSIS_TEXT.statusValue);
+ fits(`status[${i}].note`, x.note, ANALYSIS_TEXT.statusNote);
+ out.status.push({ i, label: String(x.label ?? "").trim(), value: String(x.value ?? "").trim(), note: String(x.note ?? "").trim(), color, row: rid });
+ });
+ }
+ const tableRows = (Array.isArray(pace) ? pace.length : 0) + (Array.isArray(status) ? status.length : 0);
+ if (tableRows > ANALYSIS_LIMITS.rows) errors.push(`${at}: ${tableRows} pace and status rows -- the side panel holds ${ANALYSIS_LIMITS.rows}`);
+
+ // ---- the words -----------------------------------------------------------
+ for (const k of ["title", "kicker", "reading", "footnote"]) warnings.push(...numberWarnings(`${at}: ${k}`, typeof entry[k] === "string" ? entry[k].trim() : ""));
+ fits("title", entry.title, ANALYSIS_TEXT.title);
+ fits("kicker", entry.kicker, ANALYSIS_TEXT.kicker);
+ fits("footnote", entry.footnote, ANALYSIS_TEXT.footnote);
+ fits(`reading (two lines${entry.audio ? ", beside the QR" : ""})`, entry.reading, entry.audio ? ANALYSIS_TEXT.readingQr : ANALYSIS_TEXT.reading);
+
+ // ---- the sound and the length --------------------------------------------
+ const a = entry.audio;
+ if (a !== undefined && a !== null) {
+ if (!isObj(a)) errors.push(`${at}: audio is { clip, start, end }`);
+ else {
+ const clip = (timeline ?? []).find((e) => e?.id === a.clip) ?? null;
+ const st = Number(a.start), en = Number(a.end);
+ if (!clip) errors.push(`${at}: audio.clip ${a.clip ?? "(none)"} is not an entry of the cut`);
+ else if (clip.type !== "clip") errors.push(`${at}: audio.clip ${a.clip} is a ${clip.type} entry, not a clip`);
+ if (!Number.isFinite(st) || !Number.isFinite(en) || en <= st) errors.push(`${at}: audio.start and audio.end are source seconds, end after start`);
+ else if (clip?.type === "clip") {
+ const cut = Number.isFinite(clip.cutStart) && Number.isFinite(clip.cutEnd);
+ const lo = cut ? Number(clip.cutStart) : Number(clip.start), hi = cut ? Number(clip.cutEnd) : Number(clip.end);
+ const gaps = gapsOf(clip).filter((g) => g.from < en && g.to > st);
+ if (en - st > ANALYSIS_SECONDS.audioMax + 1e-6) errors.push(`${at}: audio is ${r2(en - st)} s -- at most ${ANALYSIS_SECONDS.audioMax}`);
+ if (st < lo - 1e-6 || en > hi + 1e-6) {
+ errors.push(`${at}: audio ${st}–${en} is outside ${clip.id}'s ${cut ? "cut" : "window"} ${lo}–${hi} -- it plays only words the cut keeps`);
+ } else if (gaps.length) {
+ errors.push(`${at}: audio ${st}–${en} runs into ${clip.id}'s gap${gaps.length > 1 ? "s" : ""} ${gaps.map((g) => `${g.from}–${g.to}`).join(", ")} -- seconds the cut takes out`);
+ } else {
+ out.audio = { clip: clip.id, start: st, end: en, video: clip.video ?? null };
+ const heard = playedSpans(clip, render).filter((g) => g.from < en && g.to > st);
+ if (heard.length) {
+ const o = heard.map((g) => `${r2(Math.max(st, g.from))}–${r2(Math.min(en, g.to))}`).join(", ");
+ warnings.push(`${at}: the audio's span plays in the cut too (${clip.id} plays ${o}): its words are heard twice`);
+ }
+ }
+ }
+ if (entry.seconds !== undefined && Number(entry.seconds) !== analysisSeconds(entry)) {
+ warnings.push(`${at}: seconds is the audio's length (${analysisSeconds(entry)}) -- the ${entry.seconds} is not read`);
+ }
+ }
+ } else {
+ const secs = analysisSeconds(entry);
+ if (entry.seconds !== undefined && !(Number(entry.seconds) > 0)) errors.push(`${at}: seconds is a number of seconds`);
+ else if (secs > ANALYSIS_SECONDS.silentMax) errors.push(`${at}: held ${secs} s with no audio (at most ${ANALYSIS_SECONDS.silentMax}: no dead air) -- shorten it or give it audio from a clip`);
+ }
+ if (analysisSeconds(entry) < ANALYSIS_SECONDS.min) errors.push(`${at}: ${analysisSeconds(entry)} s is too short to read (at least ${ANALYSIS_SECONDS.min})`);
+ return out;
+}
+
+const pick = (p) => ({ row: p.row, date: p.date, value: p.value, qualifier: p.qualifier });
+const isoOf = (day) => new Date(day * 86400000).toISOString().slice(0, 10);
+
+/** A date or a row id as a day: `{ ok, day, date }` or `{ ok: false, why }`. */
+function endDay(v, byId) {
+ if (typeof v !== "string" || !v.trim()) return { ok: false, why: "is missing" };
+ if (isIso(v)) return { ok: true, day: dayNumber(v), date: v };
+ const r = byId.get(v);
+ if (!r) return { ok: false, why: `${v} is not a date or a row of the ledger` };
+ const d = dateKey(plotDate(r));
+ return Number.isFinite(dayNumber(d)) ? { ok: true, day: dayNumber(d), date: d } : { ok: false, why: `${v} has no date` };
+}
+
+/** The source spans a clip plays in the cut: its play window less its gaps. */
+function playedSpans(clip, render) {
+ const { from, to } = playEdges(clip, render);
+ if (!Number.isFinite(from) || !Number.isFinite(to)) return [];
+ const gaps = [...gapsOf(clip)].sort((x, y) => x.from - y.from);
+ const out = [];
+ let at = from;
+ for (const g of gaps) {
+ if (g.to <= at || g.from >= to) continue;
+ if (g.from > at) out.push({ from: at, to: g.from });
+ at = Math.max(at, g.to);
+ }
+ if (at < to) out.push({ from: at, to });
+ return out;
+}
+
+const norm = (s) => String(s).toLowerCase().replace(/[’']/g, "'").replace(/[^a-z0-9' ]+/g, " ").replace(/\s+/g, " ").trim();
+/** Each part of a quote (split at an ellipsis) found in the row's words. */
+function quoteIn(quote, words) {
+ const w = norm(words);
+ return quote.split(/…|\.\.\./).map(norm).filter(Boolean).every((part) => w.includes(part));
+}
diff --git a/umtool/report-to-video/analysis-plan.test.mjs b/umtool/report-to-video/analysis-plan.test.mjs
@@ -0,0 +1,240 @@
+// The analysis item's plan (analysis-plan.mjs): every figure from a ledger row, deltas against the run's start, bounds
+// never exact (in words, in the right direction on both sides of a pace row), typed numbers said, and the refusals
+// the lint names.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ analysisFigures, analysisPlan, analysisProblems, analysisRowRefs, analysisSeconds, dayMonth, paceBound, paceWords, spanWords, typedNumbers,
+} from "./analysis-plan.mjs";
+import { validateClipAudioEntries } from "./clip-audio.mjs";
+
+// The first use's shape (quartering-diet, 12 Nov): ids, dates and values only -- no quotes.
+const SCHEMA = {
+ kind: "measure", unit: "lb", bandGapDays: 60, forms: ["current", "past", "delta", "goal", "goal_loss"],
+ tracks: [{ key: "weight", role: "value", label: "Weight" }],
+ fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], render: "cell" }],
+};
+const W = (id, population, date, value, extra = {}) => ({ id, scope: "weight", population, date, value, ...extra });
+const LEDGER = [
+ W("w81", "delta", "2026-07-21", -40, { retro: true }),
+ W("w83", "delta", "2026-07-23", -5),
+ W("w87", "current", "2026-07-31", 338),
+ W("w91", "past", "2026-08-03", 349, { asOf: "2026-07-19" }),
+ W("w93", "current", "2026-08-03", 335.5),
+ W("w104", "delta", "2026-09-04", -31.5),
+ W("w110", "current", "2026-09-24", 310.5),
+ W("w115", "current", "2026-10-15", 300, { qualifier: "<" }),
+ W("w117", "current", "2026-10-23", 291),
+ W("w118", "current", "2026-10-26", 291.5, { asOf: "2026-10-23" }),
+ W("w122", "delta", "2026-11-03", -58.2),
+ W("w137", "current", "2026-11-07", 288.5),
+ W("x1", "current", "2026-10-01", 250, { speaker: "madamsavvy" }),
+ { id: "p01", scope: "promise", population: "promise", date: "2026-10-23" },
+ { id: "s01", scope: "promise", population: "promise_claim", date: "2026-10-23", speaker: "madamsavvy" },
+];
+const TIMELINE = [
+ { type: "clip", id: "c46", video: "v1", start: 4111.4, end: 4158.8, cutStart: 4112.6, cutEnd: 4158.5, gaps: [{ from: 4127.15, to: 4132.45 }] },
+ { type: "card", id: "k1", seconds: 4 },
+];
+const CTX = { ledger: LEDGER, schema: SCHEMA, timeline: TIMELINE, render: { width: 1920, height: 1080, fps: 30 } };
+const ITEM = {
+ type: "analysis", id: "an1", title: "What his own numbers say", kicker: "THE RUN",
+ series: { rows: ["w91", "w87", "w93", "w104", "w110", "w115", "w118", "w122", "w137"] },
+ band: { from: "2026-10-23", to: "2026-11-03", label: "WORLD SERIES" },
+ marks: [{ row: "w118", label: "offers the scale video" }, { row: "w115", label: "" }],
+ pace: [{ from: "2026-09-24", to: "2026-10-15" }, { from: "2026-10-15", to: "2026-10-23" }, { from: "2026-10-23", to: "2026-11-03", note: "the World Series" }, { from: "w122", to: "w137" }],
+ status: [{ label: "SCALE VIDEO", value: "NOT POSTED", note: "offered 23 Oct", color: "red", row: "p01" }],
+ reading: "By his own numbers the loss is steady.", footnote: "All figures are his own statements.", mark: { row: "w115" },
+};
+const errorsOf = (e, ctx = CTX) => analysisProblems(e, ctx).errors;
+const warningsOf = (e, ctx = CTX) => analysisProblems(e, ctx).warnings;
+
+test("every point is its row's weight at its plot date; a delta is the run's start plus it, naming the start", () => {
+ const plan = analysisPlan(ITEM, CTX);
+ const by = Object.fromEntries(plan.points.map((p) => [p.row, p]));
+ assert.equal(by.w91.value, 349);
+ assert.equal(by.w91.date, "2026-07-19");
+ assert.equal(by.w118.date, "2026-10-23");
+ assert.equal(by.w104.value, 317.5);
+ assert.deepEqual(by.w104.base, { row: "w91", value: 349 });
+ assert.equal(by.w122.value, 290.8);
+ assert.equal(by.w115.bound, true);
+ assert.equal(plan.points[plan.line[0]].row, "w91");
+ assert.equal(plan.points[plan.line.at(-1)].row, "w137");
+ // The dashed line is a row's: w115's value, labelled with it.
+ assert.equal(plan.layout.mark, 300);
+ assert.equal(plan.layout.markLabel, "300");
+ assert.equal(plan.layout.markRow, "w115");
+});
+
+test("pace rows: pounds and days computed, never typed; a date names the one point that day", () => {
+ const { pace } = analysisPlan(ITEM, CTX);
+ assert.deepEqual(pace.map((x) => [x.from.row, x.to.row, x.lb, x.days]), [
+ ["w110", "w115", -10.5, 21], ["w115", "w118", -8.5, 8], ["w118", "w122", -0.7, 11], ["w122", "w137", -2.3, 4],
+ ]);
+ assert.equal(pace[0].span, "24 Sep → 15 Oct");
+ assert.equal(pace[1].span, "15 → 23 Oct");
+ assert.equal(pace[2].text, "−0.7 lb");
+ assert.equal(pace[2].bound, null);
+});
+
+test("a bound end is said in words, unsigned, the right way: ending on < 300 MORE THAN n lost, starting on it AT MOST n lost", () => {
+ const { pace } = analysisPlan(ITEM, CTX);
+ assert.equal(pace[0].text, "MORE THAN 10.5 lb lost");
+ assert.deepEqual(pace[0].boundRows, ["w115"]);
+ assert.equal(pace[1].text, "AT MOST 8.5 lb lost");
+ // Every case: the computed change and the direction the truth lies in.
+ assert.equal(paceWords(-10.5, "lt").text, "MORE THAN 10.5 lb lost");
+ assert.equal(paceWords(-8.5, "gt").text, "AT MOST 8.5 lb lost");
+ assert.equal(paceWords(4, "gt").text, "MORE THAN 4 lb gained");
+ assert.equal(paceWords(4, "lt").text, "AT MOST 4 lb gained");
+ assert.equal(paceWords(-3, "unknown").text, "—");
+ assert.equal(paceWords(-9, null, true).text, "about −9 lb");
+ assert.equal(paceWords(-0.7, null).text, "−0.7 lb");
+ // The ends' glyphs to a direction: "<" at the end, ">" at the start -> less than computed; opposite bounds -> none.
+ assert.equal(paceBound(null, "<"), "lt");
+ assert.equal(paceBound(">", null), "lt");
+ assert.equal(paceBound("<", null), "gt");
+ assert.equal(paceBound(null, ">"), "gt");
+ assert.equal(paceBound("<", ">"), "gt");
+ assert.equal(paceBound(">", "<"), "lt");
+ assert.equal(paceBound("<", "<"), "unknown");
+ assert.equal(paceBound(">", ">"), "unknown");
+ const w = warningsOf(ITEM);
+ assert.ok(w.some((x) => /pace\[0\] ends on a bound \(w115 < 300\) -- drawn as MORE THAN 10\.5 lb lost/.test(x)), w.join("\n"));
+ assert.ok(w.some((x) => /pace\[1\] ends on a bound \(w115 < 300\) -- drawn as AT MOST 8\.5 lb lost/.test(x)), w.join("\n"));
+ assert.ok(!w.some((x) => /\bover\b|\bunder\b/i.test(x)), w.join("\n"));
+});
+
+test("an approximate end: 'about'", () => {
+ const ledger = [...LEDGER, W("ap", "current", "2026-10-01", 301.5, { qualifier: "≈" })];
+ const e = { ...ITEM, series: { rows: ["w110", "ap"] }, pace: [{ from: "w110", to: "ap" }], marks: [], band: null, mark: null };
+ const plan = analysisPlan(e, { ...CTX, ledger });
+ assert.equal(plan.pace[0].text, "about −9 lb");
+ assert.ok(analysisFigures(plan).some((l) => l === "pace[0] 24 Sep → 1 Oct: about −9 lb (w110 310.5 → ap ≈301.5), 7 days"), analysisFigures(plan).join("\n"));
+});
+
+test("--dry-run's figures name every row, a bound with its glyph", () => {
+ const lines = analysisFigures(analysisPlan(ITEM, CTX));
+ assert.ok(lines.includes("point w104: 317.5 on 2026-09-04 (-31.5 from w91 349)"), lines.join("\n"));
+ assert.ok(lines.includes("point w115: <300 on 2026-10-15 -- a bound, drawn hollow"));
+ assert.ok(lines.includes("pace[0] 24 Sep → 15 Oct: MORE THAN 10.5 lb lost (w110 310.5 → w115 < 300), 21 days -- a bound: w115"), lines.join("\n"));
+ assert.ok(lines.includes("pace[1] 15 → 23 Oct: AT MOST 8.5 lb lost (w115 < 300 → w118 291.5), 8 days -- a bound: w115"));
+ assert.ok(lines.includes("line 300 (w115), dashed"));
+ assert.ok(lines.includes("marks[0] w118: 291.5 · 23 Oct · offers the scale video"));
+ assert.ok(lines.includes("marks[1] w115: < 300 · 15 Oct"));
+ assert.ok(lines.includes("silent, 7 s"));
+});
+
+test("typed numbers: dates taken out, every other digit said, naming the field; a row backs only its own figure", () => {
+ assert.deepEqual(typedNumbers("offered 23 Oct, Oct 2026 and 2026-10-23").numbers, []);
+ assert.deepEqual(typedNumbers("In 2026 he lost 75 lb").numbers, ["2026", "75"]);
+ assert.deepEqual(typedNumbers("Oct 2026 · 75 LB").numbers, ["75"]);
+ assert.deepEqual(typedNumbers("on Oct 23, 2026 he said 61").numbers, ["61"]);
+ const w = warningsOf({
+ ...ITEM, title: "He lost 61 lb", kicker: "61 LB DOWN", footnote: "Down 61 lb since July", reading: "In 2026 he lost 75 lb.",
+ band: { ...ITEM.band, label: "2026 · 75 LB" }, marks: [{ row: "w115", label: "under 300" }, { row: "w118", label: "291.5 on the scale" }, { row: "w137", label: "lost 70" }],
+ pace: [{ from: "w110", to: "w137", note: "3 weeks" }],
+ status: [{ label: "S", value: "5 days", note: "x" }, { label: "P", value: "SAID", note: "offered 24 Oct", row: "p01" }],
+ });
+ const has = (re) => assert.ok(w.some((x) => re.test(x)), `${re}\n${w.join("\n")}`);
+ has(/title "He lost 61 lb" has "61" typed/);
+ has(/kicker "61 LB DOWN" has "61" typed/);
+ has(/footnote "Down 61 lb since July" has "61" typed/);
+ has(/reading "In 2026 he lost 75 lb\." has "2026", "75" typed/);
+ has(/band\.label "2026 · 75 LB" has "2026", "75" typed/);
+ has(/marks\[2\]\.label "lost 70" has "70" typed -- not w137's figure/);
+ has(/pace\[0\]\.note "3 weeks" has "3" typed/);
+ has(/status\[0\]\.value "5 days" has "5" typed/);
+ has(/status\[1\]\.note "offered 24 Oct" says "24 Oct" -- not p01's date \(23 Oct\)/);
+ // A mark's label that says its own row's figure is backed: "under 300" is w115's, "291.5" w118's.
+ assert.ok(!w.some((x) => /marks\[0\]|marks\[1\]/.test(x)), w.join("\n"));
+ // The first use's words: nothing.
+ assert.ok(!warningsOf(ITEM).some((x) => /typed|says/.test(x)), warningsOf(ITEM).join("\n"));
+});
+
+test("refusals, each naming the row", () => {
+ const has = (e, re, ctx) => assert.ok(errorsOf(e, ctx).some((x) => re.test(x)), `${re}\n${errorsOf(e, ctx).join("\n")}`);
+ has({ ...ITEM, series: { rows: ["w91", "w999"] } }, /series row w999 is not in the ledger/);
+ has({ ...ITEM, series: { rows: ["w91", "p01"] } }, /series row p01 is not a weight/);
+ has({ ...ITEM, series: { rows: ["w91", "x1"] } }, /series row x1 is madamsavvy's/);
+ has({ ...ITEM, band: { from: "2026-07-01", to: "2026-08-01", label: "" } }, /band 2026-07-01 → 2026-08-01 is outside the series \(2026-07-19 → 2026-11-07\)/);
+ has({ ...ITEM, pace: [{ from: "2026-09-24" }] }, /pace\[0\]\.to is missing/);
+ has({ ...ITEM, pace: [{ from: "2026-09-25", to: "w137" }] }, /pace\[0\]\.from 2026-09-25: no point of the series on that day/);
+ has({ ...ITEM, pace: [{ from: "w137", to: "w110" }] }, /pace\[0\] ends \(2026-09-24\) on or before it starts/);
+ has({ ...ITEM, marks: [{ row: "w117" }] }, /marks\[0\]\.row w117 is not a point of the series/);
+ has({ ...ITEM, reading: " " }, /reading is empty/);
+ has({ ...ITEM, status: [{ label: "X", value: "Y", row: "zz" }] }, /status\[0\]\.row zz is not in the ledger/);
+ has({ ...ITEM, status: [{ label: "X", value: "Y", row: "s01" }] }, /status\[0\]\.row s01 is madamsavvy's, not his/);
+ has({ ...ITEM, status: [{ label: "X", value: "Y", color: "pink" }] }, /status\[0\]\.color "pink"/);
+ has({ ...ITEM, bogus: 1 }, /unknown key "bogus"/);
+ has({ ...ITEM, mark: 300 }, /mark is \{ "row": "<id>" \} -- the dashed line at that row's value \(a bare number is not backed by a row\)/);
+ has({ ...ITEM, mark: { row: "p01" } }, /mark\.row p01 has no weight to draw a line at/);
+ has({ ...ITEM, mark: { row: "x1" } }, /mark\.row x1 is madamsavvy's/);
+ // Two points for one typed day: name one by id.
+ has({ ...ITEM, series: { rows: [...ITEM.series.rows, "w117"] } }, /pace\[1\]\.to 2026-10-23: w117, w118 are all on that day -- name one by id/);
+ // A delta with no run start in the record to resolve it against.
+ const lone = { ...CTX, ledger: [W("d1", "delta", "2020-01-05", -3), W("s1", "current", "2020-01-01", 200)] };
+ const bare = { ...ITEM, band: null, pace: [], marks: [], status: [], mark: null };
+ has({ ...bare, series: { rows: ["s1", "d1"] } }, /series row d1 is a delta \(-3\) with no run start/, lone);
+ // ... in a span: one sentence naming them all and the rows to name instead.
+ has({ ...bare, series: { from: "2020-01-01", to: "2020-01-31" } }, /series \{from, to\} takes d1 \(-3\) -- deltas with no run start .*"series": \{ "rows": \["s1"\] \}/, lone);
+ assert.throws(() => analysisPlan({ ...ITEM, series: { rows: ["w999"] } }, CTX), /w999 is not in the ledger/);
+});
+
+test("audio: a clip of the cut, inside what its cut keeps -- never a gap, never past its cut, at most 30 s", () => {
+ const has = (e, re) => assert.ok(errorsOf(e).some((x) => re.test(x)), `${re}\n${errorsOf(e).join("\n")}`);
+ has({ ...ITEM, audio: { clip: "c99", start: 1, end: 9 } }, /audio\.clip c99 is not an entry of the cut/);
+ has({ ...ITEM, audio: { clip: "k1", start: 1, end: 9 } }, /audio\.clip k1 is a card entry, not a clip/);
+ has({ ...ITEM, audio: { clip: "c46", start: 4111.4, end: 4116 } }, /audio 4111\.4–4116 is outside c46's cut 4112\.6–4158\.5 -- it plays only words the cut keeps/);
+ has({ ...ITEM, audio: { clip: "c46", start: 4120, end: 4130 } }, /audio 4120–4130 runs into c46's gap 4127\.15–4132\.45/);
+ has({ ...ITEM, audio: { clip: "c46", start: 4127.2, end: 4132.4 } }, /runs into c46's gap/);
+ has({ ...ITEM, audio: { clip: "c46", start: 4113, end: 4158 } }, /audio is 45 s -- at most 30/);
+ const ok = { ...ITEM, audio: { clip: "c46", start: 4112.6, end: 4127.1 } };
+ assert.deepEqual(errorsOf(ok), []);
+ assert.equal(analysisSeconds(ok), 14.5);
+ assert.ok(warningsOf(ok).some((w) => /the audio's span plays in the cut too \(c46 plays 4112\.6–4127\.1\)/.test(w)));
+ // The build's own clip-audio check leaves an analysis item's `audio` to this one.
+ assert.deepEqual(validateClipAudioEntries({ timeline: [...TIMELINE, ok] }), []);
+});
+
+test("length: silent 7 s by default, at most 8 without audio; no vertical form", () => {
+ assert.equal(analysisSeconds(ITEM), 7);
+ assert.deepEqual(errorsOf({ ...ITEM, seconds: 8 }), []);
+ assert.ok(errorsOf({ ...ITEM, seconds: 9 }).some((e) => /held 9 s with no audio \(at most 8/.test(e)));
+ assert.ok(errorsOf({ ...ITEM, seconds: 2 }).some((e) => /too short to read/.test(e)));
+ assert.ok(errorsOf(ITEM, { ...CTX, render: { width: 1080, height: 1920 } }).some((e) => /no vertical form/.test(e)));
+ assert.ok(errorsOf(ITEM, { ...CTX, render: { width: 1920, height: 1080, format: "vertical" } }).some((e) => /no vertical form/.test(e)));
+});
+
+test("the frame's room: words past their length and rows past the panel are refused", () => {
+ const has = (e, re) => assert.ok(errorsOf(e).some((x) => re.test(x)), `${re}\n${errorsOf(e).join("\n")}`);
+ has({ ...ITEM, title: "W".repeat(80) }, /title is 80 characters -- at most 44 fit the frame/);
+ has({ ...ITEM, reading: "word ".repeat(60) }, /reading \(two lines\) is 299 characters -- at most 185/);
+ has({ ...ITEM, reading: "word ".repeat(34), audio: { clip: "c46", start: 4112.6, end: 4127.1 } }, /reading \(two lines, beside the QR\) is 169 characters -- at most 160/);
+ has({ ...ITEM, status: [...ITEM.status, { label: "WEIGH-IN", value: "NONE", color: "amber" }] }, /6 pace and status rows -- the side panel holds 5/);
+});
+
+test("the rows an item names, for `umtool ledger rm`", () => {
+ assert.deepEqual(analysisRowRefs(ITEM).sort(), ["p01", "w104", "w110", "w115", "w118", "w122", "w137", "w87", "w91", "w93"].sort());
+});
+
+test("words: a day and a span", () => {
+ assert.equal(dayMonth("2026-10-23"), "23 Oct");
+ assert.equal(spanWords("2026-10-23", "2026-11-03"), "23 Oct → 3 Nov");
+ assert.equal(spanWords("2026-11-03", "2026-11-07"), "3 → 7 Nov");
+});
+
+test("axes: one cluster fitted to the points (trailLayout), a tick per month, the mark", () => {
+ const plan = analysisPlan(ITEM, CTX, { x0: 0, x1: 1000, y0: 0, y1: 400 });
+ assert.equal(plan.layout.lo, 280);
+ assert.equal(plan.layout.hi, 360);
+ assert.deepEqual(plan.layout.months.map((m) => m.text), ["JUL", "AUG", "SEP", "OCT", "NOV"]);
+ assert.ok(plan.band.x1 > plan.band.x0);
+ // The date axis is by days alone (trailLayout dayShare 1), whatever share the by-date trail gives to its weights:
+ // equal days, equal widths.
+ const per = (a, b) => (plan.layout.X(b) - plan.layout.X(a)) / (b - a);
+ const d = (iso) => Date.parse(`${iso}T00:00:00Z`) / 864e5;
+ assert.ok(Math.abs(per(d("2026-07-19"), d("2026-08-03")) - per(d("2026-10-23"), d("2026-11-07"))) < 0.02);
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -155,6 +155,7 @@ import {
} from "./sources.mjs";
// A clip whose media is a file beside the manifest (`src`, `cues`).
import { clipLabel, createLocalMedia, hasLocalMedia, resolveManifestPath, validateLocalMedia } from "./local-media.mjs";
+import { analysisSeconds, validateAnalysisEntries } from "./analysis-plan.mjs";
import { blackoutEnable, validateVideoEntries, videoBlackouts, videoFit, videoLoudnessTarget, videoLead, videoMeasureFilter, videoSeconds, videoSegmentGraph, videoSegmentKey, videoSpan } from "./video-entry.mjs";
import { createPostChannelResolver, resolvePostLinks } from "./post-links.mjs";
import { ensureWriteDir } from "../lib/report/storage.mjs";
@@ -1208,7 +1209,7 @@ export function needsFetchMessage(missing) {
// The timeline's vocabulary is OPEN; the build loop treats everything it has
// no other branch for as a clip, and so does this.
-const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post", "video"]);
+const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post", "video", "analysis"]);
const isClipEntry = (e) => !NON_CLIP_TYPES.has(e?.type);
/**
@@ -2996,6 +2997,148 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir,
return seg;
}
+// ---- the analysis item ------------------------------------------------------
+// An `analysis` entry (analysis-plan.mjs) is a full-frame page drawn from the
+// ledger (chrome-analysis.mjs), composed and rendered once (cached by its page
+// key, as a teaser is) and encoded here with its sound: with `audio`, the
+// named clip's sound over [start, end] -- read from the window the clip's own
+// segment is cut from (analysisAudioSource: on disk first, the piece holding
+// the span for a clip fetched in pieces; its sync offset applied), at the
+// level the clip plays at (its cut record's loudness gain, its own `audio.gain`),
+// faded in and out -- its picture never shown; without, digital silence. The
+// page is MEASURED first (chrome-analysis.mjs `?measure`: a box out of the
+// frame, an overlap) and refused for it. Its record (`<id>.analysis.json`)
+// keys the frames, the sound and the encode, so an unchanged item is not
+// encoded again.
+
+/** The analysis sound's fades at its edges, in seconds. */
+export const ANALYSIS_AUDIO_FADE = 0.3;
+
+/**
+ * The analysis item's sound as one filtergraph fragment to `[ta]`: input 1 (the clip's span, `-ss`/`-t`) laid on its
+ * clock, its level gain (`gain`, dB, or null), faded in and out and padded to `seconds`; null `audio`: the teaser's
+ * silence (teaserAudioGraph with no hits).
+ */
+export function analysisAudioGraph({ seconds, render, audio = null, gain = null, clipGain = null, fade = ANALYSIS_AUDIO_FADE }) {
+ if (!audio) return teaserAudioGraph([], { seconds, render });
+ const layout = render.audioChannels === 1 ? "mono" : "stereo";
+ const f = Math.min(fade, seconds / 4);
+ return `[1:a]${[
+ AUDIO_ON_CLOCK, gain != null ? levelFilters(gain) : "", ...clipAudioFilters(clipGain ? { gain: clipGain } : null, seconds),
+ `afade=t=in:d=${f}`, `afade=t=out:st=${Number((seconds - f).toFixed(3))}:d=${f}`,
+ `apad=whole_dur=${seconds}`, `aformat=sample_rates=${render.audioRate}:channel_layouts=${layout}`,
+ ].filter(Boolean).join(",")}[ta]`;
+}
+
+/** The analysis segment's encode: its frames, the clip's span (`sound`: `{ path, from, seconds }`, raw-file seconds) or none. */
+export function analysisEncodeArgs({ framesDir, seconds, render, audio, sound = null, outPath }) {
+ const args = teaserEncodeArgs({ framesDir, seconds, render, audio, outPath });
+ if (!sound) return args;
+ const at = args.indexOf("-filter_complex");
+ return [...args.slice(0, at), "-ss", Math.max(0, sound.from).toFixed(3), "-t", sound.seconds.toFixed(3), "-i", sound.path, ...args.slice(at)];
+}
+
+/**
+ * The window an analysis item's sound is read from: the audio clip's source as its own segment has it -- a window on
+ * disk holding its extent first (onDiskClipSource), else, for a clip fetched in pieces (fetchSpans), the piece that
+ * holds [start, end] (the span lies in one: it may not cross a gap), else the clip's fetch -- so a full build fetches
+ * nothing the clip's segment does not, and --chrome-only (skipFetch) reads only what is on disk.
+ */
+export async function analysisAudioSource(clip, audio, meta, render, local, opts = {}) {
+ const disk = await onDiskClipSource(clip, meta, render, local, opts);
+ if (disk) return alignedClipSource(disk);
+ const spans = hasLocalMedia(clip) ? [] : fetchSpans(clip, render, opts);
+ if (spans.length > 1) {
+ const span = spans.find((x) => Number(audio.start) >= x.from - 1e-6 && Number(audio.end) <= x.to + 1e-6);
+ if (!span) throw new Error(`${clip.id}: no piece of its window holds ${audio.start}–${audio.end}`);
+ return fetchClipAligned(clip, meta, render, local, { ...opts, span });
+ }
+ return fetchClipAligned(clip, meta, render, local, opts);
+}
+
+/** The analysis page measured (chrome-analysis.mjs `?measure`): its sentences, empty when it fits. */
+export async function measureAnalysisPage(projDir, render) {
+ const { rendererEnv } = await import("./compose-chrome.mjs");
+ const { measuredProblems } = await import("./chrome-analysis.mjs");
+ const { stdout } = await execFileP(process.env.CHROME ?? "/usr/bin/chromium", [
+ "--headless", "--disable-gpu", "--no-sandbox", "--hide-scrollbars", `--window-size=${render.width},${render.height}`,
+ "--virtual-time-budget=8000", "--dump-dom", `file://${path.join(projDir, "index.html")}?measure=1`,
+ ], { maxBuffer: 1 << 26, env: rendererEnv() });
+ const problems = measuredProblems(stdout);
+ if (problems === null) throw new Error(`the analysis page in ${projDir} did not measure itself (its fonts or script did not load)`);
+ return problems;
+}
+
+/**
+ * Compose and render the analysis item (cached by compose-chrome's key), then encode its segment with its sound
+ * unless the one on disk was made from the same frames, sound and encode. `clipSource` gets the audio clip's source
+ * (`{ path, fetchStart }`), `meta` its record's metadata (the citation line); both null without audio.
+ */
+export async function buildAnalysisSegment(entry, { manifestPath, manifest, render, outDir, variant, clipSource = null, meta = null }) {
+ const { composeChrome } = await import("./compose-chrome.mjs");
+ const t0 = Date.now();
+ const r = await composeChrome({
+ manifestPath, outDir, variant, region: "analysis", segment: entry.id, doRender: true,
+ fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence", context: { meta },
+ lease: createCapturePool({ budget: CHROME_WORKERS }).lease,
+ });
+ EMIT("chrome", {
+ phase: r.cached ? "cached" : "render", region: "analysis", segment: entry.id,
+ frames: r.frameCount, key: r.key, dir: r.frames, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)),
+ });
+ const misfit = await measureAnalysisPage(r.projDir, render);
+ if (misfit.length) throw new Error(`${entry.id}: the analysis page does not fit the frame -- ${misfit.join("; ")}`);
+ const seconds = analysisSeconds(entry);
+ let sound = null;
+ let gain = null;
+ let clipGain = null;
+ let soundKey = null;
+ if (entry.audio) {
+ const clip = (manifest.timeline ?? []).find((e) => e?.id === entry.audio.clip && e.type === "clip");
+ if (!clip || !clipSource) throw new Error(`${entry.id}: its audio clip ${entry.audio.clip} is not a clip of the cut`);
+ const src = await clipSource(clip);
+ // The clip's sync offset (clip-audio.mjs): its sound read from that much earlier or later, as its segment reads it.
+ const off = (clipAudioOf(clip)?.offset ?? 0) / 1000;
+ const from = Number(entry.audio.start) - src.fetchStart - off;
+ if (from < -0.01) throw new Error(`${entry.id}: its audio starts ${(-from).toFixed(2)}s before ${path.basename(src.path)} begins -- fetch ${clip.id}'s window again (umtool fetch --refetch ${clip.id}) or start it later`);
+ sound = { path: src.path, from: Math.max(0, from), seconds };
+ // The level the clip plays at in its own place: its cut record's loudness gain (measured over its cut), else
+ // that measured now over its play window; then its own `audio.gain`.
+ if (loudnessTargetOf(render) != null) {
+ const rec = await readCutRecord(path.join(outDir, "segments", `${clip.id}.mp4`)).catch(() => null);
+ if (Number.isFinite(rec?.loudness?.gain)) gain = rec.loudness.gain;
+ else {
+ const { from: pf, to: pt } = playWindow(clip, render);
+ gain = (await montageLevel(src.path, Math.max(0, pf - src.fetchStart - off), pt - src.fetchStart - off, { target: loudnessTargetOf(render) })).gain;
+ }
+ }
+ clipGain = clipAudioOf(clip)?.gain ?? null;
+ const st = await stat(src.path);
+ soundKey = { file: path.basename(src.path), size: st.size, from: Number(sound.from.toFixed(3)), gain, clipGain };
+ }
+ const audio = analysisAudioGraph({ seconds, render, audio: sound ? entry.audio : null, gain, clipGain });
+ const key = createHash("sha256")
+ .update(JSON.stringify({ v: 1, frames: r.key, audio, sound: soundKey, encode: encodeArgs(render) }))
+ .digest("hex");
+ const seg = path.join(outDir, "segments", `${entry.id}.mp4`);
+ const recPath = seg.replace(/\.mp4$/, ".analysis.json");
+ const rec = await readFile(recPath, "utf8").then(JSON.parse, () => null);
+ if (rec?.key === key && (await exists(seg))) {
+ EMIT("note", { id: entry.id, message: `${entry.id}: analysis segment unchanged (key ${key.slice(0, 12)})` });
+ return seg;
+ }
+ // Encoded beside it and renamed over it (a take's segment may be a hard link to another take's), as a teaser's is.
+ const tmp = tmpPathFor(path.join(path.dirname(seg), `.${entry.id}`), { ext: ".mp4" });
+ try {
+ await execFileP(FFMPEG, analysisEncodeArgs({ framesDir: r.frames, seconds, render, audio, sound, outPath: tmp }), { maxBuffer: 1 << 26 });
+ await rename(tmp, seg);
+ } finally {
+ await rm(tmp, { force: true });
+ }
+ await replaceFile(recPath, JSON.stringify({ key, frames: r.key, sound: soundKey }) + "\n");
+ return seg;
+}
+
// ---- stills --------------------------------------------------------------
// An `image` entry is a screenshot in the cut: the receipts a clip cannot say
// out loud -- a post, a thread, a DM -- shown for `seconds` and then gone.
@@ -6079,6 +6222,7 @@ export async function chapterTitle(entry, index, provenance, { deck = false } =
if (deck && entry.onscreen?.title) return entry.onscreen.title;
// A teaser is named by its own words, with or without the deck.
if (entry.type === "teaser") return teaserTitle(entry) || `Teaser ${index + 1}`;
+ if (entry.type === "analysis") return String(entry.title ?? "").trim() || `Analysis ${index + 1}`;
// A still's chapter is the SAME line it burns into the header, for the reason
// a clip's is: the chapter list and the picture are two views of one cut, and
// a viewer jumping by chapter should land on the words they were shown.
@@ -6674,6 +6818,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
manifest.render = verticalRender(asked);
// The brand intro is a landscape page: a short opens on its first moment.
manifest.timeline = (manifest.timeline ?? []).filter((e) => !isIntro(e));
+ // An analysis item is a landscape page with no vertical form (analysis-plan.mjs): refused before anything is spent.
+ const landscape = manifest.timeline.filter((e) => e?.type === "analysis").map((e) => e.id);
+ if (landscape.length) throw new Error(`vertical: ${landscape.join(", ")} ${landscape.length > 1 ? "are analysis items" : "is an analysis item"}, which has no vertical form -- take it out of the vertical cut`);
}
// A join preview (release 38, join-preview.mjs): the first few joins of
// the cut, each clip shortened to a few seconds at the join, in the cut's look.
@@ -6700,7 +6847,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole),
...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole),
- ...validateGapEntries(whole), ...measureSettingsProblems(whole),
+ ...validateGapEntries(whole), ...measureSettingsProblems(whole), ...validateAnalysisEntries(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -7090,6 +7237,17 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
EMIT("card", { id: entry.id, i, n: entries.length });
return buildVideoEntrySegment(entry, render, outDir, manifestDir, D, manifest.timeline);
}
+ // An analysis item (analysis-plan.mjs): its page's frames and, with `audio`, its clip's sound -- read from that
+ // clip's source as the clip's own segment reads it. Written through a rename, as a teaser's is.
+ if (entry.type === "analysis") {
+ EMIT("card", { id: entry.id, i, n: entries.length });
+ const clip = entry.audio ? (manifest.timeline ?? []).find((e) => e?.id === entry.audio.clip && e.type === "clip") ?? null : null;
+ const meta = clip ? await clipMeta(clip, provenance) : null;
+ return buildAnalysisSegment(entry, {
+ manifestPath, manifest, render, outDir, variant, meta,
+ clipSource: clip ? (c) => analysisAudioSource(c, entry.audio, meta, render, dirs.local, o) : null,
+ });
+ }
if (entry.type !== "teaser" && entry.type !== "clip" && entry.type !== "post") {
await detachSegmentFiles(path.join(outDir, "segments"), entry.id);
}
@@ -7329,7 +7487,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// segments in, and writing one would write the other take's file).
const missing = [];
for (const [i, seg] of segs.entries()) {
- if (entries[i].type === "teaser" || isIntro(entries[i]) || (await exists(seg))) continue;
+ if (entries[i].type === "teaser" || entries[i].type === "analysis" || isIntro(entries[i]) || (await exists(seg))) continue;
if (opts.chromePreview) throw new Error(`${what} needs ${seg}, which is missing — run a full build first`);
missing.push(i);
}
@@ -7371,6 +7529,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
}
// So is the brand intro's (copied from its cache unless its key is the one recorded).
for (const [i, e] of entries.entries()) if (isIntro(e)) await buildEntrySegment(e, i);
+ // And an analysis item's (drawn from the ledger; its audio clip's sound from the cache, never fetched).
+ for (const [i, e] of entries.entries()) if (e.type === "analysis") await buildEntrySegment(e, i, { ...opts, skipFetch: true });
await linkPosts();
const schedule = await writeChromeSchedule({ manifest, entries, segments: segs, D, outDir });
EMIT("chrome", { phase: "schedule", total: schedule.total, segments: schedule.segments.length });
diff --git a/umtool/report-to-video/chrome-analysis.mjs b/umtool/report-to-video/chrome-analysis.mjs
@@ -0,0 +1,315 @@
+// THE ANALYSIS ITEM'S PAGE (module `analysis`, a segment): the plan
+// (analysis-plan.mjs) drawn full frame on the deck's ground, faces and colours
+// -- the chart of the run on the left (its grid, its month ticks, the band, the
+// mark line, one line through the points, the marks), the pace table and the
+// status rows on the right, the reading and the footnote across the foot, and,
+// with audio, the clip's citation and its QR (its picture is never shown).
+//
+// CALM, NOT A TRAILER: no slam, no hit, no camera move. The title fades in,
+// the axes and the band after it, the line draws point to point in date order
+// (each point coming up as the line reaches it, its mark after it), the pace
+// rows land one by one, then the status, then the reading.
+//
+// PURE: an entry, its context and the faces in, an HTML string out (a cue
+// interpreter, measure-draw.mjs pageHtml/cueList -- seekable from either side).
+import { colorsOf, fontStack } from "./chrome-instruments.mjs";
+import { mix, rgba } from "./chrome-deck.mjs";
+import { analysisPlan } from "./analysis-plan.mjs";
+import { cueList, esc, fmtWeight, pageHtml, r4 } from "./measure-draw.mjs";
+
+/** The motion's seconds (at full length; a short item's motion is scaled to leave ANALYSIS_MOTION.hold at the end). */
+export const ANALYSIS_MOTION = Object.freeze({
+ title: 0.5, axes: 0.3, band: 0.8, lineFrom: 0.8, line: 2.2, point: 0.3, mark: 0.35,
+ rowGap: 0.25, row: 0.35, rowRise: 10, reading: 0.5, hold: 1.5,
+});
+
+/** The frame, in the 1280x720 units the page is laid out in (scaled to the render). */
+export const ANALYSIS_BOX = Object.freeze({ x0: 70, x1: 800, y0: 150, y1: 560, panel: 850, panelR: 1230, qr: 140 });
+
+/** When each thing lands, in the item's own seconds: `{ title, axes, band, points: Map(n -> t), marks, rows: [t], reading, foot, end }`. */
+export function analysisTimes(plan) {
+ const M = ANALYSIS_MOTION;
+ const line = plan.line.map((n) => plan.pos.get(n));
+ const span = line.length > 1 ? line.reduce((s, p, i) => (i ? s + Math.hypot(p.x - line[i - 1].x, p.y - line[i - 1].y) : 0), 0) : 0;
+ const natural = M.lineFrom + M.line + 0.1 + (plan.pace.length + plan.status.length) * M.rowGap + M.row + 0.1 + M.reading + 0.2;
+ const k = Math.min(1, Math.max(0.4, (plan.seconds - M.hold) / natural));
+ const at = (v) => r4(v * k);
+ const points = new Map();
+ let walked = 0;
+ plan.line.forEach((n, i) => {
+ if (i) walked += Math.hypot(line[i].x - line[i - 1].x, line[i].y - line[i - 1].y);
+ points.set(n, at(M.lineFrom + (span ? (walked / span) * M.line : 0)));
+ });
+ // A point that is not on the line (another weight for its day): with the line's point that day.
+ for (const p of plan.points) if (!points.has(p.n)) points.set(p.n, points.get(plan.line.find((n) => plan.points[n].day === p.day)) ?? at(M.lineFrom));
+ const rowsFrom = M.lineFrom + M.line + 0.1;
+ const rows = [...plan.pace, ...plan.status].map((_, i) => at(rowsFrom + i * M.rowGap));
+ const reading = at(rowsFrom + rows.length * M.rowGap + M.row + 0.1);
+ return { k, title: 0, axes: at(0.3), band: at(M.band), points, rows, reading, foot: r4(reading + at(0.2)), end: r4(reading + at(M.reading + 0.2)) };
+}
+
+/**
+ * The page. `ctx` = `{ ledger, schema, timeline, render }` (analysis-plan.mjs); `opts` = `{ fonts, gsap, cite, qrSrc }`:
+ * the faces (instrumentFonts), the clip's citation line and its QR's asset (both null without audio).
+ */
+export function analysisHtml(entry, ctx, opts = {}) {
+ const render = ctx.render ?? {};
+ const W = Number(render.width) || 1920, H = Number(render.height) || 1080;
+ const u = W / 1280;
+ const px = (v) => Math.round(v * u * 100) / 100;
+ const fps = render.fps ?? 30;
+ const fonts = opts.fonts ?? {};
+ const C = colorsOf(render);
+ const B = ANALYSIS_BOX;
+ const plan = analysisPlan(entry, ctx, { x0: px(B.x0), x1: px(B.x1), y0: px(B.y0), y1: px(B.y1) });
+ const T = analysisTimes(plan);
+ const M = ANALYSIS_MOTION;
+ const L = cueList(fps);
+ const parts = [];
+ const show = (k, at, dur, extra = {}, ease = "power1.out") => L.add(k, at, dur, { autoAlpha: 1, ...extra }, ease);
+ const hidden = (k, extra = {}) => L.set(k, { autoAlpha: 0, ...extra });
+ const color = (c) => (c === "accent" ? C.accent : c === "amber" ? C.amber : c === "red" ? C.needle : c === "muted" ? C.muted : c === "fg" ? C.fg : c);
+ const lay = plan.layout;
+
+ // The title.
+ parts.push(`<div class="kick" data-k="kick">${esc(plan.kicker)}</div><div class="ttl" data-k="ttl">${esc(plan.title)}</div>`);
+ hidden("kick", { y: px(8) });
+ hidden("ttl", { y: px(8) });
+ show("kick", T.title, M.title, { y: 0 });
+ show("ttl", T.title + 0.1, M.title, { y: 0 });
+
+ // The axes: a rule and its figure per grid step, a tick and a name per month, the mark line.
+ const axes = [];
+ for (const g of lay.grid) axes.push(`<div class="grid" style="top:${g.y}px"></div><div class="gv" style="top:${g.y}px">${g.v}</div>`);
+ axes.push(`<div class="base" style="top:${px(B.y1)}px"></div>`);
+ for (const m of lay.months) axes.push(`<div class="mt" style="left:${m.x}px; top:${px(B.y1)}px"></div><div class="mn" style="left:${m.x}px; top:${r4(px(B.y1) + px(10))}px">${m.text}</div>`);
+ if (lay.mark !== null) axes.push(`<div class="markl" style="top:${lay.markY}px"></div><div class="gv mk" style="top:${lay.markY}px">${esc(lay.markLabel)}</div>`);
+ parts.push(`<div class="axes" data-k="axes">${axes.join("")}</div>`);
+ hidden("axes");
+ show("axes", T.axes, 0.5);
+
+ // The band.
+ if (plan.band) {
+ const bw = Math.max(px(2), plan.band.x1 - plan.band.x0);
+ parts.push(`<div class="band" data-k="band" style="left:${plan.band.x0}px; width:${r4(bw)}px"></div>`);
+ parts.push(`<div class="bandl" data-k="bandl" style="left:${r4(plan.band.x0 + bw / 2)}px">${esc(plan.band.label)}${plan.band.label ? " · " : ""}${esc(dm(plan.band.from))} – ${esc(dm(plan.band.to))}</div>`);
+ hidden("band");
+ hidden("bandl");
+ show("band", T.band, 0.6);
+ show("bandl", T.band + 0.15, 0.5);
+ }
+
+ // The line, point to point in date order; a stretch to or from a bound is quieter and dotted (the bound is no exact figure).
+ const byN = new Map(plan.points.map((p) => [p.n, p]));
+ for (let i = 1; i < plan.line.length; i += 1) {
+ const a = plan.pos.get(plan.line[i - 1]), b = plan.pos.get(plan.line[i]);
+ const loose = byN.get(plan.line[i - 1]).bound || byN.get(plan.line[i]).bound;
+ const k = `s${i}`;
+ parts.push(`<div class="seg${loose ? " loose" : ""}" data-k="${k}"></div>`);
+ L.set(k, { x: a.x, y: a.y, width: r4(Math.hypot(b.x - a.x, b.y - a.y)), rotation: r4((Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI), scaleX: 0, transformOrigin: "0% 50%" });
+ const t0 = T.points.get(plan.line[i - 1]), t1 = T.points.get(plan.line[i]);
+ L.add(k, t0, Math.max(0.05, t1 - t0), { scaleX: 1 }, "none");
+ }
+ // The points: solid, or hollow when the row is a bound (or "about"): never drawn as an exact figure.
+ for (const p of plan.points) {
+ const at = plan.pos.get(p.n);
+ const hollow = p.bound || p.qualifier === "≈";
+ parts.push(`<div class="pt${hollow ? " q" : ""}" data-k="p${p.n}"></div>`);
+ L.set(`p${p.n}`, { x: at.x, y: at.y, autoAlpha: 0, scale: 0.6 });
+ L.add(`p${p.n}`, T.points.get(p.n), M.point, { autoAlpha: 1, scale: 1 }, "power1.out");
+ }
+ // The marks: the row's figure and day, the operator's words, his quote under them -- beside the point, on the
+ // side away from the line (right of a point in the chart's first half, left and below in its second).
+ const mid = (px(B.x0) + px(B.x1)) / 2;
+ plan.marks.forEach((m, i) => {
+ const right = m.at.x > mid;
+ const style = right
+ ? `right:${r4(W - m.at.x + px(10))}px; top:${r4(m.at.y + px(10))}px; text-align:right`
+ : `left:${r4(m.at.x + px(10))}px; top:${r4(m.at.y - px(30))}px`;
+ parts.push(`<div class="mk1" data-k="m${i}" style="${style}"><div class="mt1">${esc(m.text)}</div>${m.quote ? `<div class="mq">“${esc(m.quote)}”</div>` : ""}</div>`);
+ hidden(`m${i}`);
+ show(`m${i}`, r4(T.points.get(m.n) + 0.15), M.mark);
+ });
+
+ // The pace table and the status rows: each lands (a short rise and a fade), one after another.
+ const rows = [];
+ plan.pace.forEach((x) => {
+ const sub = [`${x.days} days`, x.note, x.bound ? boundNote(x) : ""].filter(Boolean).join(" · ");
+ rows.push(`<div class="row"><div class="l"><div class="lt">${esc(x.span.toUpperCase())}</div><div class="ls">${esc(sub)}</div></div>` +
+ `<div class="v${x.bound ? " b" : ""}">${paceFigure(x)}</div></div>`);
+ });
+ plan.status.forEach((x) => {
+ rows.push(`<div class="row"><div class="l"><div class="lt">${esc(x.label)}</div>${x.note ? `<div class="ls">${esc(x.note)}</div>` : ""}</div>` +
+ `<div class="v st" style="color:${esc(color(x.color))}">${esc(x.value)}</div></div>`);
+ });
+ parts.push(`<div class="side">${rows.map((r, i) => r.replace('<div class="row">', `<div class="row" data-k="r${i}">`)).join("")}</div>`);
+ rows.forEach((_, i) => {
+ hidden(`r${i}`, { y: px(M.rowRise) });
+ show(`r${i}`, T.rows[i], M.row, { y: 0 }, "power2.out");
+ });
+
+ // The reading, the footnote, and with audio the clip's citation and its code.
+ const narrow = !!opts.qrSrc;
+ parts.push(`<div class="foot${narrow ? " narrow" : ""}"><div class="rd" data-k="rd">${esc(plan.reading)}</div>` +
+ `${plan.footnote ? `<div class="fn" data-k="fn">${esc(plan.footnote)}</div>` : ""}` +
+ `${opts.cite ? `<div class="ci" data-k="ci">${esc(opts.cite)}</div>` : ""}</div>`);
+ hidden("rd");
+ show("rd", T.reading, M.reading);
+ if (plan.footnote) { hidden("fn"); show("fn", T.foot, M.reading); }
+ if (opts.cite) { hidden("ci"); show("ci", T.foot, M.reading); }
+ if (opts.qrSrc) {
+ parts.push(`<img class="qr" data-k="qr" src="${esc(opts.qrSrc)}" alt="">`);
+ hidden("qr");
+ show("qr", T.foot, M.reading);
+ }
+
+ const { init, cues } = L.build();
+ const css = `
+ .bg { position: absolute; inset: 0; background: ${C.bg}; }
+ .kick { position: absolute; left: ${px(B.x0)}px; top: ${px(36)}px; font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(20)}px;
+ letter-spacing: 0.14em; color: ${C.muted}; white-space: nowrap; }
+ .ttl { position: absolute; left: ${px(B.x0)}px; top: ${px(62)}px; font-family: ${fontStack(fonts, "display")}; font-size: ${px(40)}px;
+ color: ${C.fg}; white-space: nowrap; }
+ .axes { position: absolute; inset: 0; }
+ .grid, .base, .markl { position: absolute; left: ${px(B.x0)}px; width: ${r4(px(B.x1) - px(B.x0))}px; height: 0; border-top: 1px solid ${C.rule}; }
+ .base { border-top-color: ${mix(C.bg, C.fg, 0.28)}; }
+ .markl { border-top: ${px(1.5)}px dashed ${rgba(C.accent, 0.7)}; }
+ .gv { position: absolute; right: ${r4(W - px(B.x0) + px(10))}px; transform: translateY(-50%); font-family: ${fontStack(fonts, "condensed")};
+ font-size: ${px(15)}px; color: ${C.muted}; letter-spacing: 0.04em; }
+ .gv.mk { color: ${C.accent}; font-family: ${fontStack(fonts, "bold")}; }
+ .mt { position: absolute; width: 1px; height: ${px(6)}px; background: ${mix(C.bg, C.fg, 0.28)}; }
+ .mn { position: absolute; transform: translateX(-50%); font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(15)}px;
+ color: ${C.muted}; letter-spacing: 0.08em; white-space: nowrap; }
+ .band { position: absolute; top: ${px(B.y0)}px; height: ${r4(px(B.y1) - px(B.y0))}px; background: ${rgba(C.amber, 0.13)}; }
+ .bandl { position: absolute; top: ${px(B.y0 - 24)}px; transform: translateX(-50%); font-family: ${fontStack(fonts, "condensed")};
+ font-size: ${px(15)}px; letter-spacing: 0.08em; color: ${C.amber}; white-space: nowrap; }
+ .seg { position: absolute; left: 0; top: 0; height: ${px(3)}px; margin-top: -${px(1.5)}px; background: ${C.accent}; border-radius: ${px(2)}px; }
+ .seg.loose { height: 0; margin-top: -${px(1)}px; background: none; border-top: ${px(2)}px dotted ${rgba(C.accent, 0.7)}; border-radius: 0; }
+ .pt { position: absolute; left: 0; top: 0; width: ${px(8)}px; height: ${px(8)}px; margin: -${px(4)}px 0 0 -${px(4)}px; border-radius: 50%; background: ${C.accent}; }
+ .pt.q { width: ${px(11)}px; height: ${px(11)}px; margin: -${px(5.5)}px 0 0 -${px(5.5)}px; background: ${C.bg}; border: ${px(2)}px solid ${C.accent}; }
+ .mk1 { position: absolute; max-width: ${px(420)}px; }
+ .mt1 { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(15)}px; color: ${C.fg}; white-space: nowrap; }
+ .mq { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(14)}px; color: ${C.amber}; font-style: italic; margin-top: ${px(2)}px; }
+ .side { position: absolute; left: ${px(B.panel)}px; width: ${px(B.panelR - B.panel)}px; top: ${px(B.y0)}px; }
+ .row { display: flex; justify-content: space-between; align-items: center; padding: ${px(10)}px 0; border-bottom: 1px solid ${C.rule}; }
+ .row .lt { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(17)}px; letter-spacing: 0.05em; color: ${C.muted}; white-space: nowrap; }
+ .row .ls { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(14)}px; color: ${C.muted}; margin-top: ${px(3)}px; white-space: nowrap; }
+ .row .v { font-family: ${fontStack(fonts, "display")}; font-size: ${px(30)}px; color: ${C.fg}; white-space: nowrap; text-align: right; }
+ .row .v.b { color: ${mix(C.bg, C.fg, 0.82)}; }
+ .row .v.st { font-size: ${px(28)}px; }
+ .row .bw { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(15)}px; letter-spacing: 0.08em; color: ${C.muted}; }
+ .row .bw.ab { margin-right: ${px(8)}px; vertical-align: ${px(4)}px; }
+ .row .bt { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(17)}px; color: ${C.muted}; margin-left: ${px(4)}px; }
+ .foot { position: absolute; left: ${px(B.x0)}px; right: ${px(1280 - B.panelR)}px; top: ${px(604)}px; }
+ .foot.narrow { right: ${px(1280 - B.panelR + B.qr + 24)}px; }
+ .rd { font-family: ${fontStack(fonts, "regular")}; font-size: ${px(24)}px; line-height: 1.3; color: ${C.fg}; }
+ .fn { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(15)}px; color: ${C.muted}; margin-top: ${px(6)}px; }
+ .ci { font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(14)}px; color: ${C.muted}; margin-top: ${px(4)}px; letter-spacing: 0.03em; }
+ .qr { position: absolute; left: ${px(B.panelR - B.qr)}px; top: ${px(720 - 16 - B.qr)}px; width: ${px(B.qr)}px; height: ${px(B.qr)}px; }`;
+ return pageHtml({
+ id: "analysis", W, H, fps, fonts, gsap: opts.gsap,
+ data: { total: plan.seconds, window: null, init, cues },
+ css,
+ body: `<div class="bg"></div>${parts.join("")}${measureScript(W, H)}`,
+ });
+}
+
+const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+const dm = (iso) => {
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso ?? ""));
+ return m ? `${Number(m[3])} ${MON[Number(m[2]) - 1]}`.toUpperCase() : "";
+};
+
+/**
+ * A pace row's figure: exact, the signed change; "about" before an approximate one; a bound in words, unsigned --
+ * "MORE THAN" / "AT MOST" over the figure, "lost" / "gained" after it (analysis-plan.mjs paceWords).
+ */
+function paceFigure(x) {
+ if (x.lead === "about") return `<span class="bw ab">about</span>${esc(x.figure)}`;
+ if (x.lead) return `<div class="bw">${esc(x.lead)}</div><div>${esc(x.figure)}<span class="bt">${esc(x.tail)}</span></div>`;
+ return esc(x.figure);
+}
+
+/**
+ * THE PAGE MEASURED (the build's check, `?measure`): at the item's last frame, every text box and the code
+ * against the frame and each other -- a box leaving the frame, a row's words and figure overlapping or the row
+ * wider than the panel, the table running into the reading, the QR or the citation over the table, the reading or
+ * the footnote, a mark over the table -- written as `data-measure` (a JSON list of sentences) on the root.
+ */
+function measureScript(W, H) {
+ return `<script data-measure="">
+ (function () {
+ if (new URLSearchParams(location.search).get("measure") === null) return;
+ addEventListener("load", function () {
+ (document.fonts ? document.fonts.ready : Promise.resolve()).then(function () {
+ var tl = window.__timelines && window.__timelines["analysis"];
+ if (tl) tl.seek(tl.duration(), false);
+ var W = ${W}, H = ${H}, P = [];
+ var R = function (el) { return el.getBoundingClientRect(); };
+ var hit = function (a, b) { return a.width > 0 && b.width > 0 && a.left < b.right - 0.5 && b.left < a.right - 0.5 && a.top < b.bottom - 0.5 && b.top < a.bottom - 0.5; };
+ var named = [];
+ var add = function (sel, name) { document.querySelectorAll(sel).forEach(function (el, i) { named.push({ el: el, name: name.replace("#", String(i)) }); }); };
+ add(".kick", "the kicker"); add(".ttl", "the title"); add(".bandl", "the band's label"); add(".mk1", "marks[#]");
+ add(".side .row", "table row #"); add(".rd", "the reading"); add(".fn", "the footnote"); add(".ci", "the citation"); add(".qr", "the QR");
+ named.forEach(function (x) {
+ var r = R(x.el);
+ if (r.width > 0 && (r.left < -0.5 || r.top < -0.5 || r.right > W + 0.5 || r.bottom > H + 0.5)) P.push(x.name + " leaves the frame");
+ });
+ document.querySelectorAll(".side .row").forEach(function (row, i) {
+ if (row.scrollWidth > row.clientWidth + 1) P.push("table row " + i + " is wider than the panel (clipped)");
+ var l = row.querySelector(".l"), v = row.querySelector(".v");
+ if (l && v && R(l).right > R(v).left + 0.5) P.push("table row " + i + ": its words and its figure overlap");
+ });
+ var rows = Array.prototype.slice.call(document.querySelectorAll(".side .row"));
+ var foot = ["rd", "fn", "ci"].map(function (k) { return document.querySelector("." + k); }).filter(Boolean);
+ var last = rows[rows.length - 1];
+ foot.forEach(function (f) { if (last && R(last).bottom > R(f).top + 0.5 && hit(R(document.querySelector(".side")), R(f))) P.push("the table runs into " + (f.className === "rd" ? "the reading" : f.className === "fn" ? "the footnote" : "the citation")); });
+ var qr = document.querySelector(".qr"), ci = document.querySelector(".ci");
+ [qr, ci].filter(Boolean).forEach(function (q) {
+ var qn = q === qr ? "the QR" : "the citation";
+ rows.forEach(function (row, i) { if (hit(R(q), R(row))) P.push(qn + " overlaps table row " + i); });
+ foot.forEach(function (f) { if (f !== q && hit(R(q), R(f))) P.push(qn + " overlaps " + (f.className === "rd" ? "the reading" : f.className === "fn" ? "the footnote" : "the citation")); });
+ });
+ var side = document.querySelector(".side");
+ document.querySelectorAll(".mk1").forEach(function (m, i) { if (side && hit(R(m), R(side))) P.push("marks[" + i + "] runs into the table"); });
+ document.documentElement.setAttribute("data-measure", JSON.stringify(P));
+ });
+ });
+ })();
+</script>`;
+}
+
+/** The measure's sentences from a page's dumped DOM (`data-measure`), or null when the page did not measure. */
+export function measuredProblems(dom) {
+ const m = /<html[^>]*\sdata-measure="([^"]*)"/.exec(String(dom ?? ""));
+ if (!m) return null;
+ const json = m[1].replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
+ try {
+ const v = JSON.parse(json);
+ return Array.isArray(v) ? v.map(String) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The words under a bounded pace row: which end is a bound, as he said it ("to < 300"). */
+function boundNote(x) {
+ const end = (e) => `${e.qualifier} ${fmtWeight(e.value)}`;
+ const ends = [];
+ if (x.boundRows.includes(x.from.row)) ends.push(`from ${end(x.from)}`);
+ if (x.boundRows.includes(x.to.row)) ends.push(`to ${end(x.to)}`);
+ return ends.join(", ");
+}
+
+/**
+ * The clip's citation as the page prints it: "HEARD: <channel> · <title> · <date> · <m:ss>" from attributionParts'
+ * parts (attribution.mjs) -- the build's own, with the source's metadata when it has it.
+ */
+export function analysisCite(parts) {
+ if (!parts) return null;
+ const at = Number(parts.at);
+ const clock = Number.isFinite(at)
+ ? `${Math.floor(at / 3600) ? `${Math.floor(at / 3600)}:${String(Math.floor((at % 3600) / 60)).padStart(2, "0")}` : Math.floor(at / 60)}:${String(Math.floor(at % 60)).padStart(2, "0")}`
+ : "";
+ return ["HEARD:", [parts.channel, parts.title, parts.date, clock].filter((x) => x && String(x).trim()).join(" · ")].join(" ");
+}
diff --git a/umtool/report-to-video/chrome-analysis.test.mjs b/umtool/report-to-video/chrome-analysis.test.mjs
@@ -0,0 +1,112 @@
+// The analysis item's page (chrome-analysis.mjs): the plan's figures and nothing else, calm motion (no slam, no
+// overshoot, nothing grows past its size), a bound drawn hollow, the clip's citation and code only with audio.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+import { analysisCite, analysisHtml, analysisTimes } from "./chrome-analysis.mjs";
+import { analysisPlan } from "./analysis-plan.mjs";
+
+const SCHEMA = {
+ kind: "measure", unit: "lb", bandGapDays: 60,
+ tracks: [{ key: "weight", role: "value", label: "Weight" }],
+ fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], render: "cell" }],
+};
+const W = (id, population, date, value, extra = {}) => ({ id, scope: "weight", population, date, value, ...extra });
+const LEDGER = [
+ W("w83", "delta", "2026-07-23", -5),
+ W("w91", "past", "2026-08-03", 349, { asOf: "2026-07-19" }),
+ W("w104", "delta", "2026-09-04", -31.5),
+ W("w110", "current", "2026-09-24", 310.5),
+ W("w115", "current", "2026-10-15", 300, { qualifier: "<" }),
+ W("w118", "current", "2026-10-26", 291.5, { asOf: "2026-10-23" }),
+ W("w137", "current", "2026-11-07", 288.5),
+];
+const CTX = {
+ ledger: LEDGER, schema: SCHEMA, render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#0f1311", fg: "#edf0ec" } },
+ timeline: [{ type: "clip", id: "c46", video: "v1", start: 100, end: 160 }],
+};
+const ITEM = {
+ type: "analysis", id: "an1", title: "What his own numbers say", kicker: "THE RUN",
+ series: { rows: ["w91", "w104", "w110", "w115", "w118", "w137"] },
+ band: { from: "2026-10-23", to: "2026-11-07", label: "WORLD SERIES" },
+ marks: [{ row: "w118", label: "offers the scale video" }],
+ pace: [{ from: "w110", to: "w115" }, { from: "w115", to: "w118" }],
+ status: [{ label: "SCALE VIDEO", value: "NOT POSTED", note: "offered 23 Oct", color: "red" }],
+ reading: "The loss is steady.", footnote: "His own statements.", mark: { row: "w115" },
+};
+const dataOf = (html) => JSON.parse(/<script id="analysis-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+
+test("the page draws the plan's figures, a bound hollow and its pace rows in words", () => {
+ const html = analysisHtml(ITEM, CTX);
+ assert.match(html, /data-duration="7"/);
+ assert.match(html, /What his own numbers say/);
+ assert.match(html, /<div class="bw">MORE THAN<\/div><div>10\.5 lb<span class="bt">lost<\/span><\/div>/);
+ assert.match(html, /<div class="bw">AT MOST<\/div><div>8\.5 lb<span class="bt">lost<\/span><\/div>/);
+ assert.doesNotMatch(html, /−10\.5|−8\.5/);
+ // The dashed line at w115's value, labelled with it.
+ assert.match(html, /<div class="gv mk" style="top:[\d.]+px">300<\/div>/);
+ assert.match(html, /21 days · to < 300/);
+ assert.match(html, /8 days · from < 300/);
+ assert.match(html, /291\.5 · 23 Oct · offers the scale video/);
+ assert.match(html, /NOT POSTED/);
+ const plan = analysisPlan(ITEM, CTX);
+ const bound = plan.points.find((p) => p.row === "w115");
+ assert.match(html, new RegExp(`class="pt q" data-k="p${bound.n}"`));
+ assert.equal((html.match(/class="pt q"/g) ?? []).length, 1);
+ // The stretches to and from the bound are dotted: never an exact line through it.
+ assert.equal((html.match(/class="seg loose"/g) ?? []).length, 2);
+ // No audio: no citation, no code.
+ assert.doesNotMatch(html, /class="qr"|class="ci"/);
+});
+
+test("calm: no overshoot ease, nothing scaled past its size, every cue inside the item", () => {
+ const html = analysisHtml(ITEM, CTX);
+ const { cues, init } = dataOf(html);
+ assert.ok(cues.length > 10);
+ for (const c of cues) {
+ assert.doesNotMatch(String(c.ease), /back|elastic|bounce/, `${c.k} eases ${c.ease}`);
+ if (c.to.scale !== undefined) assert.ok(c.to.scale <= 1, `${c.k} scales to ${c.to.scale}`);
+ assert.ok(c.at + c.dur <= 7 + 1e-6, `${c.k} ends at ${c.at + c.dur}`);
+ }
+ for (const [k, v] of Object.entries(init)) if (v.scale !== undefined) assert.ok(v.scale <= 1, k);
+});
+
+test("the line reaches each point in date order; the rows land after it, the reading last", () => {
+ const plan = analysisPlan(ITEM, CTX);
+ const T = analysisTimes(plan);
+ const ts = plan.line.map((n) => T.points.get(n));
+ assert.deepEqual([...ts].sort((a, b) => a - b), ts);
+ assert.ok(T.rows[0] >= ts.at(-1));
+ assert.ok(T.reading > T.rows.at(-1));
+ assert.ok(T.end <= plan.seconds);
+});
+
+test("a short silent item's motion is scaled to leave its hold", () => {
+ const plan = analysisPlan({ ...ITEM, seconds: 5 }, CTX);
+ const T = analysisTimes(plan);
+ assert.ok(T.k < 1);
+ assert.ok(T.end <= 5 - 1 + 1e-6, `ends ${T.end}`);
+});
+
+test("with audio: the citation line and the code", () => {
+ const html = analysisHtml({ ...ITEM, audio: { clip: "c46", start: 110, end: 124.5 } }, CTX, {
+ cite: analysisCite({ channel: "chan", title: "A stream", date: "2026-10-26", at: 4112.6 }), qrSrc: "assets/qr00.png",
+ });
+ assert.match(html, /data-duration="14\.5"/);
+ assert.match(html, /HEARD: chan · A stream · 2026-10-26 · 1:08:32/);
+ assert.match(html, /<img class="qr" data-k="qr" src="assets\/qr00\.png"/);
+ assert.match(html, /\.foot\.narrow/);
+});
+
+test("deterministic", () => {
+ assert.equal(analysisHtml(ITEM, CTX), analysisHtml(ITEM, CTX));
+});
+
+test("the page measures itself under ?measure (the build's check), and the dump is read back", async () => {
+ const { measuredProblems } = await import("./chrome-analysis.mjs");
+ const html = analysisHtml(ITEM, CTX);
+ assert.match(html, /<script data-measure="">/);
+ assert.equal(measuredProblems("<html lang=\"en\" data-measure=\"["the reading leaves the frame"]\"><body></body></html>")[0], "the reading leaves the frame");
+ assert.deepEqual(measuredProblems('<html data-fit="1" data-measure="[]">'), []);
+ assert.equal(measuredProblems("<html><body></body></html>"), null);
+});
diff --git a/umtool/report-to-video/chrome-instruments.mjs b/umtool/report-to-video/chrome-instruments.mjs
@@ -38,7 +38,7 @@ export const INSTRUMENT_MOTION = Object.freeze({
/** The faces a measure page draws in: the deck's, and the manifest's display and condensed faces when it names them. */
export const INSTRUMENT_FONTS = Object.freeze({ display: "MeasureDisplay", condensed: "MeasureCond" });
-const fontStack = (fonts, which) =>
+export const fontStack = (fonts, which) =>
which === "display"
? `'${fonts.MeasureDisplay ? "MeasureDisplay" : "DeckSansBold"}', sans-serif`
: which === "condensed"
@@ -46,7 +46,7 @@ const fontStack = (fonts, which) =>
: which === "bold" ? "'DeckSansBold', sans-serif" : "'DeckSans', sans-serif";
/** The palette roles every instrument draws in. */
-function colorsOf(render, dial = resolveDial(render)) {
+export function colorsOf(render, dial = resolveDial(render)) {
const pal = render.palette ?? {};
const bg = pal.bg ?? "#0f1311", fg = pal.fg ?? "#edf0ec";
return {
diff --git a/umtool/report-to-video/clip-audio.mjs b/umtool/report-to-video/clip-audio.mjs
@@ -63,8 +63,9 @@ export function validateClipAudio(audio, where = "audio") {
export function validateClipAudioEntries(manifest) {
const errors = [];
(manifest?.timeline ?? []).forEach((e, i) => {
- // A video entry's `audio` (bass, gain) is its own: video-entry.mjs validates it.
- if (e?.audio === undefined || e?.type === "video") return;
+ // A video entry's `audio` (bass, gain) is its own: video-entry.mjs validates it. So is an analysis item's
+ // (`{clip, start, end}`: the clip whose sound plays under it -- analysis-plan.mjs validates it).
+ if (e?.audio === undefined || e?.type === "video" || e?.type === "analysis") return;
const where = `timeline[${i}] (${e.id ?? "?"}).audio`;
if (e.type && e.type !== "clip") { errors.push(`${where}: only a clip's sound has these settings`); return; }
errors.push(...validateClipAudio(e.audio, where));
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -743,11 +743,11 @@ export async function fxThumbs(schedule, base, render, assetsDir) {
* handed what it may touch -- the faces, the QR maker, the shots -- as
* helpers, so a module never reaches into the file system itself.
*/
-async function regionHtml(region, { manifest, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, teaser, transition }) {
+async function regionHtml(region, { manifest, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, teaser, transition, context = null }) {
const mod = regionModule(region);
const render = manifest.render;
return mod.page({
- manifest, render, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, entry: teaser, transition,
+ manifest, render, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, entry: teaser, transition, context,
fonts: (names, opts) => copyFonts(render, assetsDir, names, opts),
qrs: (urls, size) => qrPngsFor(urls, render, size, assetsDir),
// `threads`, a Set: the posts whose thread shot was drawn in place of their shot are added to it.
@@ -862,6 +862,10 @@ export function runRenderer(cmd, args) {
* lead is the dissolve and the black): the build passes its own, so a
* `--no-xfade` build composes the lead it plays; default the manifest's.
*
+ * Analysis (`region: "analysis"`, `segment` = the entry's id): as the teaser,
+ * `chrome/analysis-<id>/`; `context` (`{ meta }`, the build's source metadata
+ * of its audio clip) names the clip on its citation line.
+ *
* `schedule` (an object) overrides reading `out/<variant>/schedule.json`.
*
* @returns {Promise<{ projDir: string, frames: string|null, still: string|null,
@@ -873,7 +877,7 @@ export async function composeChrome({
schedule = null, preview = false, doRender = false,
fps = null, workers = null, quality = "high", format = "png-sequence",
still = null, png = null, from = 0, duration = null, window = null, segment = null, transition = null,
- lease = null, want = null, render: renderOverride = null,
+ lease = null, want = null, render: renderOverride = null, context = null,
}) {
// The variant's view, and its own out directory. Handed the whole manifest
// the band would draw claims this cut never makes, and the deck would name
@@ -944,7 +948,7 @@ export async function composeChrome({
// keys hold only while it is shown (frame-keys.mjs).
const drawn = await regionHtml(region, {
manifest, manifestDir: path.dirname(path.resolve(manifestPath)), base, projDir, assetsDir, schedule: sched,
- duration: duration != null ? Number(duration) : null, from, window: win, teaser, transition: D,
+ duration: duration != null ? Number(duration) : null, from, window: win, teaser, transition: D, context,
});
const html = typeof drawn === "string" ? drawn : drawn.html;
const pageItems = typeof drawn === "string" ? null : drawn.items ?? null;
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -24,6 +24,7 @@ import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs";
import { attributionParts, deckSubtitle, deckSubtitleLines, deckSubtitleLinesParts, deckSubtitleParts, formatDeckDate, hms } from "./attribution.mjs";
import { panelEntry, postDeckText, postItemSeconds, postLayout } from "./post-item.mjs";
+import { analysisSeconds } from "./analysis-plan.mjs";
import { videoDip, videoEnter, videoHidesChrome, videoSeconds } from "./video-entry.mjs";
import {
claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, rawMarksOf, tallyCells, tallyOf, validateFactcheck,
@@ -1215,6 +1216,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render))
if (entry.type === "intro") return Number(entry.seconds ?? INTRO_SECONDS);
// A teaser's dip makes its segment longer by the dissolve and the black (`teaserLead`).
if (entry.type === "teaser") return teaserSeconds(entry, D, render.fps ?? 30);
+ // An analysis item (analysis-plan.mjs): its audio's span, else its silent seconds.
+ if (entry.type === "analysis") return analysisSeconds(entry);
// A narrated card's `"auto"` is its words' length, estimated until a build measures it.
if (hasNarration(entry)) return estimatedNarratedCardSeconds(entry, render);
return Number(entry.seconds ?? 5);
@@ -1266,6 +1269,8 @@ export function hidesDeck(entry, deck) {
// A teaser that counts keeps the deck up over it (teaserCounts).
if (entry.type === "teaser") return !teaserCounts(entry);
if (entry.type === "intro") return true;
+ // An analysis item is the whole frame (analysis-plan.mjs): its page is its own ground.
+ if (entry.type === "analysis") return true;
// A video entry is the whole frame, nothing over it -- unless it says `deck: "shown"`.
if (entry.type === "video") return videoHidesChrome(entry);
return deck.overCards === "hide" && CARD_TYPES.includes(entry.type);
@@ -1325,6 +1330,10 @@ export function deckText(entry, meta, provenance, deck, multiChannel) {
// so the deck says only what its `onscreen` says.
if (!title && !teaserCounts(entry)) title = teaserTitle(entry);
subtitle = "";
+ } else if (entry.type === "analysis") {
+ // An analysis item: its title names it (the deck is not up over it).
+ if (!title) title = String(entry.title ?? "").trim();
+ subtitle = "";
} else if (entry.type === "post") {
// A post item: its day as the deck's date, its author and platform under it.
const t = postDeckText(entry, (d) => formatDeckDate(d, deck.subtitle?.dateFormat ?? "long"));
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -36,6 +36,10 @@
// - a `drafted` mark that is malformed or where no field may be drafted, and
// a `publish` block that is not `{ youtube: { title, description } }`
// (drafted.mjs `validateDrafted`, `validatePublish`);
+// - an analysis item's refusals (analysis-plan.mjs), each naming its row: a
+// row not in the ledger, a band outside the series, a pace end missing, an
+// empty reading, an audio clip unknown or a span outside its window, held
+// over 8 s without audio, a vertical cut;
// - a narrated card whose `seconds` is a number shorter than its narration
// needs (the lead, the words, the tail). The words' length is known once
// the voice is synthesized: the build checks it then, and `--lint` reads
@@ -51,6 +55,8 @@
// first tier, or any line's break: house style, not a fit. (A title's
// first tier is held to the same 34 by the frame itself, TEASER_LIMITS.fit,
// and validateTeasers refuses it.)
+// - an analysis item's pace row ending on a bound (drawn over/under), a
+// number typed into its words, its audio span heard twice in the cut;
// - a QR under WARN_QR_PX_PER_MODULE_720P pixels per module at 720p: it
// scans on a good screen with a steady hand, not reliably.
// - a promise outcome's `stampNote` (a ledger row's words under its stamp on the promise clock) longer than
@@ -110,6 +116,8 @@ import { validateTransitionStyle } from "./transition.mjs";
import { validateLook } from "./look.mjs";
// The stacked vertical deck (vertical-deck.mjs): what it leaves out, and a twocrop band drawn past its source's pixels.
import { stackedLeftOut } from "./modules/index.mjs";
+import { analysisSource, analysisWarnings, validateAnalysisEntries } from "./modules/analysis.mjs";
+import { ANALYSIS_BOX } from "./chrome-analysis.mjs";
import { verticalOn, verticalRender } from "./vertical.mjs";
import { ENLARGE_WARN, STACKED_QR_SHARE, STACKED_QR_SMALL_SHARE, clipTwoCrop, stackedOn, twoCropEnlargement } from "./vertical-deck.mjs";
import { roomWindowWarnings } from "./room.mjs";
@@ -186,6 +194,11 @@ export function qrsOf(manifest, { only = null, metaOf = null } = {}) {
// A basic-mode cut is the footage alone (basic.mjs): it draws no code, so none is measured -- nor counted as built
// from the origin (originQrsOf, the Inbox's Blocking siteOrigin card: a quick clip on no public site raises none).
if (basicOn(render)) return out;
+ // An analysis item's code (chrome-analysis.mjs): its audio clip's, drawn on its own page whatever the chrome.
+ for (const e of timeline) {
+ const src = e.type === "analysis" ? analysisSource(e, manifest) : null;
+ if (src?.url) out.push({ where: `timeline ${e.id} (the analysis item's QR)`, id: e.id, source: "entry", url: src.url, px: Math.round((ANALYSIS_BOX.qr * (Number(render.width) || 1920)) / 1280) });
+ }
if (deckOn(render)) {
const d = resolveDeck(render);
if (d.qr?.show) {
@@ -337,6 +350,8 @@ export function validatorErrors(whole) {
...validateTransitionStyle(whole),
// Release 36: render.captions, render.loudness and a clip's vertical crop.
...validateLook(whole),
+ // An analysis item (analysis-plan.mjs): its rows in the ledger, its band, pace, audio and length.
+ ...validateAnalysisEntries(whole),
// The deck finale: each entry's `layout` and the one run (finale.mjs).
...validateFinaleEntries(whole),
// A clip's blurred picture and the cut's render.blur (clip-blur.mjs).
@@ -462,6 +477,8 @@ export function lintManifest(manifest, {
warnings.push(...stackedLintWarnings(manifest, { only }));
// A promise outcome's own stamp words (a ledger row's `stampNote`) longer than the stamp's line holds.
if (!only) warnings.push(...stampNoteWarnings(whole));
+ // An analysis item: a bound pace row, a number typed into words, its audio heard twice (analysis-plan.mjs).
+ warnings.push(...analysisWarnings(manifest, { only }));
for (const { where, src } of imageSrcsOf(manifest, { only })) {
if (path.isAbsolute(src) || src.startsWith("~")) {
diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs
@@ -191,6 +191,47 @@ export function lossRuns(rows, schema) {
return { runs, runOf, claims: claims.map((c) => ({ id: c.id, date: c.date, run: runOf.get(c.id) })), total: r1(runs.reduce((n, r) => n + r.peak, 0)) };
}
+/**
+ * THE RUN'S START on day `d`, when the record names one: `{ value, row, date }`
+ * or null. The run open on `d` is the run of his last loss claim on or before
+ * it, within bandGapDays, else of his next one within bandGapDays (a day as a
+ * run begins); its start is a remembered weight about a day within
+ * bandGapDays before the run's first claim, said by `d` (the latest said
+ * wins). A loss goal's base (measureSlice) and an analysis item's deltas
+ * (analysis-plan.mjs) both read it.
+ *
+ * @param {string} d
+ * @param {{ readings: any[], lossClaims: Array<{ id: string, date: string, run: number }>, runById: Map<number, { start: string }>, bandGapDays: number }} ctx
+ * `readings` his value-track current/past rows, chronological; `lossClaims` and `runById` lossRuns' over his usable rows.
+ */
+export function runStartAt(d, { readings, lossClaims, runById, bandGapDays }) {
+ let run = null;
+ const before = lossClaims.filter((c) => dateKey(c.date) <= dateKey(d)).pop();
+ if (before && Math.round(daysBetween(before.date, d)) <= bandGapDays) run = runById.get(before.run) ?? null;
+ else {
+ const after = lossClaims.find((c) => dateKey(c.date) > dateKey(d));
+ if (after && Math.round(daysBetween(d, after.date)) <= bandGapDays) run = runById.get(after.run) ?? null;
+ }
+ if (!run) return null;
+ const starts = readings.filter((r) => r.population === "past" && r.asOf && dateKey(r.date) <= dateKey(d) &&
+ dateKey(r.asOf) <= dateKey(run.start) && Math.round(daysBetween(r.asOf, run.start)) <= bandGapDays);
+ const last = starts[starts.length - 1];
+ return last ? { value: Number(last.value), row: last.id, date: last.date ?? null } : null;
+}
+
+/**
+ * runStartAt over a ledger: `rows` every row (only his own on the value track
+ * are read, as measureSlice reads them), `schema` the ledger's.
+ */
+export function runStartOf(rows, schema, d) {
+ const s = measureSchema(schema);
+ const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null;
+ const own = (rows ?? []).filter((r) => isObj(r) && typeof r.id === "string" && speakerOf(r) === null);
+ const { runs, claims } = lossRuns(own.filter(isUsable), s);
+ const readings = chronological(own.filter((r) => r.scope === valueTrack && (r.population === "current" || r.population === "past") && Number.isFinite(Number(r.value))));
+ return runStartAt(d, { readings, lossClaims: claims, runById: new Map(runs.map((r) => [r.run, r])), bandGapDays: s.bandGapDays });
+}
+
// ---------------------------------------------------------------------------
// A row as an event
// ---------------------------------------------------------------------------
@@ -480,20 +521,9 @@ export function measureSlice(manifest, schedule, opts = {}) {
/**
* A loss goal's target weight: against the start of the run open when he
- * set it, when the record knows that start -- a remembered weight about a
- * day within bandGapDays before the run's first claim, said by the goal's
- * date (the latest said wins) -- else against the last weight he stated by
- * then, else none (his words stay the goal). The run open when he set it:
- * the run of his last loss claim before it, within bandGapDays, else of his
- * next one within bandGapDays (a goal set as a run begins).
+ * set it, when the record knows that start (runStartAt) -- else against the
+ * last weight he stated by then, else none (his words stay the goal).
*/
- const runAt = (d) => {
- const before = lossClaims.filter((c) => dateKey(c.date) <= dateKey(d)).pop();
- if (before && Math.round(daysBetween(before.date, d)) <= s.bandGapDays) return runById.get(before.run) ?? null;
- const after = lossClaims.find((c) => dateKey(c.date) > dateKey(d));
- if (after && Math.round(daysBetween(d, after.date)) <= s.bandGapDays) return runById.get(after.run) ?? null;
- return null;
- };
// A loss goal's base (rev 9, 6 Nov): the run's start when the record names one;
// else the latest weight he gave by the goal's date -- stated or remembered,
// by the day it was his weight (a remembered one's asOf); else none. A target
@@ -501,13 +531,8 @@ export function measureSlice(manifest, schedule, opts = {}) {
// not 140 lb): his words stay the goal -- "LOSE 100", no weight, no tick.
const goalBase = (row) => {
const d = row.date;
- const run = runAt(d);
- if (run) {
- const starts = readings.filter((r) => r.population === "past" && r.asOf && dateKey(r.date) <= dateKey(d) &&
- dateKey(r.asOf) <= dateKey(run.start) && Math.round(daysBetween(r.asOf, run.start)) <= s.bandGapDays);
- const last = starts[starts.length - 1];
- if (last) return { value: Number(last.value), row: last.id, from: "runStart", date: last.date ?? null };
- }
+ const start = runStartAt(d, { readings, lossClaims, runById, bandGapDays: s.bandGapDays });
+ if (start) return { value: start.value, row: start.row, from: "runStart", date: start.date };
const known = readings
.filter((r) => dateKey(r.date) <= dateKey(d))
.sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || dateKey(a.date).localeCompare(dateKey(b.date)));
diff --git a/umtool/report-to-video/modules/analysis.mjs b/umtool/report-to-video/modules/analysis.mjs
@@ -0,0 +1,73 @@
+// THE ANALYSIS ITEM (module `analysis`, a segment): an ending built from the
+// ledger -- a chart of a named run of his weights, a pace table, a status row
+// and one reading line -- inserted into the cut as a timeline entry of its own
+// (`{ type: "analysis" }`, analysis-plan.mjs). chrome-analysis.mjs writes the
+// page; the build encodes its frames into segments/<id>.mp4 with the sound of
+// the clip it names under it, or silence (build-video's buildAnalysisSegment).
+import { analysisContext, analysisProblems, analysisSeconds, validateAnalysisEntries } from "../analysis-plan.mjs";
+import { attributionParts } from "../attribution.mjs";
+import { deckQrUrl, resolveDeck } from "../deck.mjs";
+import { defineModule } from "./contract.mjs";
+import { instrumentFonts } from "./instruments-shared.mjs";
+
+export { analysisContext, analysisWarnings, validateAnalysisEntries } from "../analysis-plan.mjs";
+
+/**
+ * The audio clip's citation parts and QR link: the clip at the audio's start -- with the source's metadata when the
+ * build has it (`meta`), else the entry's own words. Null without audio.
+ */
+export function analysisSource(entry, manifest, meta = null) {
+ const a = entry?.audio;
+ if (!a) return null;
+ const clip = (manifest?.timeline ?? []).find((e) => e?.id === a.clip && e.type === "clip");
+ if (!clip) return null;
+ const at = { ...clip, cite: Number(a.start), start: Number(a.start) };
+ const links = resolveDeck(manifest?.render ?? {}).qr?.links;
+ return {
+ parts: attributionParts(at, meta ?? {}, manifest?.provenance ?? {}),
+ url: deckQrUrl(at, manifest?.provenance ?? {}, { ...(links ? { links } : {}), meta }),
+ };
+}
+
+export default defineModule({
+ id: "analysis",
+ version: 1,
+ z: 0,
+ kind: "segment",
+ slot: "full",
+ title: "Analysis",
+ summary: "An ending built from the ledger: a chart of a named run of his weights, a pace table, a status row and one reading line, as its own segment.",
+ validate: (_value, { manifest }) => validateAnalysisEntries(manifest),
+ docs: {
+ heading: "Analysis item",
+ intro: "A timeline entry `{ type: \"analysis\", … }` (analysis-plan.mjs; [report-video.md](report-video.md#the-analysis-item)): a full-frame ending drawn from the LEDGER -- a chart of a named run of his weights (`series`: rows, or a span; a delta resolved against the run's start), a shaded `band`, `marks`, a `pace` table whose pounds and days are computed, `status` rows and ONE `reading` -- the line drawing in, the rows landing; with `audio` a clip's sound under it (its citation and QR on the page, its picture not), else silent for `seconds` (7, at most 8). Every figure traces to a ledger row (the dashed line too: `mark: {row}`); a bound (\"< 300\") is drawn hollow and a pace row ending on one says it in words (\"MORE THAN 10.5 lb lost\", \"AT MOST 8.5 lb lost\"); a number typed into the words is a lint warning.",
+ rows: [
+ ["an `analysis` entry", "`title`, `kicker`, `series`, `band`, `marks`, `pace`, `status`, `reading`, `footnote`, `mark`, `audio?`, `seconds?`", "`umtool timeline <p> [--take <t>] add-analysis @<file>` · `set-analysis <id> @<file>` (or the JSON itself)"],
+ ],
+ },
+ region: "analysis",
+ workers: "wide",
+ noun: "the analysis item's",
+ entry(manifest, segment) {
+ const e = (manifest.timeline ?? []).find((x) => x.id === segment && x.type === "analysis") ?? null;
+ if (!e) return null;
+ const errors = analysisProblems(e, analysisContext(manifest)).errors;
+ if (errors.length) throw new Error(errors.join("; "));
+ return e;
+ },
+ seconds: (entry) => analysisSeconds(entry),
+ names: ({ preview, entry }) => ({ project: `analysis-${preview ? "preview-" : ""}${entry.id}`, stem: `analysis-${entry.id}` }),
+ async page(ctx) {
+ const { analysisHtml, analysisCite, ANALYSIS_BOX } = await import("../chrome-analysis.mjs");
+ const fonts = await instrumentFonts(ctx);
+ const src = analysisSource(ctx.entry, ctx.manifest, ctx.context?.meta ?? null);
+ let qrSrc = null;
+ if (src?.url) {
+ const byUrl = await ctx.qrs([src.url], Math.round((ANALYSIS_BOX.qr * (Number(ctx.render.width) || 1920)) / 1280));
+ qrSrc = byUrl.get(src.url) ?? null;
+ }
+ return analysisHtml(ctx.entry, analysisContext(ctx.manifest), { fonts, cite: src ? analysisCite(src.parts) : null, qrSrc });
+ },
+ // A cue interpreter: a changed item recaptures only the frames its change is on.
+ frameKeys: { data: "analysis-data", omit: ["init", "cues"] },
+});
diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs
@@ -25,6 +25,7 @@ import threads from "./threads.mjs";
import flips from "./flips.mjs";
import finale from "./finale.mjs";
import teaser from "./teaser.mjs";
+import analysis from "./analysis.mjs";
import subtitle from "./subtitle.mjs";
import qr from "./qr.mjs";
import rail from "./rail.mjs";
@@ -53,7 +54,7 @@ export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, RE
/** Every module, by z (stack order), then id. */
export const MODULES = Object.freeze(
- [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status, chat, shelf, diet, peak, goals, promise, streak, dial, odometer, trail, dialFinale, runsFinale]
+ [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, analysis, intro, blur, pair, chapter, status, chat, shelf, diet, peak, goals, promise, streak, dial, odometer, trail, dialFinale, runsFinale]
.sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)),
);
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -19,6 +19,7 @@
"exports": {
"./attribution": "./attribution.mjs",
"./video-entry": "./video-entry.mjs",
+ "./analysis-plan": "./analysis-plan.mjs",
"./site-links": "./site-links.mjs",
"./brand": "./brand.mjs",
"./brand-ids": "./brand-ids.mjs",
diff --git a/umtool/report-to-video/trail-plan.mjs b/umtool/report-to-video/trail-plan.mjs
@@ -95,8 +95,10 @@ const jan1 = (y) => Date.UTC(y, 0, 1) / 86400000;
* between them (`gaps`: `{ key, x }`), the year labels (`years`: `{ key, text, x, tick }`), and `X(day)` / `Y(v)`.
*
* `box` = `{ x0, x1, y0, y1, gapPx, yearPx }` in page pixels.
+ * `dayShare` (default DAY_SHARE): the part of the width shared out by days -- 1 lays x by days alone (the analysis
+ * item's date axis, analysis-plan.mjs, where a span's width says its days).
*/
-export function trailLayout(points, box, { thr = Infinity, mark = null } = {}) {
+export function trailLayout(points, box, { thr = Infinity, mark = null, dayShare = DAY_SHARE } = {}) {
const { x0, x1, y0, y1 } = box;
const gapPx = box.gapPx ?? 22;
const yearPx = box.yearPx ?? 34;
@@ -127,7 +129,7 @@ export function trailLayout(points, box, { thr = Infinity, mark = null } = {}) {
c.knots = knots.map((d, i) => {
if (i > 0) {
const share = (i > 1 ? 0.5 : 0) + (i < knots.length - 1 ? 0.5 : 0);
- x += avail * (DAY_SHARE * (d - knots[i - 1]) / widthDays + (1 - DAY_SHARE) * share / slots);
+ x += avail * (dayShare * (d - knots[i - 1]) / widthDays + (1 - dayShare) * share / slots);
}
return { d, x };
});