commit 3367d158675d0aa79a380eb27d613726519fa1b2
parent 0e64a563a537f5a0a4d1695bbbb973ed21cda9a9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 5 Nov 2026 23:49:15 -0500
Merge main (the measure ledger) into lane/scale-dial
scheduleSlices' measure line is the producer's (one copy); the deck's allowed
keys take "measure" and the instruments'; SETTINGS keeps measure before the
counter, the instruments after popup-posts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
29 files changed, 5641 insertions(+), 49 deletions(-)
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -94,6 +94,10 @@
// promo/trailer-beats.json): running length against the limit, beats outside their clip
// umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence,
// each edge into its pause: before -> after for review; --apply writes the named rows
+// umtool ledger <project> [ls | add <id> --<key> V … | set <id> --<key> V … [--unset k,k] | rm <id>] [--json]
+// a measure ledger's rows, through its writers (weight video rev 9)
+// umtool measure <project> [--take <t>] [--scopes a,b] [--as-of D] [--json]
+// the measure slice the instruments draw from
// umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>]
// the clip deck's montage rulings (release 34)
// umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of
@@ -1015,6 +1019,10 @@ function usage() {
" --reel <name>: that beat reel (promo/<name>-beats.json); every write is an undo point",
" umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence (its",
" cut's, else the whole ones in its window), each edge into its pause; before -> after; --apply writes",
+ " umtool ledger <project> [ls] [--scope S] [--json] | add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] | set <id> --<key> V … [--unset k,k] | rm <id>",
+ " a measure ledger's rows, checked against its ledgerSchema (incl. promise / promise_check, run, retro)",
+ " umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]",
+ " the measure slice the instruments draw from: events at their cut seconds, hidden rows, totals",
" umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>",
" the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out",
" umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]",
@@ -1169,6 +1177,9 @@ const COMMANDS = {
tighten: async () => process.exit(await (await import("../lib/report/tightCli.mjs")).tightenCommand(argv.slice(argv.indexOf("tighten") + 1))),
// The trailer's beats, edited (UI notes item 11): lib/report/trailerBeatsCli.mjs.
"trailer-beats": async () => process.exit(await (await import("../lib/report/trailerBeatsCli.mjs")).trailerBeatsCommand(argv.slice(argv.indexOf("trailer-beats") + 1))),
+ // A measure ledger's rows, and the slice its instruments draw from (weight video rev 9).
+ ledger: async () => process.exit(await (await import("../lib/report/ledgerCli.mjs")).ledgerCommand(argv.slice(argv.indexOf("ledger") + 1))),
+ measure: async () => process.exit(await (await import("../lib/report/measureCli.mjs")).measureCommand(argv.slice(argv.indexOf("measure") + 1))),
// The clip deck's rulings (release 34): lib/report/rulingsCli.mjs.
rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))),
// Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs.
diff --git a/umtool/components/projects/ClaimBenchPage.tsx b/umtool/components/projects/ClaimBenchPage.tsx
@@ -37,7 +37,7 @@ export default async function ClaimBenchPage({
// while somebody is standing on this page.
let fired: Array<{ rule: string; text: string }> = [];
try {
- const totals = ledgerTotals(ledger, { strict: false });
+ const totals = ledgerTotals(ledger, { strict: false, manifest });
fired = totals.steps.find((s: { id: string }) => s.id === claimId)?.flags ?? [];
} catch {
/* a malformed ledger shows as gaps, not as a broken page */
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -69,6 +69,8 @@ Inbox cannot disagree about what is wrong with one.
| `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) |
| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) |
+| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
+| `measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]` | the **measure slice** the instruments draw from (`render.chrome.deck.measure`; the flags override it): each row in scope the cut shows at the cut second its figure is said, the hidden rows, and the totals -- the odometer's runs, NET, the goals, the diets, the promises. The take's built `schedule.json` with `--take`, else an estimate; `--json` prints the slice. Reads only ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
| `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -446,6 +446,49 @@ umtool look <p> deck.claims='[{"kind":"count","at":"less-than-ten","t":903.6,"sa
umtool set <p> costco-ok claim.eventDate=2026-09-22
```
+## The measure slice (the weight instruments)
+
+A manifest whose `ledgerSchema.kind` is `"measure"` (one quantity over time and the regime he names; report-to-video
+`measure-totals.mjs`) has its rows pinned to the cut by each row's `entryId` or an entry's ledger pin, `claim:
+"<row id>"` (a string; a manifest that stamps fact-check verdicts keeps `claim` as `{id, verdict}`). With the deck on
+and `render.chrome.deck.measure` set, the build writes the **measure slice** into `schedule.json` (`doc.measure`,
+`measure-slice.mjs`): every row in scope the cut shows, at the cut second its figure is said (the clip's words, else
+its cues spread by characters, else the entry's `quoteStart`, else the segment's start -- `tFrom` says which), the
+rows no entry shows (`hidden`), the state after each event (current, remembered, goal, goals, lost, net, diet,
+promises) and the totals. Every instrument module reads it whole (`slices.measure`). Absent the key, the schedule is
+the one it always was.
+
+| Key | What it is |
+|---|---|
+| `scopes` | the ledger's tracks the instruments see (`["weight","regime"]`); a row of any other track is ignored entirely. Default: every track |
+| `scale` | `{min, max}` in the ledger's unit: the dial's face. Default: the schema's `yMin`..`yMax` |
+| `asOf` | the day the live countdowns and the promise clock count to (YYYY-MM-DD). Default: the day it is built |
+
+**The odometer** (ruled 5 Nov 2026, "go by his words"): only real-time loss claims count -- a `delta` below zero with
+no `asOf` and not `retro`; a run's figure is its HIGHEST claim (his figure, over any app's he cites); a row's `run`
+places it where his words say ("since I started"), else a gap over `bandGapDays` starts a new run; the total is the
+sum of the runs. A **goal_loss** is a target weight against the start of the run open when he set it (a remembered
+weight about a day within `bandGapDays` before the run's first claim), else against the last weight he stated. A
+**diet** is the regime cell: an off closes only the regime it names. A **promise** (`promise`: what he says he will
+do, `due` when he gave a day) is checked by his later `promise_check` rows naming it (`promise`), claimed about by
+another party's `promise_claim` rows (`speaker`, e.g. `madamsavvy`; `paidOn`; a `citeUrl`), and ended by a
+`promise_outcome` (`outcome`: `kept` · `refunded` · `withdrawn`); `kept: true` on the promise or a check, or an
+outcome `kept`, keeps it. A row with a `speaker` is someone else's: it moves none of his numbers (current, lost, net,
+goals, diet, the totals) and only feeds the promises (`state.promises[].claims`, `.outcome`).
+
+Rows are written through `umtool ledger` only; `umtool measure` prints the slice:
+
+```sh
+umtool look <p> deck.measure='{"scopes":["weight","regime"],"scale":{"min":220,"max":400}}'
+umtool ledger <p> add p01 --date 2026-10-23 --scope weight --population promise --display "post a video of the scale" --scopeBasis "his own post" --citeUrl https://x.com/…/status/…
+umtool ledger <p> add p02 --date 2026-11-03 --scope weight --population promise_check --promise p01 --display "pull up a video from three months ago" --scopeBasis "about the scale video"
+umtool ledger <p> add s01 --date 2026-10-23 --scope weight --population promise_claim --promise p01 --speaker madamsavvy --paidOn 2026-10-23 --display "bought the 5 bags" --scopeBasis "her post" --citeUrl https://x.com/…/status/…
+umtool ledger <p> add o01 --date 2026-10-31 --scope weight --population promise_outcome --promise p01 --outcome refunded --speaker madamsavvy --label "refunded by 31 Oct" --scopeBasis "his email, read in her video"
+umtool ledger <p> set w14 --retro true # a loss told in the past: off the odometer
+umtool ledger <p> set w75 --run 6 # his words put it in the 2025 run
+umtool measure <p> --take <t> --json
+```
+
## Walk and preview (the clip editor)
The clip editor (`/projects/<p>/clips`, a clip with **Edit**) is where a deck cut is walked: under the player,
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -1491,8 +1491,10 @@ export async function reportDecisions(ctx, summary) {
// One row per entry, not one collapsed row. Forty unpunctuated sources are
// the same true thing said forty times; forty unadjudicated claims are
// forty DIFFERENT decisions, and the inbox being empty is the sign-off.
- for (const e of unadjudicatedOf(ledger)) {
- const gaps = adjudicationGaps(e);
+ // The manifest picks the arithmetic: a measure ledger (ledgerSchema.kind
+ // "measure") is gated on ITS vocabulary, never the headcount one.
+ for (const e of unadjudicatedOf(ledger, m)) {
+ const gaps = adjudicationGaps(e, m);
add(
"claim-unadjudicated",
e.id,
@@ -1507,7 +1509,7 @@ export async function reportDecisions(ctx, summary) {
// proceeds rather than all at once at the end.
let totals = null;
try {
- totals = ledgerTotals(ledger, { strict: false });
+ totals = ledgerTotals(ledger, { strict: false, manifest: m });
} catch {
/* a malformed ledger is already reported as unadjudicated rows */
}
diff --git a/umtool/lib/report/ledgerCli.mjs b/umtool/lib/report/ledgerCli.mjs
@@ -0,0 +1,153 @@
+// `umtool ledger` (weight video rev 9): a MEASURE ledger's rows from a
+// terminal -- listed, added, patched, removed -- through the manifest's own
+// writers (manifest.mjs addLedgerRow / updateLedgerRow / removeLedgerRow), so
+// every row written is checked against the manifest's ledgerSchema
+// (ledgerRows.mjs) exactly as the instruments will read it.
+//
+// umtool ledger <project> [ls] [--scope S] [--population P] [--json]
+// umtool ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}'] [--json]
+// umtool ledger <project> set <id> --<key> V … [--unset k,k] [--json]
+// umtool ledger <project> rm <id> [--json]
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { addLedgerRow, removeLedgerRow, updateLedgerRow } from "./manifest.mjs";
+import { isMeasureLedger, parseLedgerValue } from "./ledgerRows.mjs";
+
+export const LEDGER_USAGE = [
+ "usage: umtool ledger <project> [ls] [--scope S] [--population P] [--json] the ledger's rows",
+ " umtool ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] [--row '{…}'] [--json]",
+ " umtool ledger <project> set <id> --<key> V … [--unset k,k] [--json]",
+ " umtool ledger <project> rm <id> [--json]",
+ "",
+ "A measure ledger's rows (ledgerSchema.kind \"measure\"), written only through these: each row is checked against",
+ "the schema -- a scope that is a track, a form it names (and the promise forms: promise / promise_check /",
+ "promise_claim / promise_outcome), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults",
+ "scopeConfidence read, valueKind uttered, flags []; --scopeBasis is never defaulted) and the declared fields.",
+ "--<key> sets any built-in key (date asOf scope population value event display label quote deadline src channel",
+ "video cite citeFrom scopeBasis scopeConfidence valueKind flags (a|b) hedged unsourced entryId authorNote, and the",
+ "instruments' own: run (a loss claim's run, his words placing it), retro (a loss told in the past with no asOf:",
+ "off the odometer), promise (a promise_check's or promise_claim's promise), kept, due (YYYY-MM-DD), speaker (another",
+ "party's key: a promise_claim's -- her rows move none of his numbers), paidOn (YYYY-MM-DD), outcome (a",
+ "promise_outcome's: kept, refunded, withdrawn)) or a declared field; `null`",
+ "clears a value. rm refuses a row a timeline entry pins or another row names.",
+].join("\n");
+
+class CliError extends Error {}
+
+/** `--key value` pairs (the rest: words), `--json`/`--help` alone. */
+function parseArgs(args) {
+ const flags = new Map();
+ const words = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--json" || a === "--help") { flags.set(a.slice(2), true); continue; }
+ if (a.startsWith("--")) {
+ const eq = a.indexOf("=");
+ if (eq > 0) { flags.set(a.slice(2, eq), a.slice(eq + 1)); continue; }
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ flags.set(a.slice(2), args[i + 1]);
+ i += 1;
+ continue;
+ }
+ words.push(a);
+ }
+ return { flags, words };
+}
+
+/** The row patch the flags spell: `--row` JSON first, then each `--<key>`. */
+function patchOf(flags, skip) {
+ let patch = {};
+ if (flags.has("row")) {
+ try {
+ patch = JSON.parse(String(flags.get("row")));
+ } catch (e) {
+ throw new CliError(`--row is not JSON: ${e instanceof Error ? e.message : e}`);
+ }
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) throw new CliError("--row must be a JSON object");
+ }
+ for (const [k, v] of flags) {
+ if (skip.has(k)) continue;
+ patch[k] = parseLedgerValue(k, v);
+ }
+ return patch;
+}
+
+const line = (r) =>
+ [
+ String(r.id).padEnd(6),
+ String(r.date ?? "").padEnd(10),
+ String(r.scope ?? "").padEnd(9),
+ String(r.population ?? "").padEnd(14),
+ String(r.display ?? r.value ?? "—").padEnd(22),
+ r.entryId ? `@${r.entryId}` : "",
+ Number.isInteger(r.run) ? `run ${r.run}` : "",
+ r.retro ? "retro" : "",
+ r.promise ? `-> ${r.promise}` : "",
+ r.speaker ? `by ${r.speaker}` : "",
+ r.paidOn ? `paid ${r.paidOn}` : "",
+ r.outcome ? String(r.outcome).toUpperCase() : "",
+ r.kept ? "kept" : "",
+ String(r.label ?? "").slice(0, 70),
+ ].filter(Boolean).join(" ");
+
+/**
+ * @param {string[]} args the words after `ledger`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>} the exit code
+ */
+export async function ledgerCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const { flags, words } = parseArgs(args);
+ const [projectArg, verb = "ls", id] = words;
+ if (!projectArg || flags.get("help")) {
+ err(LEDGER_USAGE);
+ return 2;
+ }
+ const json = flags.get("json") === true;
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
+ const project = r.project;
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+
+ if (verb === "ls") {
+ const rows = (manifest.ledger ?? []).filter((x) =>
+ (!flags.has("scope") || x.scope === flags.get("scope")) && (!flags.has("population") || x.population === flags.get("population")));
+ if (json) out(JSON.stringify({ project: project.id, kind: isMeasureLedger(manifest) ? "measure" : "headcount", rows }, null, 2));
+ else {
+ for (const x of rows) out(line(x));
+ out(`${rows.length} of ${(manifest.ledger ?? []).length} row(s)`);
+ }
+ return 0;
+ }
+ if (!isMeasureLedger(manifest)) throw new CliError(`${project.id} has no measure ledger (ledgerSchema.kind "measure"): these writers are a measure ledger's`);
+ if (!id) throw new CliError(`${verb} needs a row id`);
+ if (verb === "add") {
+ const patch = { ...patchOf(flags, new Set(["json", "help"])), id };
+ const done = await addLedgerRow(project.dir, patch);
+ if (json) out(JSON.stringify({ project: project.id, added: done.row }, null, 2));
+ else out(`added ${line(done.row)}`);
+ return 0;
+ }
+ if (verb === "set") {
+ const unset = flags.has("unset") ? String(flags.get("unset")).split(",").map((s) => s.trim()).filter(Boolean) : [];
+ const patch = patchOf(flags, new Set(["json", "help", "unset"]));
+ if (!Object.keys(patch).length && !unset.length) throw new CliError("set needs --<key> <value> or --unset <keys>");
+ const done = await updateLedgerRow(project.dir, id, patch, { unset });
+ if (json) out(JSON.stringify({ project: project.id, row: done.row }, null, 2));
+ else out(`set ${line(done.row)}`);
+ return 0;
+ }
+ if (verb === "rm") {
+ const done = await removeLedgerRow(project.dir, id);
+ if (json) out(JSON.stringify({ project: project.id, removed: done.row.id }, null, 2));
+ else out(`removed ${done.row.id}`);
+ return 0;
+ }
+ throw new CliError(`unknown: ledger ${verb} — ls, add, set or rm`);
+ } catch (e) {
+ err(`umtool ledger: ${e instanceof Error ? e.message : String(e)}`);
+ return 1;
+ }
+}
diff --git a/umtool/lib/report/ledgerCli.test.mjs b/umtool/lib/report/ledgerCli.test.mjs
@@ -0,0 +1,164 @@
+// `umtool ledger` and `umtool measure` (weight video rev 9): a measure
+// ledger's rows written only through its writers, checked against the
+// schema, and the slice printed off a project made here. Run with:
+// pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-ledger-cli-"));
+process.env.REPORTS_DIR = path.join(ROOT, "reports");
+const { ledgerCommand } = await import("./ledgerCli.mjs");
+const { measureCommand } = await import("./measureCli.mjs");
+const { ledgerRowOf, ledgerRowReferences, parseLedgerValue } = await import("./ledgerRows.mjs");
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SCHEMA = {
+ kind: "measure",
+ unit: "lb",
+ yMin: 210,
+ yMax: 400,
+ bandGapDays: 60,
+ tracks: [
+ { key: "weight", role: "value", label: "Weight" },
+ { key: "regime", role: "regime", label: "Diet", regimes: ["keto", "off"] },
+ { key: "drinking", role: "regime", label: "Drinking", regimes: ["dry", "drinking"] },
+ ],
+ forms: ["current", "past", "delta", "goal", "goal_loss", "overweight_by", "status"],
+ regimes: [{ key: "keto", label: "Keto" }, { key: "off", label: "No diet" }, { key: "dry", label: "Dry" }, { key: "drinking", label: "Drinking" }],
+ fields: [
+ { key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], appliesTo: { scope: "weight" }, render: "cell" },
+ { key: "citeUrl", label: "Source link", kind: "text", maxLength: 200 },
+ ],
+};
+const base = (o) => ({ scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o });
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "weigh",
+ provenance: { siteOrigin: "https://example.test", channelSlug: "chan", channelsDir: "nowhere" },
+ render: { fps: 30, transition: 0 },
+ ledgerSchema: SCHEMA,
+ timeline: [
+ { type: "clip", id: "c1", video: "v1", start: 10, end: 30, quoteStart: 12, claim: "w01" },
+ { type: "clip", id: "c2", video: "v2", start: 0, end: 20, quoteStart: 5, claim: "w02" },
+ ],
+ ledger: [
+ base({ id: "w01", date: "2026-09-15", population: "delta", value: -5, display: "-5", entryId: "c1" }),
+ base({ id: "w02", date: "2026-10-26", population: "current", value: 291.5, display: "291.5 lb", entryId: "c2" }),
+ base({ id: "w03", date: "2026-10-31", population: "delta", value: -60, display: "-60", qualifier: "≈" }),
+ base({ id: "w04", date: "2023-03-02", population: "delta", value: -64, display: "-64" }),
+ base({ id: "w05", date: "2008-06-30", population: "past", asOf: "2008-06-30", value: 368, display: "368 lb" }),
+ base({ id: "d01", date: "2026-10-01", scope: "drinking", population: "status", value: "dry", event: "start", display: "dry" }),
+ ],
+};
+
+async function project() {
+ const dir = path.join(ROOT, "reports", "weigh");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2));
+ return dir;
+}
+const lines = [];
+const run = (cmd, ...args) => cmd(args, { root: path.join(ROOT, "reports"), out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) });
+const manifestOf = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+
+test("a row is checked against the schema, and every problem is named", () => {
+ assert.throws(() => ledgerRowOf({ ...MANIFEST, ledgerSchema: undefined }, null, {}), /no measure ledger/);
+ assert.throws(
+ () => ledgerRowOf(MANIFEST, null, { id: "w01", date: "soon", scope: "gym", population: "guess", nonsense: 1 }),
+ /"nonsense" is not a ledger key/,
+ );
+ let e;
+ try { ledgerRowOf(MANIFEST, null, { id: "w01", date: "soon", scope: "gym", population: "guess" }); } catch (err) { e = String(err.message); }
+ for (const want of ["already has a row w01", "date must be", "scope must be one of the ledger's tracks: weight, regime, drinking", "population must be one of", "scopeBasis must quote"]) {
+ assert.ok(e.includes(want), `${want} in: ${e}`);
+ }
+ assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "r9", date: "2026-01-01", scope: "regime", population: "status", value: "dry" })), /value on the regime track must be one of its regimes: keto, off; event must be/);
+ assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "current", value: "heavy" })), /value must be a number/);
+ assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "current", value: 300, run: 2 })), /run is a loss claim's/);
+ assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "delta", value: -3, run: 1.5 })), /run must be a whole number/);
+ assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "p9", date: "2026-01-01", population: "promise_check", promise: "w01" })), /promise must name a promise row \(w01 is a delta row\)/);
+ assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "current", value: 300, qualifier: "?" })), /qualifier/);
+ // A sound one: the defaults for three of the six, its display from its value.
+ const ok = ledgerRowOf(MANIFEST, null, { id: "w9", date: "2026-11-03", scope: "weight", population: "delta", value: -58.2, scopeBasis: "his words" });
+ assert.deepEqual([ok.scopeConfidence, ok.valueKind, ok.flags, ok.display], ["read", "uttered", [], "-58.2 lb"]);
+ assert.equal(parseLedgerValue("value", "-58.2"), -58.2);
+ assert.equal(parseLedgerValue("retro", "true"), true);
+ assert.deepEqual(parseLedgerValue("flags", "a|b"), ["a", "b"]);
+ assert.deepEqual(ledgerRowReferences(MANIFEST, "w01"), ["timeline entry c1 pins it (claim)"]);
+});
+
+test("umtool ledger: add, set, unset, rm -- through the writers, on the file", async () => {
+ const dir = await project();
+ lines.length = 0;
+ assert.equal(await run(ledgerCommand, "weigh", "ls", "--scope", "weight"), 0);
+ assert.match(lines.at(-1), /5 of 6 row\(s\)/);
+ // The promise, and a later word about it.
+ assert.equal(await run(ledgerCommand, "weigh", "add", "p01", "--date", "2026-10-23", "--scope", "weight", "--population", "promise",
+ "--display", "post a video of the scale", "--scopeBasis", "his own post", "--citeUrl", "https://x.com/a/status/1", "--json"), 0, lines.join("\n"));
+ assert.equal(JSON.parse(lines.at(-1)).added.citeUrl, "https://x.com/a/status/1");
+ assert.equal(await run(ledgerCommand, "weigh", "add", "p02", "--date", "2026-11-03", "--scope", "weight", "--population", "promise_check",
+ "--promise", "p01", "--display", "pull up a video from three months ago", "--scopeBasis", "the scale video"), 0, lines.join("\n"));
+ // Another party's word about it: a promise_claim, with her key and the day she says she paid.
+ assert.equal(await run(ledgerCommand, "weigh", "add", "s01", "--date", "2026-10-24", "--scope", "weight", "--population", "promise_claim",
+ "--promise", "p01", "--speaker", "madamsavvy", "--paidOn", "2026-10-24", "--display", "bought the 5 bags", "--scopeBasis", "her post",
+ "--citeUrl", "https://x.com/MadamSavvy/status/2"), 0, lines.join("\n"));
+ assert.equal(await run(ledgerCommand, "weigh", "add", "s02", "--date", "2026-10-24", "--scope", "weight", "--population", "promise_check",
+ "--promise", "p01", "--speaker", "madamsavvy", "--scopeBasis", "her post"), 1);
+ assert.match(lines.at(-1), /a promise_check is the subject's own word: madamsavvy's is a promise_claim/);
+ assert.equal(await run(ledgerCommand, "weigh", "add", "s02", "--date", "2026-10-24", "--scope", "weight", "--population", "current",
+ "--value", "250", "--paidOn", "2026-10-24", "--speaker", "Madam Savvy", "--scopeBasis", "her post"), 1);
+ assert.match(lines.at(-1), /speaker must be a speaker's key.*paidOn is a promise_claim's|paidOn is a promise_claim's/);
+ // How it ended: a promise_outcome, refunded by her account.
+ assert.equal(await run(ledgerCommand, "weigh", "add", "o01", "--date", "2026-10-31", "--scope", "weight", "--population", "promise_outcome",
+ "--promise", "p01", "--outcome", "refunded", "--speaker", "madamsavvy", "--label", "refunded by 31 Oct", "--scopeBasis", "her video"), 0, lines.join("\n"));
+ assert.equal(await run(ledgerCommand, "weigh", "add", "o02", "--date", "2026-10-31", "--scope", "weight", "--population", "promise_outcome",
+ "--promise", "p01", "--outcome", "forgotten", "--scopeBasis", "x"), 1);
+ assert.match(lines.at(-1), /outcome kept, refunded, withdrawn/);
+ assert.equal(await run(ledgerCommand, "weigh", "rm", "o01"), 0);
+ assert.equal(await run(ledgerCommand, "weigh", "rm", "s01"), 0);
+ // A loss told in the past: off the odometer; then put back on it.
+ assert.equal(await run(ledgerCommand, "weigh", "set", "w04", "--retro", "true"), 0, lines.join("\n"));
+ let m = await manifestOf(dir);
+ assert.equal(m.ledger.find((r) => r.id === "w04").retro, true);
+ assert.equal(await run(ledgerCommand, "weigh", "set", "w04", "--unset", "retro"), 0);
+ m = await manifestOf(dir);
+ assert.equal("retro" in m.ledger.find((r) => r.id === "w04"), false);
+ // Refused, by name, and nothing written.
+ const before = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ assert.equal(await run(ledgerCommand, "weigh", "set", "w02", "--run", "3"), 1);
+ assert.match(lines.at(-1), /ERR umtool ledger: run is a loss claim's/);
+ assert.equal(await run(ledgerCommand, "weigh", "rm", "p01"), 1);
+ assert.match(lines.at(-1), /p01 is still named: row p02 names it/);
+ assert.equal(await run(ledgerCommand, "weigh", "rm", "w01"), 1);
+ assert.match(lines.at(-1), /timeline entry c1 pins it/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+ assert.equal(await run(ledgerCommand, "weigh", "rm", "p02"), 0);
+ m = await manifestOf(dir);
+ assert.equal(m.ledger.some((r) => r.id === "p02"), false);
+});
+
+test("umtool measure: the slice, scoped, with the odometer by his words", async () => {
+ await project();
+ assert.equal(await run(ledgerCommand, "weigh", "set", "w04", "--retro", "true"), 0);
+ assert.equal(await run(ledgerCommand, "weigh", "add", "w06", "--date", "2026-11-03", "--scope", "weight", "--population", "delta", "--value", "-58.2", "--scopeBasis", "his words"), 0);
+ lines.length = 0;
+ assert.equal(await run(measureCommand, "weigh", "--scopes", "weight,regime", "--as-of", "2026-11-05", "--json"), 0, lines.join("\n"));
+ const sl = JSON.parse(lines.join("\n"));
+ assert.deepEqual(sl.scopes, ["weight", "regime"]);
+ assert.equal(sl.asOfRender, "2026-11-05");
+ assert.deepEqual(sl.events.map((e) => [e.row, e.tFrom]), [["w01", "quote"], ["w02", "quote"]]);
+ assert.ok(![...sl.events, ...sl.hidden].some((e) => e.row === "d01"), "drinking is out of scope");
+ // One run: 5, then 60, then 58.2 -- its peak stays 60; the retro 64 is not counted.
+ assert.equal(sl.totals.runs, 1);
+ assert.equal(sl.totals.lost, 60);
+ assert.deepEqual(sl.totals.net, { from: 368, to: 291.5, value: -76.5, fromRow: "w05", toRow: "w02" });
+ lines.length = 0;
+ assert.equal(await run(measureCommand, "weigh", "--scopes", "weight,regime"), 0);
+ assert.match(lines.join("\n"), /lost \(his words\): 60 lb across 1 run\(s\)/);
+ assert.equal(await run(measureCommand, "weigh", "--scopes", "gym"), 1);
+ assert.match(lines.at(-1), /"gym" is not a track/);
+});
diff --git a/umtool/lib/report/ledgerRows.mjs b/umtool/lib/report/ledgerRows.mjs
@@ -0,0 +1,194 @@
+// A MEASURE ledger's rows, checked (weight video rev 9): what `umtool ledger
+// add|set|rm` may write into `manifest.ledger`, against the manifest's own
+// `ledgerSchema`. Pure: manifest.mjs's addLedgerRow / updateLedgerRow /
+// removeLedgerRow write what this returns, under the manifest lock.
+//
+// A row is the built-in keys (ledger-shared.mjs LEDGER_BUILTIN_KEYS, each
+// with its type here) and the schema's declared `fields[]` (measure-totals
+// validateFields); any other key is refused by name -- a key nothing reads is
+// adjudication work that never comes out. A written row passes the gate the
+// arithmetic keeps (measureGaps): a scope that is a track, a form the schema
+// names, the six adjudication fields, and on a regime track a declared
+// regime and an event. The promise forms are every measure ledger's:
+// `promise` (what he says he will do), `promise_check` (his later word about
+// it) and `promise_claim` (another party's statement about it, with its
+// `speaker` and `paidOn`), the last two naming the promise in `promise`;
+// `kept: true` on a promise or a check; `promise_outcome` says how it ended
+// (`outcome`: kept, refunded, withdrawn). A row's `speaker` (absent: the
+// subject) is a lower-case key; another speaker's row moves none of his
+// numbers (measure-slice.mjs).
+import {
+ EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields,
+} from "umtool-report-to-video/ledger-totals";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const DATE_RE = /^\d{4}(?:-\d{2}(?:-\d{2})?)?$/;
+const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
+const ID_RE = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;
+
+/** The forms whose value is a number in the schema's unit. */
+const NUMERIC_FORMS = new Set(["current", "past", "delta", "goal", "goal_loss", "overweight_by"]);
+
+/** Each built-in key's type: what a CLI flag's text is parsed as, and what is checked. */
+export const LEDGER_KEY_TYPES = Object.freeze({
+ id: "id", date: "date", asOf: "date?", scope: "text", population: "text", value: "value", event: "text?",
+ display: "text?", label: "text?", quote: "text?", deadline: "text?", src: "text?", channel: "text?", video: "text?",
+ cite: "seconds?", citeFrom: "text?", scopeBasis: "text", scopeConfidence: "text", valueKind: "text", flags: "list",
+ hedged: "bool?", unsourced: "bool?", plotted: "bool?", hidden: "bool?", entryId: "text?", authorNote: "text?",
+ run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", speaker: "speaker?", paidOn: "day?", outcome: "text?",
+});
+
+/** Is this manifest's ledger a measure ledger (the one these writers write)? */
+export const isMeasureLedger = (manifest) => isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure";
+
+/**
+ * A flag's text as the value of `key`: a number for a number key ("null"
+ * clears), true/false for a boolean, a list split on "|" for `flags`, a
+ * number for `value` when it reads as one. Declared fields are left as text
+ * (validateFields types them).
+ */
+export function parseLedgerValue(key, text) {
+ const t = String(text);
+ if (t === "null") return null;
+ const type = LEDGER_KEY_TYPES[key];
+ if (type === "bool?") {
+ if (t === "true") return true;
+ if (t === "false") return false;
+ return t;
+ }
+ if (type === "seconds?" || type === "run?") return /^-?\d+(?:\.\d+)?$/.test(t) ? Number(t) : t;
+ if (type === "value") return /^[-+]?\d+(?:\.\d+)?$/.test(t) ? Number(t) : t;
+ if (type === "list") return t === "" ? [] : t.split("|").map((s) => s.trim()).filter(Boolean);
+ return t;
+}
+
+/**
+ * The row `patch` makes of `base` (null for a new row), checked and
+ * normalised -- or a thrown sentence naming every problem. `unset` lists the
+ * keys to remove. A new row gets the boring answer for three of the six
+ * (`scopeConfidence` read, `valueKind` uttered, `flags` []) and its display
+ * from its value; `scopeBasis` is never defaulted (a ruling with no basis is
+ * an opinion).
+ *
+ * @param {object} manifest
+ * @param {Record<string, unknown> | null} base the row as it stands, or null
+ * @param {Record<string, unknown>} patch
+ * @param {{ unset?: string[] }} [opts]
+ * @returns {Record<string, unknown>}
+ */
+export function ledgerRowOf(manifest, base, patch, { unset = [] } = {}) {
+ if (!isMeasureLedger(manifest)) throw new Error('the manifest has no measure ledger (ledgerSchema.kind "measure")');
+ const schema = measureSchema(manifest.ledgerSchema);
+ const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : [];
+ const declared = new Map(schema.fields.map((f) => [f.key, f]));
+ const errors = [];
+ for (const k of [...Object.keys(patch ?? {}), ...unset]) {
+ if (!LEDGER_BUILTIN_KEYS.has(k) && !declared.has(k)) {
+ errors.push(`"${k}" is not a ledger key (the built-ins, or the schema's fields: ${[...declared.keys()].join(", ") || "none"})`);
+ }
+ }
+ for (const k of unset) if (["id", "date", "scope", "population", "scopeBasis", "scopeConfidence", "valueKind", "flags"].includes(k)) errors.push(`"${k}" cannot be unset: every row has one`);
+ if (errors.length) throw new Error(errors.join("; "));
+
+ const builtins = Object.fromEntries(Object.entries(patch ?? {}).filter(([k]) => LEDGER_BUILTIN_KEYS.has(k)));
+ const fieldPatch = Object.fromEntries(Object.entries(patch ?? {}).filter(([k]) => declared.has(k)));
+ const row = { ...(base ?? {}), ...builtins };
+ for (const k of unset) delete row[k];
+ if (!base) {
+ row.scopeConfidence ??= "read";
+ row.valueKind ??= "uttered";
+ row.flags ??= [];
+ }
+
+ // ---- the built-ins, each against its type ----
+ if (!ID_RE.test(String(row.id ?? ""))) errors.push("id must be a letter, then letters, digits, dots, colons, dashes or underscores (at most 64)");
+ else if (!base && ledger.some((r) => r?.id === row.id)) errors.push(`the ledger already has a row ${row.id}`);
+ if (!DATE_RE.test(String(row.date ?? ""))) errors.push("date must be YYYY-MM-DD (or YYYY-MM, YYYY)");
+ if (row.asOf !== undefined && row.asOf !== null && !DATE_RE.test(String(row.asOf))) errors.push("asOf must be a date, or null");
+ const track = schema.tracks.find((t) => t.key === row.scope) ?? null;
+ if (!track) errors.push(`scope must be one of the ledger's tracks: ${schema.tracks.map((t) => t.key).join(", ")}`);
+ if (!schema.forms.includes(row.population)) errors.push(`population must be one of ${schema.forms.join(", ")}`);
+ const promiseForm = PROMISE_FORMS.includes(row.population);
+ if (track?.role === "regime") {
+ const allowed = track.regimes ?? schema.regimes.map((r) => r.key);
+ if (!allowed.includes(String(row.value))) errors.push(`value on the ${track.key} track must be one of its regimes: ${allowed.join(", ")}`);
+ if (!EVENTS.includes(row.event)) errors.push(`event must be one of ${EVENTS.join(", ")} on a regime track`);
+ } else if (track) {
+ if (NUMERIC_FORMS.has(row.population) && !Number.isFinite(row.value)) errors.push(`value must be a number (in ${schema.unit || "the ledger's unit"}) for a ${row.population} row`);
+ if (promiseForm && row.value !== undefined && row.value !== null) errors.push(`a ${row.population} row has no value (its words are its display)`);
+ if (row.event !== undefined && row.event !== null) errors.push("event is a regime track's");
+ }
+ for (const [k, type] of Object.entries(LEDGER_KEY_TYPES)) {
+ const v = row[k];
+ if (v === undefined || v === null) continue;
+ if (type.startsWith("text") && typeof v !== "string") errors.push(`${k} must be text`);
+ if (type === "speaker?" && !(typeof v === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(v))) errors.push(`${k} must be a speaker's key (lower case: "madamsavvy")`);
+ if (type === "bool?" && typeof v !== "boolean") errors.push(`${k} must be true or false`);
+ if (type === "seconds?" && !(Number.isFinite(v) && v >= 0)) errors.push(`${k} must be a source second, 0 or more`);
+ if (type === "day?" && !DAY_RE.test(String(v))) errors.push(`${k} must be a day (YYYY-MM-DD)`);
+ if (type === "list" && !(Array.isArray(v) && v.every((x) => typeof x === "string"))) errors.push(`${k} must be a list of sentences`);
+ }
+ if (row.scopeConfidence !== undefined && !SCOPE_CONFIDENCE.includes(row.scopeConfidence)) errors.push(`scopeConfidence must be one of ${SCOPE_CONFIDENCE.join(", ")}`);
+ if (row.valueKind !== undefined && !VALUE_KINDS.includes(row.valueKind)) errors.push(`valueKind must be one of ${VALUE_KINDS.join(", ")}`);
+ if (typeof row.scopeBasis !== "string" || !row.scopeBasis.trim()) errors.push("scopeBasis must quote the phrase that settles the scope (--scopeBasis)");
+
+ // ---- the measure instruments' own ----
+ const isDelta = row.population === "delta";
+ if (row.run !== undefined && row.run !== null) {
+ if (!Number.isInteger(row.run) || row.run < 0) errors.push("run must be a whole number, 0 or more");
+ else if (!isDelta) errors.push("run is a loss claim's (a delta row)");
+ }
+ if (row.retro !== undefined && row.retro !== null && !isDelta) errors.push("retro is a loss claim's (a delta row)");
+ if (row.kept !== undefined && row.kept !== null && !["promise", "promise_check"].includes(row.population)) errors.push("kept is a promise's (a promise or promise_check row)");
+ if (row.population === "promise_outcome") {
+ if (!PROMISE_OUTCOMES.includes(row.outcome)) errors.push(`a promise_outcome says how it ended: outcome ${PROMISE_OUTCOMES.join(", ")}`);
+ } else if (row.outcome !== undefined && row.outcome !== null) errors.push("outcome is a promise_outcome's");
+ if (["promise_check", "promise_claim", "promise_outcome"].includes(row.population)) {
+ const p = ledger.find((r) => r?.id === row.promise);
+ if (!row.promise) errors.push(`a ${row.population} names its promise (--promise <row id>)`);
+ else if (!p || p.population !== "promise") errors.push(`promise must name a promise row (${row.promise} is ${p ? `a ${p.population} row` : "not in the ledger"})`);
+ } else if (row.promise !== undefined && row.promise !== null) errors.push("promise is a promise_check's, promise_claim's or promise_outcome's");
+ if (row.paidOn !== undefined && row.paidOn !== null && row.population !== "promise_claim") errors.push("paidOn is a promise_claim's");
+ // A promise_check is HIS later word; another party's is a promise_claim.
+ if (row.population === "promise_check" && row.speaker) errors.push(`a promise_check is the subject's own word: ${row.speaker}'s is a promise_claim`);
+ if (row.entryId !== undefined && row.entryId !== null && !(manifest.timeline ?? []).some((e) => e?.id === row.entryId)) {
+ errors.push(`entryId ${row.entryId} is not an entry of the timeline`);
+ }
+ if (errors.length) throw new Error(errors.join("; "));
+
+ // ---- the declared fields (validateFields types and scopes them) ----
+ try {
+ const { set, clear } = validateFields(row, fieldPatch, schema, ledger);
+ Object.assign(row, set);
+ for (const k of clear) delete row[k];
+ } catch (err) {
+ throw new Error(err instanceof Error ? err.message : String(err));
+ }
+ for (const k of unset) if (declared.has(k)) delete row[k];
+
+ if (row.display === undefined || row.display === null || row.display === "") {
+ row.display = measureDisplay({ ...row, display: null }, schema);
+ }
+ const gaps = measureGaps(row, schema);
+ if (gaps.length) throw new Error(`the row is not adjudicated: ${gaps.join(", ")}`);
+ return row;
+}
+
+/**
+ * What still names a row -- the timeline entries that pin it (`claim: "<id>"`)
+ * and the rows that refer to it (`promise`, a declared rowRef field) -- for
+ * `rm` to refuse with.
+ *
+ * @returns {string[]}
+ */
+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)`);
+ 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;
+ if (r.promise === id) out.push(`row ${r.id} names it (promise)`);
+ for (const k of refs) if (r[k] === id) out.push(`row ${r.id} refers to it (${k})`);
+ }
+ return out;
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -67,6 +67,7 @@ import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umto
import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration";
import { termWords, validatePostsRender } from "umtool-report-to-video/post-redact";
import { parseMuteFrom } from "./playback.mjs";
+import { isMeasureLedger, ledgerRowOf, ledgerRowReferences } from "./ledgerRows.mjs";
import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs";
import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources";
import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs";
@@ -1270,6 +1271,79 @@ export async function updateClaim(dir, claimId, patch, { token = null } = {}) {
// ---------------------------------------------------------------------------
+// A MEASURE ledger's rows (weight video rev 9): added, patched and removed
+// whole, through ledgerRows.mjs's checks -- the one way a row gets into the
+// ledger the instruments draw from (`umtool ledger <p> add|set|rm`).
+// ---------------------------------------------------------------------------
+
+/**
+ * Add one row to a measure ledger, checked (ledgerRows.mjs ledgerRowOf).
+ *
+ * @param {string} dir
+ * @param {Record<string, unknown>} row
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ row: Record<string, unknown>, token: string | null }>}
+ */
+export async function addLedgerRow(dir, row, { token = null } = {}) {
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ const made = ledgerRowOf(manifest, null, row);
+ manifest.ledger = [...(Array.isArray(manifest.ledger) ? manifest.ledger : []), made];
+ return { row: made, token: await writeManifestAtomic(dir, manifest) };
+ });
+}
+
+/**
+ * Patch one row of a measure ledger: `patch` sets keys, `unset` removes them;
+ * the row that results is checked whole.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {Record<string, unknown>} patch
+ * @param {{ token?: string | null, unset?: string[] }} [opts]
+ */
+export async function updateLedgerRow(dir, id, patch, { token = null, unset = [] } = {}) {
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : [];
+ const i = ledger.findIndex((r) => r?.id === id);
+ if (i < 0) throw new Error(`no ledger row ${id}`);
+ if (patch.id !== undefined && patch.id !== id) throw new Error("a row's id is not changed by set (add the new row, then rm the old)");
+ const made = ledgerRowOf(manifest, ledger[i], patch, { unset });
+ ledger[i] = made;
+ return { row: made, token: await writeManifestAtomic(dir, manifest) };
+ });
+}
+
+/**
+ * Remove one row of a measure ledger. Refused while anything names it -- a
+ * timeline entry's pin, a check of a promise, a declared row reference.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function removeLedgerRow(dir, id, { token = null } = {}) {
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ if (!isMeasureLedger(manifest)) throw new Error('the manifest has no measure ledger (ledgerSchema.kind "measure")');
+ const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : [];
+ const row = ledger.find((r) => r?.id === id);
+ if (!row) throw new Error(`no ledger row ${id}`);
+ const refs = ledgerRowReferences(manifest, id);
+ if (refs.length) throw new Error(`${id} is still named: ${refs.join("; ")}`);
+ manifest.ledger = ledger.filter((r) => r?.id !== id);
+ return { row, token: await writeManifestAtomic(dir, manifest) };
+ });
+}
+
+// ---------------------------------------------------------------------------
// The DECK: per-entry on-screen text, and the render.chrome block that turns
// the deck on.
//
diff --git a/umtool/lib/report/measureCli.mjs b/umtool/lib/report/measureCli.mjs
@@ -0,0 +1,130 @@
+// `umtool measure` (weight video rev 9): the measure slice a cut's
+// instruments would draw from (report-to-video measure-slice.mjs), printed --
+// every event at its cut second, the hidden rows, and the totals. Reads only.
+//
+// umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]
+//
+// The cut's seconds: the take's built schedule (takes/<t>/out/sourced/
+// schedule.json) when there is one, else an estimate from the manifest. Each
+// figure is timed by its clip's words (measure-words.mjs: the project's
+// channels tree, then the corpus) -- read off disk, never fetched.
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { CHANNELS_DIR } from "../paths.mjs";
+import { resolveTakeManifest, takePlayDir } from "./takeManifest.mjs";
+import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video";
+import { estimateSchedule, playWindow } from "umtool-report-to-video/deck";
+import { renderGaps } from "umtool-report-to-video/gaps";
+import { measureSlice, pinnedRows } from "umtool-report-to-video/measure-slice";
+import { measureClipWords } from "umtool-report-to-video/measure-words";
+import { SHADOW_CHANNELS, channelsDirFor } from "umtool-report-to-video/sources";
+
+export const MEASURE_USAGE = [
+ "usage: umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]",
+ "",
+ "The measure slice of the cut (render.chrome.deck.measure; --scopes / --scale / --as-of override it): every ledger row",
+ "in scope the cut shows, at the cut second its figure is said (its clip's words; else the quote's start),",
+ "the rows no entry shows, the state after each, and the totals -- the odometer's runs (the highest real-time",
+ "loss claim of each run, summed), NET, the goals, the diets, the promises. The cut's seconds are the take's",
+ "built schedule.json with --take, else an estimate. --json prints the slice itself.",
+].join("\n");
+
+class CliError extends Error {}
+
+const exists = (p) => stat(p).then(() => true, () => false);
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const clock = (t) => {
+ const s = Math.max(0, Math.round(t));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
+};
+
+/**
+ * @param {string[]} args the words after `measure`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, channelsDir?: string }} [opts]
+ * @returns {Promise<number>} the exit code
+ */
+export async function measureCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), channelsDir = CHANNELS_DIR } = {}) {
+ const valued = new Set(["--take", "--scopes", "--scale", "--as-of"]);
+ const flags = new Map();
+ const words = [];
+ for (let i = 0; i < args.length; i += 1) {
+ if (valued.has(args[i])) { flags.set(args[i], args[i + 1] ?? ""); i += 1; } else if (!args[i].startsWith("--")) words.push(args[i]);
+ }
+ const json = args.includes("--json");
+ try {
+ const [projectArg] = words;
+ if (!projectArg || args.includes("--help")) {
+ err(MEASURE_USAGE);
+ return 2;
+ }
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
+ const project = r.project;
+ const take = flags.get("--take") ?? null;
+ const base = take ? (await resolveTakeManifest(project.dir, take)).manifest : await readManifest(project.dir);
+ if (!base) throw new CliError(`${project.id} has no manifest`);
+ if (!isObj(base.ledgerSchema) || base.ledgerSchema.kind !== "measure") throw new CliError(`${project.id} has no measure ledger (ledgerSchema.kind "measure")`);
+
+ // The settings the slice is made with: the manifest's, with the flags over them.
+ const m = JSON.parse(JSON.stringify(base));
+ m.render = isObj(m.render) ? m.render : {};
+ const chrome = isObj(m.render.chrome) ? m.render.chrome : { engine: "hyperframes", layout: "deck", deck: {} };
+ const deck = isObj(chrome.deck) ? chrome.deck : {};
+ const measure = { ...(isObj(deck.measure) ? deck.measure : {}) };
+ if (flags.has("--scopes")) measure.scopes = String(flags.get("--scopes")).split(",").map((s) => s.trim()).filter(Boolean);
+ if (flags.has("--as-of")) measure.asOf = flags.get("--as-of");
+ if (flags.has("--scale")) {
+ const m2 = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(flags.get("--scale")));
+ if (!m2) throw new CliError("--scale is MIN-MAX, in the ledger's unit (220-400)");
+ measure.scale = { min: Number(m2[1]), max: Number(m2[2]) };
+ }
+ m.render.chrome = { ...chrome, layout: "deck", deck: { ...deck, measure } };
+ const cut = selectVariant(m, DEFAULT_VARIANT);
+ const entries = cut.timeline ?? [];
+
+ // The cut's seconds: the take's built schedule, else an estimate.
+ let schedule = null;
+ let from = "an estimate from the manifest";
+ if (take) {
+ const p = path.join(takePlayDir(project.dir, take), "out", DEFAULT_VARIANT, "schedule.json");
+ const doc = await readFile(p, "utf8").then((t) => JSON.parse(t), () => null);
+ if (Array.isArray(doc?.segments)) { schedule = doc; from = `take ${take}'s schedule.json`; }
+ }
+ if (!schedule) schedule = estimateSchedule(cut);
+
+ const ledger = cut.measureLedger ?? base.ledger ?? [];
+ const ids = new Set(pinnedRows(entries, ledger).keys());
+ const own = channelsDirFor(project.dir, base, { shadowExists: await exists(path.join(project.dir, SHADOW_CHANNELS)) });
+ const wordsOf = await measureClipWords({ entries, ids, provenance: base.provenance ?? {}, channelsDirs: [own, channelsDir] });
+ const clk = new Map(entries.filter((e) => e.type === "clip").map((e) => [e.id, playWindow(e, cut.render).from]));
+ const gaps = new Map(entries.filter((e) => e.type === "clip" && renderGaps(e, cut.render).length).map((e) => [e.id, renderGaps(e, cut.render)]));
+ const slice = measureSlice({ ...cut, ledger }, schedule, { words: wordsOf, clock: clk, gaps, asOf: measure.asOf ?? null });
+
+ if (json) {
+ out(JSON.stringify(slice, null, 2));
+ return 0;
+ }
+ const by = slice.events.reduce((a, e) => ((a[e.tFrom] = (a[e.tFrom] ?? 0) + 1), a), {});
+ out(`${project.id}${take ? ` · take ${take}` : ""} · the cut's seconds: ${from}`);
+ out(`scopes ${slice.scopes.join(", ")} · scale ${slice.scale.min}–${slice.scale.max} ${slice.unit} · as of ${slice.asOfRender}`);
+ out(`${slice.events.length} event(s) on camera (timed by: ${Object.entries(by).map(([k, n]) => `${k} ${n}`).join(", ")}) · ${slice.hidden.length} hidden`);
+ out("");
+ for (const e of slice.events) {
+ out(` ${clock(e.t).padStart(6)} ${String(e.row).padEnd(6)} ${String(e.kind).padEnd(12)} ${String(e.display ?? "").padEnd(24)} ${e.run !== null ? `run ${e.run}`.padEnd(7) : "".padEnd(7)} ${String(e.tFrom).padEnd(7)} ${e.segment}`);
+ }
+ const t = slice.totals;
+ out("");
+ out(`lost (his words): ${t.lost} ${slice.unit} across ${t.runs} run(s) — ${t.lostRuns.map((x) => `${x.start} ${x.peak} (${x.row})`).join(" · ")}`);
+ out(`net: ${t.net.from ?? "—"} → ${t.net.to ?? "—"} = ${t.net.value ?? "—"} ${slice.unit} (${t.net.fromRow ?? "—"} → ${t.net.toRow ?? "—"})`);
+ out(`goals: ${t.goals}${Object.keys(t.goalRepeats).length ? ` (${Object.entries(t.goalRepeats).map(([k, n]) => `"${k}" ×${n}`).join(", ")})` : ""} · diets: ${t.diets} · peak drift: ${t.peakDrift.join(" → ") || "—"} · under 300: ${t.under300.said}${t.under300.rows.length ? ` (${t.under300.rows.join(", ")})` : ""}`);
+ for (const p of t.promises) out(`promise ${p.row}, said ${p.said}: "${p.what}"${p.due ? ` · due ${p.due}` : ""} · ${p.kept ? "KEPT" : "not kept"}${p.checks.length ? ` · checked ${p.checks.join(", ")}` : ""}${(p.claims ?? []).map((c) => ` · ${c.speaker ?? "he"} says ${c.label ?? c.row}${c.paidOn ? ` (paid ${c.paidOn})` : ""}`).join("")}${p.outcome ? ` · ${String(p.outcome.kind).toUpperCase()} ${p.outcome.date ?? ""} (${p.outcome.row})` : ""}`);
+ out(`span: ${t.span.from ?? "—"} → ${t.span.to ?? "—"}`);
+ return 0;
+ } catch (e) {
+ err(`umtool measure: ${e instanceof Error ? e.message : String(e)}`);
+ return 1;
+ }
+}
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -165,6 +165,8 @@ import {
// The effects region (`render.chrome.fx`, release 35): pure, in fx.mjs.
import { fxOn, fxQuoteSpan, fxShiftConflicts, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs";
import { marksOf, stampsDrawn, validateClaims } from "./factcheck.mjs";
+import { measureOn, measureSettingsProblems, pinnedRows } from "./measure-slice.mjs";
+import { measureClipWords } from "./measure-words.mjs";
import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs";
import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blurSpan, clipBlurOf, fittedSize, validateClipBlurEntries } from "./clip-blur.mjs";
import { validateFinaleEntries } from "./finale.mjs";
@@ -384,7 +386,11 @@ export function selectVariant(manifest, variant = DEFAULT_VARIANT) {
// without the key, the same object again.
// A look preset (`preset`, presets.mjs) is the base layer under it all:
// laid first, so the brand and the intro read the render as it will be.
- return introManifest(brandManifest(presetManifest({ ...manifest, variant, timeline, ledger, ...(posts !== undefined ? { posts } : {}) })));
+ // A MEASURE ledger keeps its whole record beside the cut's rows: the
+ // instruments' totals and the finale's hidden rows are the rows no clip is
+ // behind (measure-slice.mjs). A headcount manifest gains nothing.
+ const measureLedger = manifest.ledgerSchema?.kind === "measure" ? { measureLedger: manifest.ledger ?? [] } : {};
+ return introManifest(brandManifest(presetManifest({ ...manifest, variant, timeline, ledger, ...measureLedger, ...(posts !== undefined ? { posts } : {}) })));
}
/**
@@ -6087,6 +6093,10 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du
clipGaps ??= new Map();
clipGaps.set(entries[i].id, recordGaps(rec));
}
+ // The measure slice (measure-slice.mjs): read only for a cut that writes
+ // one -- each clip's words for the second its figure is said, and the
+ // source second its segment starts at.
+ const measure = measureOn(manifest) ? await measureInputs({ manifest, entries, segments, render, provenance }) : null;
// The variant's posts, placed on the clips this cut plays with their real
// upload dates. A manifest without posts writes the schedule it always did.
return deckSchedule({
@@ -6096,10 +6106,35 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du
...(clipClock ? { clipClock } : {}),
...(clipGaps ? { clipGaps } : {}),
...(estimated ? { estimated: true } : {}),
+ ...(measure ? { measure } : {}),
});
}
/**
+ * What deckSchedule needs for a measure slice that a manifest alone cannot
+ * give: the whole ledger, the words of each clip that shows a measure row
+ * (measure-words.mjs: the project's channels tree, then the corpus, then the
+ * build's cue reader), and the source second each one's segment starts at
+ * (its cut record's).
+ */
+async function measureInputs({ manifest, entries, segments, render, provenance }) {
+ const ledger = manifest.measureLedger ?? manifest.ledger ?? [];
+ const pins = pinnedRows(entries, ledger);
+ const ids = new Set(pins.keys());
+ const words = await measureClipWords({
+ entries, ids, provenance, channelsDirs: [FX_CHANNELS_DIR, DEFAULT_CHANNELS_DIR], cues: (e) => montageCues(e, provenance),
+ });
+ const clock = new Map();
+ for (let i = 0; i < entries.length; i += 1) {
+ if (!ids.has(entries[i].id) || !segments[i]) continue;
+ const rec = await readCutRecord(segments[i]).catch(() => null);
+ if (Number.isFinite(rec?.start)) clock.set(entries[i].id, rec.start);
+ }
+ for (const [id, w] of words) EMIT("log", { message: `measure: ${id}'s figures timed by its ${w.from}` });
+ return { ledgerSchema: manifest.ledgerSchema, ledger, words, clock, render };
+}
+
+/**
* The chat for the clips that ask for it (`chat: true`, chat.mjs): each
* clip's video's `live_chat.cues.json` (SOURCE seconds), and `clock` the
* source second each clip's segment starts at (its cut record's, else the
@@ -6525,7 +6560,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),
+ ...validateGapEntries(whole), ...measureSettingsProblems(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -18,6 +18,7 @@ import { createHash } from "node:crypto";
import { archiveMomentUrl } from "./site-links.mjs";
import { playEdges, soundEdges as soundEdgesOf, soundOnSegment } from "./mute.mjs";
import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs";
+import { measureOn, measureSlice } from "./measure-slice.mjs";
import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs";
@@ -179,8 +180,9 @@ export function validateChrome(chrome, render = {}) {
// (counter.mjs: the tally's named series).
// `rail` (rail.mjs: `{labels}`) likewise has no default to fill, nor
// `sectionTitle` (section-title.mjs: the current section's name).
- // `dial`, `odometer` and `trail` (instruments.mjs: the measure's instruments) likewise.
- unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale", "claims", "counter", "rail", "sectionTitle", "dial", "odometer", "trail"], w, errors);
+ // `measure` (measure-slice.mjs: the measure ledger's slice for the
+ // instruments) likewise, and `dial`, `odometer`, `trail` (instruments.mjs: the instruments).
+ unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale", "claims", "counter", "rail", "sectionTitle", "measure", "dial", "odometer", "trail"], w, errors);
deckChecked = true;
}
errors.push(...entry.validate(settingValue(chrome, entry), { render, chrome, deck: d, where: w }));
@@ -1220,7 +1222,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin
*/
export function deckSchedule({
entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null,
- fxWords = null, fxClock = null, clipClock = null, clipGaps = null, chat = null,
+ fxWords = null, fxClock = null, clipClock = null, clipGaps = null, chat = null, measure = null,
}) {
const deck = resolveDeck(render);
// A clip's gaps (gaps.mjs) on its segment: its cut record's as built
@@ -1407,6 +1409,23 @@ export function deckSchedule({
doc.finale = { ...doc.finale, box, railBottom: room.railBottom, ...(room.textScale !== 1 ? { textScale: room.textScale } : {}) };
if (was && doc.moves) doc.moves = doc.moves.map((m) => (m.to === was ? { ...m, to: box } : m));
}
+ // The measure slice (measure-slice.mjs): a measure ledger's rows in the
+ // cut's clock and the instruments' state after each, for the dial, the
+ // odometer and the rest. Only with a measure ledger and
+ // `render.chrome.deck.measure`: a cut without them writes what it did.
+ // `measure` is `{ ledgerSchema, ledger, words?, clock?, asOf? }` -- the
+ // WHOLE ledger (a variant keeps only its pinned rows), each clip's words
+ // and the source second its segment starts at (the cut record's; else the
+ // play window's, here).
+ if (measure && measureOn({ ledgerSchema: measure.ledgerSchema, render })) {
+ const clock = new Map(entries.filter((e) => e.type === "clip").map((e) => [e.id, measure.clock?.get(e.id) ?? playWindow(e, render).from]));
+ const gaps = new Map(entries.filter((e) => e.type === "clip" && gapsFor(e).length).map((e) => [e.id, gapsFor(e)]));
+ doc.measure = measureSlice(
+ { ledgerSchema: measure.ledgerSchema, ledger: measure.ledger ?? [], render, timeline: entries },
+ doc,
+ { words: measure.words ?? null, clock, gaps, asOf: measure.asOf ?? null },
+ );
+ }
return doc;
}
@@ -1904,6 +1923,8 @@ export function estimateSchedule(manifest, { metas = [], noXfade = false } = {})
metas,
estimated: true,
frameScan: manifest.frameScan ?? null,
+ // A measure ledger's slice, timed by the quotes (no words in an estimate).
+ ...(manifest.ledgerSchema ? { measure: { ledgerSchema: manifest.ledgerSchema, ledger: manifest.measureLedger ?? manifest.ledger ?? [] } } : {}),
});
}
diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs
@@ -394,10 +394,36 @@ export function claimKnobs(claim) {
export function rawMarksOf(entry) {
if (!isObj(entry)) return [];
if (Array.isArray(entry.claims)) return entry.claims;
+ // A `claim` written as a string is a LEDGER PIN (ledgerPinOf), not a mark.
+ if (typeof entry.claim === "string") return [];
return entry.claim === undefined || entry.claim === null ? [] : [entry.claim];
}
/**
+ * An entry's LEDGER PIN: its `claim` written as a ledger row's id (`"w118"`)
+ * -- the row the entry shows, the way a measure ledger's cut names its rows --
+ * or null. A pin is not a fact-check mark: it stamps nothing and counts
+ * nothing here (measure-slice.mjs reads it).
+ */
+export function ledgerPinOf(entry) {
+ if (!isObj(entry) || typeof entry.claim !== "string") return null;
+ const id = entry.claim.trim();
+ return id || null;
+}
+
+/**
+ * Whether this manifest reads a string `claim` as a ledger pin: a measure
+ * ledger (`ledgerSchema.kind: "measure"`), or a manifest with no fact-check
+ * marks at all. A manifest that stamps verdicts keeps refusing a string, as
+ * it always has: there, `claim` is `{ id, verdict }`.
+ */
+export function pinsLedgerRows(manifest) {
+ if (isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure") return true;
+ const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ return !timeline.some((e) => rawMarksOf(e).some(isObj));
+}
+
+/**
* A `claims` value, normalised: each mark through normalizeClaim (its errors
* named `claims[k].…`), 1 to CLAIM_MARKS_MAX of them, each id once. Throws a
* sentence on a shape no writer should store.
@@ -461,6 +487,8 @@ export function validateClaims(manifest) {
const series = resolveCounter(manifest?.render).order;
const verdictOf = new Map();
const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const pins = pinsLedgerRows(manifest);
+ const rowIds = new Set((Array.isArray(manifest?.ledger) ? manifest.ledger : []).map((r) => (isObj(r) ? r.id : null)));
// The last entry carrying each id: a mark stamps there, and only there.
const lastOf = new Map();
timeline.forEach((e, i) => {
@@ -474,6 +502,12 @@ export function validateClaims(manifest) {
const key = many ? "claims" : "claim";
if (many && one) { errors.push(`${where}: claim and claims are both set -- one mark is \`claim\`, two or more \`claims\``); return; }
if (e.type === "teaser") { errors.push(`${where}.${key}: a teaser is not evidence for a claim`); return; }
+ // A ledger pin (`claim: "<row id>"`), where the manifest reads one: it
+ // must name a row of the ledger, and is nothing more to check here.
+ if (!many && typeof e.claim === "string" && pins) {
+ if (!rowIds.has(e.claim.trim())) errors.push(`${where}.claim "${e.claim}" names no ledger row`);
+ return;
+ }
let marks;
try {
marks = many ? normalizeMarks(e.claims, { series }) : [normalizeClaim(e.claim, { series })];
diff --git a/umtool/report-to-video/factcheck.test.mjs b/umtool/report-to-video/factcheck.test.mjs
@@ -11,7 +11,7 @@ import path from "node:path";
import test from "node:test";
import {
- claimOf, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, normalizeClaim, originalUrlAt, resolveFactcheck, roundStamps, STAMP_MOTION, stampSchedule,
+ claimOf, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, ledgerPinOf, marksOf, normalizeClaim, pinsLedgerRows, rawMarksOf, originalUrlAt, resolveFactcheck, roundStamps, STAMP_MOTION, stampSchedule,
TALLY_LABEL, TALLY_POP, tallyCues, tallyLabelOf, tallyLabelWidth, tallyOf, tallyPopIns, tallyShowAt, tallySteps, tallyVerdicts, validateClaims, validateFactcheck, VERDICTS,
} from "./factcheck.mjs";
import {
@@ -90,6 +90,31 @@ test("validateClaims: shape, never on a teaser, one verdict per claim id; the re
assert.match(errs[2], /timeline\[3\] \(c9\)\.claim\.verdict must be one of/);
});
+test("a ledger pin (claim: \"<row id>\") is a measure ledger's, and a stamping manifest still refuses one", () => {
+ const ledger = [{ id: "w118" }, { id: "r96" }];
+ const measure = {
+ ledgerSchema: { kind: "measure" },
+ ledger,
+ timeline: [{ type: "clip", id: "c46", claim: "w118" }, { type: "clip", id: "c36", claim: "r96" }, { ...ENTRIES[0] }],
+ };
+ // A measure ledger reads a string as the row the entry shows, beside any marks.
+ assert.deepEqual(validateClaims(measure), []);
+ assert.equal(ledgerPinOf(measure.timeline[0]), "w118");
+ assert.equal(ledgerPinOf(ENTRIES[0]), null);
+ assert.deepEqual(rawMarksOf(measure.timeline[0]), [], "a pin is not a mark");
+ assert.deepEqual(marksOf(measure.timeline[0]), []);
+ assert.equal(pinsLedgerRows(measure), true);
+ // …and it must name a row.
+ const bad = validateClaims({ ...measure, timeline: [{ type: "clip", id: "c1", claim: "w999" }] });
+ assert.deepEqual(bad, ['timeline[0] (c1).claim "w999" names no ledger row']);
+ // A manifest with no fact-check marks reads one the same way.
+ assert.deepEqual(validateClaims({ ledger, timeline: [{ type: "clip", id: "c1", claim: "w118" }] }), []);
+ // One that stamps verdicts refuses it, as it always did.
+ const stamping = { ledger, timeline: [ENTRIES[0], { type: "clip", id: "c1", claim: "w118" }] };
+ assert.equal(pinsLedgerRows(stamping), false);
+ assert.match(validateClaims(stamping).join("\n"), /timeline\[1\] \(c1\)\.claim must be \{ id, verdict \}/);
+});
+
// ---- the settings ---------------------------------------------------------------
test("resolveFactcheck: every default, a verdict's label and colour filled on their own", () => {
diff --git a/umtool/report-to-video/fixtures/measure-sample.manifest.json b/umtool/report-to-video/fixtures/measure-sample.manifest.json
@@ -0,0 +1,178 @@
+{
+ "_note": "A hand-built miniature MEASURE ledger. Eleven claims, two regimes, one long silence and one predicate apiece — small enough to check by eye against the rendered chart, complete enough that every branch of measureTotals() is exercised. Used by ledger-totals.test.mjs and by the render smoke test.",
+ "schemaVersion": 1,
+ "slug": "measure-sample",
+ "title": "A Measure Fixture",
+ "subtitle": "one quantity, and what he says he is doing about it",
+ "generatedOn": "2026-08-30",
+ "provenance": {
+ "channelSlug": "testchan",
+ "siteOrigin": "https://archive.example"
+ },
+ "ledgerSchema": {
+ "kind": "measure",
+ "unit": "lb",
+ "yLabel": "POUNDS",
+ "yMin": 280,
+ "yMax": 420,
+ "from": "2025-01-01",
+ "to": "2026-09-01",
+ "bandGapDays": 60,
+ "tracks": [
+ { "key": "weight", "role": "value", "label": "His weight", "shortLabel": "WEIGHT", "color": "#22AB83" },
+ { "key": "regime", "role": "regime", "label": "What he says he is on", "shortLabel": "ON", "color": "#D2732F" }
+ ],
+ "forms": ["current", "past", "delta", "goal", "overweight_by", "status"],
+ "regimes": [
+ { "key": "keto", "label": "Keto", "color": "#D2732F" },
+ { "key": "carnivore", "label": "Carnivore", "color": "#6A82DC" },
+ { "key": "off", "label": "No diet", "color": "#98A29B" }
+ ]
+ },
+ "render": {
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "audioRate": 48000,
+ "audioChannels": 2,
+ "headerHeight": 56,
+ "footerHeight": 100,
+ "palette": {
+ "bg": "#0F1312",
+ "fg": "#EDF0EC",
+ "muted": "#98A29B",
+ "accent": "#22AB83",
+ "amber": "#E8A33F"
+ },
+ "rail": {
+ "width": 500,
+ "rowHeight": 38,
+ "tallyRowHeight": 40,
+ "tallyTop": 76,
+ "pad": 22,
+ "slide": 0.55,
+ "rule": "#2A322F",
+ "cellWidth": 170,
+ "counter": { "label": "Regime changes", "word": "switches" },
+ "headings": {
+ "title": "THE WEIGHT LEDGER",
+ "sub": "every figure he has given, as he gave it",
+ "tally": "WHERE HE SAYS HE IS NOW"
+ },
+ "tracks": [
+ { "key": "weight", "label": "His weight", "shortLabel": "WEIGHT", "color": "#22AB83" },
+ { "key": "regime", "label": "What he is on", "shortLabel": "ON", "color": "#D2732F" }
+ ]
+ }
+ },
+ "ledger": [
+ {
+ "id": "w1", "date": "2025-02-10", "scope": "weight", "population": "current",
+ "value": 380, "display": "380 lb",
+ "label": "opens the year at three-eighty",
+ "quote": "I'm three hundred and eighty pounds right now",
+ "src": "A stream @ 12:04", "channel": "testchan", "video": "vid1", "cite": 3,
+ "scopeBasis": "“I'm … right now” — his own weight, today",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "entryId": "c01"
+ },
+ {
+ "id": "w2", "date": "2025-02-18", "scope": "weight", "population": "current",
+ "value": 340, "display": "340 lb",
+ "label": "forty pounds lighter, eight days later",
+ "quote": "I'm at three forty",
+ "src": "A stream @ 04:11", "channel": "testchan", "video": "vid1", "cite": 9,
+ "scopeBasis": "“I'm at” — a reading of himself",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "entryId": "c02"
+ },
+ {
+ "id": "r1", "date": "2025-03-01", "scope": "regime", "population": "status",
+ "value": "keto", "event": "start", "display": "Keto",
+ "label": "starts keto",
+ "quote": "day one of keto, we're doing this",
+ "src": "A stream @ 00:30", "channel": "testchan", "video": "vid1", "cite": 12,
+ "scopeBasis": "“day one of keto” — he names the diet and the start",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "entryId": "c03"
+ },
+ {
+ "id": "r2", "date": "2025-03-20", "scope": "regime", "population": "status",
+ "value": "carnivore", "event": "start", "display": "Carnivore",
+ "label": "starts carnivore, nineteen days later",
+ "quote": "I'm carnivore now, meat only",
+ "src": "A stream @ 41:02", "channel": "testchan", "video": "vid2", "cite": 1,
+ "scopeBasis": "“I'm carnivore now” — a new regime, and no word about the last",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "w3", "date": "2025-11-05", "scope": "weight", "population": "current",
+ "value": 360, "display": "≈360 lb", "hedged": true,
+ "label": "about three-sixty",
+ "quote": "I'm about three sixty give or take",
+ "src": "A stream @ 08:20", "channel": "testchan", "video": "vid1", "cite": 15,
+ "scopeBasis": "“about … give or take” — a hedge, but his own figure",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "r3", "date": "2026-01-15", "scope": "regime", "population": "status",
+ "value": "carnivore", "event": "stop", "display": "off Carnivore",
+ "label": "quits carnivore",
+ "quote": "I'm done with the carnivore thing",
+ "src": "A stream @ 55:00", "channel": "testchan", "video": "vid2", "cite": 4,
+ "scopeBasis": "“I'm done with” — a stop, named",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "w4", "date": "2026-02-01", "asOf": "2025-02-15", "scope": "weight",
+ "population": "past", "value": 400, "display": "400 lb",
+ "label": "says he was four hundred a year ago",
+ "quote": "I was four hundred pounds back then",
+ "src": "A stream @ 22:15", "channel": "testchan", "video": "vid1", "cite": 18,
+ "scopeBasis": "“back then” — he is describing February of last year",
+ "scopeConfidence": "read", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "g1", "date": "2026-03-01", "scope": "weight", "population": "goal",
+ "value": 300, "display": "goal 300",
+ "label": "wants three hundred by Christmas",
+ "quote": "I want to be at three hundred by Christmas",
+ "src": "A stream @ 02:40", "channel": "testchan", "video": "vid1", "cite": 6,
+ "scopeBasis": "“I want to be at” — a target, not a reading",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "d1", "date": "2026-04-01", "scope": "weight", "population": "delta",
+ "value": -40, "display": "−40 lb",
+ "label": "down forty",
+ "quote": "I'm down forty pounds",
+ "src": "A stream @ 11:11", "channel": "testchan", "video": "vid1", "cite": 9,
+ "scopeBasis": "“down forty pounds” — a change, with no absolute beside it",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "o1", "date": "2026-05-01", "scope": "weight", "population": "overweight_by",
+ "value": 100, "display": "100 over",
+ "label": "the hundred-pounds-overweight refrain",
+ "quote": "I'm about a hundred pounds overweight",
+ "src": "A stream @ 33:03", "channel": "testchan", "video": "vid1", "cite": 12,
+ "scopeBasis": "“overweight” — relative to a number he never gives",
+ "scopeConfidence": "read", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "r4", "date": "2026-06-01", "scope": "regime", "population": "status",
+ "value": "keto", "event": "start", "display": "Keto",
+ "label": "back on keto",
+ "quote": "keto, day three, and I feel great",
+ "src": "A stream @ 01:05", "channel": "testchan", "video": "vid2", "cite": 7,
+ "scopeBasis": "“keto, day three” — a restart he dates himself",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ },
+ {
+ "id": "w5", "date": "2026-08-01", "scope": "weight", "population": "current",
+ "value": 337, "display": "337 lb",
+ "label": "three thirty-seven",
+ "quote": "the scale said three thirty seven this morning",
+ "src": "A stream @ 05:50", "channel": "testchan", "video": "vid1", "cite": 3,
+ "scopeBasis": "“the scale said” — a reading he took",
+ "scopeConfidence": "clear", "valueKind": "uttered", "flags": [], "unsourced": true
+ }
+ ]
+}
diff --git a/umtool/report-to-video/fixtures/measure-two-track.manifest.json b/umtool/report-to-video/fixtures/measure-two-track.manifest.json
@@ -0,0 +1,489 @@
+{
+ "_note": "A hand-built MEASURE ledger with TWO regime tracks — what he eats and what he drinks — plus a GOAL lane, ghosts, the gap bar and the totals line. Every case `broke_pledge` has to get right is in here: a pledge broken in two days, a second admission under the same pledge, a pledge that held thirty-one, and one he ended before drinking again. Used by ledger-totals.test.mjs.",
+ "schemaVersion": 1,
+ "slug": "measure-two-track",
+ "title": "A Two-Track Measure Fixture",
+ "subtitle": "one quantity, two regimes, and the pledges he breaks",
+ "generatedOn": "2026-08-31",
+ "provenance": {
+ "channelSlug": "testchan",
+ "siteOrigin": "https://archive.example"
+ },
+ "ledgerSchema": {
+ "kind": "measure",
+ "unit": "lb",
+ "yLabel": "POUNDS",
+ "yMin": 260,
+ "yMax": 360,
+ "from": "2025-06-01",
+ "to": "2026-08-01",
+ "bandGapDays": 60,
+ "pledgeDays": 30,
+ "tracks": [
+ {
+ "key": "weight",
+ "role": "value",
+ "label": "What he says he weighs",
+ "shortLabel": "WEIGHT",
+ "color": "#22AB83"
+ },
+ {
+ "key": "regime",
+ "role": "regime",
+ "label": "The diet he names",
+ "shortLabel": "DIET",
+ "color": "#E0913C",
+ "regimes": [
+ "keto",
+ "carnivore",
+ "off"
+ ]
+ },
+ {
+ "key": "drinking",
+ "role": "regime",
+ "label": "What he says he drinks",
+ "shortLabel": "DRINKING",
+ "color": "#C9534B",
+ "regimes": [
+ "dry",
+ "cutting",
+ "drinking",
+ "off"
+ ]
+ }
+ ],
+ "forms": [
+ "current",
+ "past",
+ "delta",
+ "goal",
+ "goal_loss",
+ "overweight_by",
+ "status"
+ ],
+ "regimes": [
+ {
+ "key": "keto",
+ "label": "Keto",
+ "color": "#E0913C"
+ },
+ {
+ "key": "carnivore",
+ "label": "Carnivore",
+ "color": "#4E9BD8"
+ },
+ {
+ "key": "dry",
+ "label": "Dry",
+ "color": "#3FA9A0",
+ "kind": "pledge"
+ },
+ {
+ "key": "cutting",
+ "label": "Cutting back",
+ "color": "#8E97A8",
+ "kind": "pledge"
+ },
+ {
+ "key": "drinking",
+ "label": "Drinking",
+ "color": "#C9534B",
+ "kind": "lapse"
+ },
+ {
+ "key": "off",
+ "label": "Nothing",
+ "color": "#98A29B"
+ }
+ ]
+ },
+ "render": {
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "audioRate": 48000,
+ "audioChannels": 2,
+ "headerHeight": 56,
+ "footerHeight": 100,
+ "palette": {
+ "bg": "#0F1312",
+ "fg": "#EDF0EC",
+ "muted": "#98A29B",
+ "accent": "#22AB83",
+ "amber": "#E8A33F"
+ },
+ "rail": {
+ "width": 500,
+ "rowHeight": 38,
+ "tallyRowHeight": 40,
+ "pad": 22,
+ "slide": 0.55,
+ "rule": "#2A322F",
+ "cellWidth": 158,
+ "qrSize": 132,
+ "roster": false,
+ "ghosts": true,
+ "headings": {
+ "title": "",
+ "sub": "",
+ "tally": "NOW",
+ "order": "",
+ "roster": ""
+ },
+ "tracks": [
+ {
+ "key": "weight",
+ "label": "WEIGHT",
+ "shortLabel": "WEIGHT",
+ "color": "#22AB83"
+ },
+ {
+ "key": "weight",
+ "label": "GOAL",
+ "shortLabel": "GOAL",
+ "color": "#E8A33F",
+ "form": "goal"
+ },
+ {
+ "key": "regime",
+ "label": "DIET",
+ "shortLabel": "DIET",
+ "color": "#E0913C"
+ },
+ {
+ "key": "drinking",
+ "label": "DRINKING",
+ "shortLabel": "DRINKING",
+ "color": "#C9534B"
+ }
+ ],
+ "totals": {
+ "chips": [
+ "diets",
+ "pledges",
+ "broken",
+ "net"
+ ]
+ }
+ }
+ },
+ "ledger": [
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "w1",
+ "date": "2025-06-01",
+ "scope": "weight",
+ "population": "current",
+ "value": 340,
+ "display": "340 lb",
+ "label": "opens at three-forty",
+ "quote": "I'm three forty",
+ "entryId": "c01"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "g1",
+ "date": "2025-06-02",
+ "scope": "weight",
+ "population": "goal_loss",
+ "value": -40,
+ "display": "lose 40",
+ "deadline": "2025-12-31",
+ "label": "wants forty off by new year",
+ "quote": "forty pounds by new year",
+ "entryId": "c02"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "r1",
+ "date": "2025-06-10",
+ "scope": "regime",
+ "population": "status",
+ "value": "keto",
+ "event": "start",
+ "display": "Keto",
+ "label": "starts keto",
+ "quote": "day one of keto",
+ "entryId": "c03"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "w2",
+ "date": "2025-09-01",
+ "scope": "weight",
+ "population": "current",
+ "value": 317,
+ "display": "317 lb",
+ "label": "twenty-three down",
+ "quote": "three seventeen this morning",
+ "entryId": "c04"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "g2",
+ "date": "2025-10-01",
+ "scope": "weight",
+ "population": "goal",
+ "value": 280,
+ "display": "280",
+ "label": "the round number",
+ "quote": "I want to be at two eighty",
+ "entryId": "c05"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "r2",
+ "date": "2025-11-01",
+ "scope": "regime",
+ "population": "status",
+ "value": "carnivore",
+ "event": "start",
+ "display": "Carnivore",
+ "label": "carnivore now",
+ "quote": "meat only",
+ "entryId": "c06"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "p1",
+ "date": "2026-01-16",
+ "scope": "drinking",
+ "population": "status",
+ "value": "dry",
+ "event": "start",
+ "display": "Dry",
+ "label": "says he is done drinking",
+ "quote": "I decided to stop drinking",
+ "entryId": "c07"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "a1",
+ "date": "2026-01-18",
+ "scope": "drinking",
+ "population": "status",
+ "value": "drinking",
+ "event": "start",
+ "display": "Drinking",
+ "label": "had a few at the game",
+ "quote": "had a few at the Brewers game",
+ "entryId": "c08"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "a2",
+ "date": "2026-01-25",
+ "scope": "drinking",
+ "population": "status",
+ "value": "drinking",
+ "event": "on",
+ "display": "Drinking",
+ "label": "still drinking a week later",
+ "quote": "we were out again Saturday",
+ "entryId": "c09"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "p2",
+ "date": "2026-03-01",
+ "scope": "drinking",
+ "population": "status",
+ "value": "dry",
+ "event": "start",
+ "display": "Dry",
+ "label": "the second pledge",
+ "quote": "no drinking, none, I'm done",
+ "entryId": "c10"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "a3",
+ "date": "2026-04-01",
+ "scope": "drinking",
+ "population": "status",
+ "value": "drinking",
+ "event": "start",
+ "display": "Drinking",
+ "label": "a drink thirty-one days later",
+ "quote": "I had a beer last night",
+ "entryId": "c11"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "p3",
+ "date": "2026-05-01",
+ "scope": "drinking",
+ "population": "status",
+ "value": "cutting",
+ "event": "start",
+ "display": "Cutting back",
+ "label": "weekends only",
+ "quote": "weekends only from here",
+ "entryId": "c12"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "s1",
+ "date": "2026-05-10",
+ "scope": "drinking",
+ "population": "status",
+ "value": "cutting",
+ "event": "stop",
+ "display": "off Cutting back",
+ "label": "says the rule is over",
+ "quote": "that experiment's over",
+ "entryId": "c13"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "a4",
+ "date": "2026-05-15",
+ "scope": "drinking",
+ "population": "status",
+ "value": "drinking",
+ "event": "start",
+ "display": "Drinking",
+ "label": "drinking again, having said so",
+ "quote": "had a couple last night",
+ "entryId": "c14"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "w3",
+ "date": "2026-06-01",
+ "scope": "weight",
+ "population": "current",
+ "value": 305,
+ "display": "305 lb",
+ "label": "three-oh-five",
+ "quote": "the scale said three oh five",
+ "entryId": "c15"
+ },
+ {
+ "scopeBasis": "he says it about himself",
+ "scopeConfidence": "clear",
+ "valueKind": "uttered",
+ "flags": [],
+ "src": "A stream @ 00:00",
+ "channel": "testchan",
+ "video": "vid1",
+ "cite": 3,
+ "id": "w4",
+ "date": "2026-07-01",
+ "asOf": "2026-06-20",
+ "scope": "weight",
+ "population": "past",
+ "value": 312,
+ "display": "312 lb",
+ "label": "says he was three-twelve in June",
+ "quote": "I was three twelve a couple weeks back",
+ "entryId": "c16"
+ }
+ ]
+}
diff --git a/umtool/report-to-video/ledger-shared.mjs b/umtool/report-to-video/ledger-shared.mjs
@@ -0,0 +1,107 @@
+// The handful of things BOTH ledger kinds need, in one place.
+//
+// It exists because there are now two arithmetics over the same JSON shape --
+// `headcount` (ledger-totals.mjs) and `measure` (measure-totals.mjs) -- and the
+// alternative to this file is a cycle between them or a second copy of dateKey.
+// A second dateKey is the worse outcome by a distance: the month-only entries it
+// pads are exactly the rows a copy would get subtly wrong, and nothing would say
+// so until a chart drew a claim in the wrong year.
+//
+// Nothing here knows what a claim MEANS. Vocabulary, predicates and totals all
+// live in the kind's own module.
+
+export const isStr = (v) => typeof v === "string" && v.trim().length > 0;
+
+/** The confidence a scope adjudication carries. Kind-independent. */
+export const SCOPE_CONFIDENCE = ["clear", "read", "unresolved"];
+
+/** Whose number it is. Kind-independent: a midpoint is ours in any unit. */
+export const VALUE_KINDS = ["uttered", "derived", "synthetic"];
+
+// ---------------------------------------------------------------------------
+// Dates. Some entries are month-only ("2024-02") because that is all the source
+// supports. Sorting pads them to the first of the month, which puts them before
+// any dated claim in the same month rather than guessing a day.
+// ---------------------------------------------------------------------------
+export function dateKey(d) {
+ const s = String(d ?? "");
+ const m = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(s);
+ if (!m) return "9999-99-99";
+ return `${m[1]}-${m[2] ?? "01"}-${m[3] ?? "01"}`;
+}
+
+/** Days since the epoch, so an x scale is linear in real time, not in claims. */
+export const dayOf = (d) => Date.parse(`${dateKey(d)}T00:00:00Z`) / 86400000;
+
+/** Whole days from `a` to `b`, NaN-safe callers only. */
+export const daysBetween = (a, b) => dayOf(b) - dayOf(a);
+
+/** `2026-01-09` plus n days, back as an ISO date. */
+export function addDays(d, n) {
+ const t = new Date(`${dateKey(d)}T00:00:00Z`);
+ t.setUTCDate(t.getUTCDate() + n);
+ return t.toISOString().slice(0, 10);
+}
+
+/** Chronological, ties broken by ledger id so the order is total and stable. */
+export const chronological = (ledger) =>
+ [...(ledger ?? [])].sort((a, b) => {
+ const d = dateKey(a.date).localeCompare(dateKey(b.date));
+ return d !== 0 ? d : String(a.id).localeCompare(String(b.id));
+ });
+
+/**
+ * "6 days earlier", "3 months earlier" — how a predicate says WHEN in prose.
+ *
+ * Every predicate's `text` is read aloud off a card, so the gap is words and
+ * never a date arithmetic the viewer has to perform.
+ */
+export function gapWords(from, to) {
+ const days = Math.round(daysBetween(from, to));
+ if (!Number.isFinite(days)) return "earlier";
+ if (days <= 0) return "the same day";
+ if (days === 1) return "a day earlier";
+ if (days < 31) return `${days} days earlier`;
+ const months = Math.round(days / 30.44);
+ if (months < 24) return `${months} month${months === 1 ? "" : "s"} earlier`;
+ return `${Math.round(days / 365.25)} years earlier`;
+}
+
+// ---------------------------------------------------------------------------
+// What a ledger row is allowed to carry without declaring itself
+// ---------------------------------------------------------------------------
+
+/**
+ * Every key a ledger row may hold that the code already knows the meaning of.
+ *
+ * It exists so that `ledgerSchema.fields[]` can be the ONLY other way a key
+ * gets onto a row. A key in neither set is a field somebody added by hand or by
+ * script and never declared, which reads on the board as nothing at all: the
+ * arithmetic does not see it, the panel does not draw it, and the operator who
+ * wrote it has no way of knowing that. `umtool check` raises it by name.
+ *
+ * Kind-independent on purpose. Both arithmetics walk the same JSON shape, and a
+ * per-kind list would mean a `headcount` row and a `measure` row disagreeing
+ * about whether `event` is a real key -- which is a distinction neither the
+ * bench nor the inbox makes.
+ */
+export const LEDGER_BUILTIN_KEYS = new Set([
+ // identity, and where it came from
+ "id", "date", "asOf", "src", "channel", "video", "cite", "citeFrom", "quote",
+ // what it says
+ "scope", "population", "value", "event", "display", "label", "deadline",
+ // the adjudication
+ "scopeBasis", "scopeConfidence", "valueKind", "flags", "hedged", "unsourced",
+ // the cut
+ "entryId", "plotted", "hidden", "authorNote",
+ // the measure instruments (measure-slice.mjs): a loss claim's run (his
+ // words placing it), a loss told in the past with no asOf to give it
+ // (`retro`), a promise check's promise, whether it was kept, and a day a
+ // goal or a promise is due
+ "run", "retro", "promise", "kept", "due",
+ // who said it, when it is not the subject (a promise_claim's counterparty;
+ // such a row never moves the subject's numbers), and the day she says she paid
+ "speaker", "paidOn",
+ // how a promise ended (a promise_outcome's: kept, refunded, withdrawn)
+ "outcome",
+]);
diff --git a/umtool/report-to-video/ledger-totals.mjs b/umtool/report-to-video/ledger-totals.mjs
@@ -28,12 +28,127 @@
// screen that it is ours. That weakens "his stated total swings wildly" a little
// and makes it survive scrutiny.
+import {
+ SCOPE_CONFIDENCE,
+ VALUE_KINDS,
+ chronological,
+ dateKey,
+ gapWords,
+ isStr,
+} from "./ledger-shared.mjs";
+import {
+ measureGaps,
+ measureSchema,
+ measureTotals,
+ measureVocab,
+} from "./measure-totals.mjs";
+
+// Re-exported rather than redefined: every consumer already imports these from
+// here, and two files owning one vocabulary is the divergence this module was
+// written to stop.
+export { LEDGER_BUILTIN_KEYS, SCOPE_CONFIDENCE, VALUE_KINDS, addDays, chronological, dateKey, dayOf, daysBetween } from "./ledger-shared.mjs";
+export {
+ EVENTS,
+ MEASURE_PREDICATES,
+ MEASURE_THRESHOLDS,
+ PROMISE_FORMS,
+ PROMISE_OUTCOMES,
+ allRegimeGaps,
+ freshestReading,
+ goalAbsolute,
+ measureDisplay,
+ measureGaps,
+ measureQualifier,
+ measureSchema,
+ measureScoreboard,
+ measureScoreboardSplit,
+ measureTotals,
+ measureVocab,
+ offCloses,
+ plotDate,
+ regimeGaps,
+} from "./measure-totals.mjs";
+
+export {
+ DEFAULT_FIELD_MAXLENGTH,
+ FIELD_KINDS,
+ FIELD_RENDERS,
+ REGIME_KINDS,
+ fieldApplies,
+ isPledgeKind,
+ validateFields,
+} from "./measure-totals.mjs";
+
export const SCOPES = ["media", "coffee", "publica", "all"];
/** The three that sum. `all` is a claim ABOUT the sum, never a term in it. */
export const COMPANY_SCOPES = ["media", "coffee", "publica"];
export const POPULATIONS = ["employees", "full-time", "salaried", "contractor", "1099", "people"];
-export const VALUE_KINDS = ["uttered", "derived", "synthetic"];
-export const SCOPE_CONFIDENCE = ["clear", "read", "unresolved"];
+
+// ---------------------------------------------------------------------------
+// Which arithmetic a manifest is asking for
+// ---------------------------------------------------------------------------
+// `ledgerSchema` ABSENT means headcount, which is what every manifest written
+// before this said by saying nothing. That is the whole compatibility contract:
+// no key, no change, byte-for-byte.
+
+/** "headcount" | "measure". A bare schema object is accepted too. */
+export function ledgerKind(manifest) {
+ return ledgerSchemaOf(manifest) ? "measure" : "headcount";
+}
+
+/**
+ * The measure schema this manifest carries, or null for headcount.
+ *
+ * Accepts a manifest, a `render`-less `{ ledgerSchema }` bag, or the schema
+ * itself — three call sites want three of those and none of them should have to
+ * know which shape the others hold.
+ */
+export function ledgerSchemaOf(manifest) {
+ if (!manifest || typeof manifest !== "object") return null;
+ const s = manifest.ledgerSchema ?? (manifest.kind ? manifest : null);
+ if (!s || typeof s !== "object") return null;
+ return s.kind === "measure" ? measureSchema(s) : null;
+}
+
+/**
+ * The vocabulary an editor may offer for THIS manifest's claims.
+ *
+ * One function, because the claim bench's radio buttons, the API's validation
+ * and the gate all have to agree about what a legal answer is — and a page
+ * offering a term the arithmetic has never heard of is exactly the silent
+ * divergence the adjudication was introduced to end.
+ */
+export function claimVocab(manifest) {
+ const schema = ledgerSchemaOf(manifest);
+ if (schema) return measureVocab(schema);
+ return {
+ kind: "headcount",
+ scopes: SCOPES,
+ populations: POPULATIONS,
+ valueKinds: VALUE_KINDS,
+ scopeConfidence: SCOPE_CONFIDENCE,
+ events: null,
+ regimes: null,
+ tracks: null,
+ regimeList: null,
+ /** A headcount manifest declares no fields, and the empty list says so. */
+ fields: [],
+ unit: "",
+ schema: null,
+ };
+}
+
+/**
+ * The fields THIS manifest declares beyond the built-ins, for both kinds.
+ *
+ * One reader, because the bench's controls, the API's validation and
+ * `umtool check` all have to agree about what a legal key is — the same
+ * argument `claimVocab` is here for, one level down. Headcount declares none,
+ * and so does a measure manifest that has never needed one.
+ */
+export function ledgerFields(manifest) {
+ return ledgerSchemaOf(manifest)?.fields ?? [];
+}
/** The six fields an entry must carry before it may feed a total. */
export const ADJUDICATION_FIELDS = [
@@ -45,15 +160,15 @@ export const ADJUDICATION_FIELDS = [
"flags",
];
-const isStr = (v) => typeof v === "string" && v.trim().length > 0;
-
/**
* Which of the six an entry is missing or has wrong. Empty array == adjudicated.
*
* Returned rather than thrown because this is what the inbox renders: one
* `claim-unadjudicated` row per entry, naming the fields still outstanding.
*/
-export function adjudicationGaps(entry) {
+export function adjudicationGaps(entry, manifest = null) {
+ const schema = ledgerSchemaOf(manifest);
+ if (schema) return measureGaps(entry, schema);
const gaps = [];
if (!SCOPES.includes(entry?.scope)) gaps.push("scope");
// The phrase that settles it. An adjudication with no basis is an opinion,
@@ -66,11 +181,12 @@ export function adjudicationGaps(entry) {
return gaps;
}
-export const isAdjudicated = (entry) => adjudicationGaps(entry).length === 0;
+export const isAdjudicated = (entry, manifest = null) =>
+ adjudicationGaps(entry, manifest).length === 0;
-/** Entries that carry a number nobody has ruled on yet. */
-export const unadjudicatedOf = (ledger) =>
- (ledger ?? []).filter((e) => !isAdjudicated(e));
+/** Entries that carry a claim nobody has ruled on yet. */
+export const unadjudicatedOf = (ledger, manifest = null) =>
+ (ledger ?? []).filter((e) => !isAdjudicated(e, manifest));
export class UnadjudicatedLedger extends Error {
constructor(entries) {
@@ -92,19 +208,8 @@ export class UnadjudicatedLedger extends Error {
// touching a total. Sorting pads them to the first of the month, which puts them
// before any dated claim in the same month rather than guessing a day.
// ---------------------------------------------------------------------------
-export function dateKey(d) {
- const s = String(d ?? "");
- const m = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(s);
- if (!m) return "9999-99-99";
- return `${m[1]}-${m[2] ?? "01"}-${m[3] ?? "01"}`;
-}
-
-/** Chronological, ties broken by ledger id so the order is total and stable. */
-export const chronological = (ledger) =>
- [...(ledger ?? [])].sort((a, b) => {
- const d = dateKey(a.date).localeCompare(dateKey(b.date));
- return d !== 0 ? d : String(a.id).localeCompare(String(b.id));
- });
+// `dateKey` and `chronological` live in ledger-shared.mjs and are re-exported
+// above: the measure walk pads month-only dates by exactly the same rule.
// ---------------------------------------------------------------------------
// The five predicates.
@@ -278,18 +383,6 @@ function notHisNumber(step) {
const fmt = (n) => (Number.isInteger(n) ? String(n) : String(n));
-function gapWords(from, to) {
- const a = new Date(`${dateKey(from)}T00:00:00Z`).getTime();
- const b = new Date(`${dateKey(to)}T00:00:00Z`).getTime();
- const days = Math.round((b - a) / 86400000);
- if (!Number.isFinite(days)) return "earlier";
- if (days <= 0) return "the same day";
- if (days === 1) return "a day earlier";
- if (days < 31) return `${days} days earlier`;
- const months = Math.round(days / 30.44);
- if (months < 24) return `${months} month${months === 1 ? "" : "s"} earlier`;
- return `${Math.round(days / 365.25)} years earlier`;
-}
// ---------------------------------------------------------------------------
// The walk.
@@ -300,11 +393,21 @@ function gapWords(from, to) {
* predicate — one pass, in date order.
*
* @param {Array<object>} ledger
- * @param {{ strict?: boolean }} [opts] strict:false computes over whatever is
- * adjudicated so the inbox can show its own coherence rows while the rest of
- * the ledger is still being worked. Any renderer must use strict:true.
+ * @param {{ strict?: boolean, schema?: object|null, manifest?: object|null }} [opts]
+ * strict:false computes over whatever is adjudicated so the inbox can show
+ * its own coherence rows while the rest of the ledger is still being worked;
+ * any renderer must use strict:true. `schema` or `manifest` is what selects
+ * the measure arithmetic — neither, and this is the headcount walk it always
+ * was.
+ * @returns {any}
*/
-export function ledgerTotals(ledger, { strict = true } = {}) {
+export function ledgerTotals(ledger, { strict = true, schema = null, manifest = null } = {}) {
+ // The dispatch, and the only place a kind is branched on. A manifest with no
+ // `ledgerSchema` falls straight through to the walk below, which is why every
+ // headcount report renders byte-for-byte as it did.
+ const measure = ledgerSchemaOf(schema ?? manifest);
+ if (measure) return measureTotals(ledger, measure, { strict });
+
const all = chronological(ledger);
const pending = all.filter((e) => !isAdjudicated(e));
if (strict && pending.length) throw new UnadjudicatedLedger(pending);
diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs
@@ -0,0 +1,611 @@
+// THE MEASURE SLICE (weight video rev 9): one object every measure module
+// draws from -- the dial, the odometer, the trail, the goals, the peak, the
+// promise clock, the diet badge. Written into a deck cut's schedule.json as
+// `doc.measure` by the build when the manifest carries a measure ledger
+// (`ledgerSchema.kind: "measure"`) and `render.chrome.deck.measure` is set;
+// `scheduleSlices(doc).measure` hands it to each module's page whole.
+//
+// Pure: no I/O. The build reads each clip's words (measure-words.mjs) and the
+// source second each segment starts at, and passes them in.
+//
+// events every ledger row in scope the CUT SHOWS -- pinned to an entry in
+// the cut, by the row's `entryId` or the entry's ledger pin
+// (`claim: "<row id>"`) -- in cut order, each at the cut second
+// it lands: the spoken number's word time when the clip's words
+// have it, else the entry's quoteStart, else the segment's start.
+// hidden the rows in scope no entry of the cut shows (t: null).
+// state one entry per event, the state AFTER it, sorted by t; state[0]
+// (t: 0) is the state before any event. Built from the EVENTS
+// only: a hidden row never moves a number on screen.
+// totals over events + hidden: the whole record in scope.
+//
+// The odometer rule (ruled 5 Nov 2026, "go by his words"): see lossRuns.
+import { chronological, dateKey, daysBetween } from "./ledger-shared.mjs";
+import { PROMISE_FORMS, measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs";
+import { goalCell, nextRegime, offOf } from "./panel-model.mjs";
+import { offsetIn } from "./gaps.mjs";
+
+export const MEASURE_SLICE_VERSION = 1;
+
+export { PROMISE_FORMS };
+
+/** `render.chrome.deck.measure`'s keys. */
+export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf"]);
+
+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) && !Number.isNaN(Date.parse(`${v}T00:00:00Z`));
+const r1 = (v) => Math.round(v * 10) / 10;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+
+/**
+ * `render.chrome.deck.measure`, checked: `{ scopes?, scale?, asOf? }` --
+ * `scopes` a list of track keys (unique, at least one), `scale` `{ min, max }`
+ * (numbers, min < max), `asOf` a date (YYYY-MM-DD). Whether the scopes are
+ * the ledger's tracks is measureSettingsProblems' (it has the schema).
+ *
+ * @returns {string[]}
+ */
+export function validateMeasureSettings(v, where = "render.chrome.deck.measure") {
+ if (v === undefined) return [];
+ if (!isObj(v)) return [`${where} must be { scopes, scale, asOf }`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!MEASURE_SETTINGS_KEYS.includes(k)) errors.push(`${where}.${k} is not a measure setting (${MEASURE_SETTINGS_KEYS.join(", ")})`);
+ if (v.scopes !== undefined) {
+ if (!Array.isArray(v.scopes) || !v.scopes.length || v.scopes.some((s) => typeof s !== "string" || !s.trim())) {
+ errors.push(`${where}.scopes must be a list of the ledger's track keys (at least one)`);
+ } else if (new Set(v.scopes).size !== v.scopes.length) errors.push(`${where}.scopes names a track twice`);
+ }
+ if (v.scale !== undefined) {
+ const s = v.scale;
+ if (!isObj(s) || !Number.isFinite(s.min) || !Number.isFinite(s.max)) errors.push(`${where}.scale must be { min, max } in the ledger's unit`);
+ else if (s.min >= s.max) errors.push(`${where}.scale.min must be below scale.max`);
+ else for (const k of Object.keys(s)) if (k !== "min" && k !== "max") errors.push(`${where}.scale.${k} is not a scale setting (min, max)`);
+ }
+ if (v.asOf !== undefined && !isIso(v.asOf)) errors.push(`${where}.asOf must be a date (YYYY-MM-DD)`);
+ return errors;
+}
+
+/** Does this manifest carry a measure ledger? */
+export const isMeasureManifest = (manifest) => isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure";
+
+/** Does this cut write a measure slice: a deck, a measure ledger, and `render.chrome.deck.measure` set? */
+export function measureOn(manifest) {
+ const chrome = manifest?.render?.chrome;
+ return isMeasureManifest(manifest) && isObj(chrome) && chrome.layout === "deck" && isObj(chrome.deck?.measure);
+}
+
+/**
+ * The measure settings against the manifest: the deck's `measure` shape, that
+ * the manifest has a measure ledger for it, and that every scope is one of
+ * its tracks.
+ *
+ * @returns {string[]}
+ */
+export function measureSettingsProblems(manifest) {
+ const v = manifest?.render?.chrome?.deck?.measure;
+ if (v === undefined) return [];
+ const errors = validateMeasureSettings(v);
+ if (errors.length) return errors;
+ if (!isMeasureManifest(manifest)) return ['render.chrome.deck.measure needs a measure ledger (ledgerSchema.kind "measure")'];
+ const tracks = measureSchema(manifest.ledgerSchema).tracks.map((t) => t.key);
+ for (const s of v.scopes ?? []) if (!tracks.includes(s)) errors.push(`render.chrome.deck.measure.scopes: "${s}" is not a track of the ledger (${tracks.join(", ")})`);
+ return errors;
+}
+
+/**
+ * The settings with their defaults: scopes every track, the scale the
+ * schema's yMin..yMax, asOf the render's date.
+ */
+export function resolveMeasure(manifest, { asOf = null } = {}) {
+ const schema = measureSchema(manifest.ledgerSchema);
+ const v = manifest?.render?.chrome?.deck?.measure ?? {};
+ const today = new Date().toISOString().slice(0, 10);
+ return {
+ schema,
+ scopes: Array.isArray(v.scopes) && v.scopes.length ? [...v.scopes] : schema.tracks.map((t) => t.key),
+ scale: isObj(v.scale) ? { min: v.scale.min, max: v.scale.max } : { min: schema.yMin, max: schema.yMax },
+ asOfRender: asOf ?? v.asOf ?? today,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The odometer
+// ---------------------------------------------------------------------------
+
+/**
+ * Is this row a REAL-TIME loss claim -- one the odometer counts? A `delta`
+ * on the (first) value track, below zero, about now: no `asOf`, and not
+ * marked `retro` (a loss he describes in the past -- "I also lost 64 pounds"
+ * -- with no date to put in `asOf`).
+ */
+export function isRealtimeLoss(row, schema) {
+ const s = measureSchema(schema);
+ const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null;
+ return row?.scope === valueTrack && row.population === "delta" && Number(row.value) < 0 &&
+ (row.asOf === undefined || row.asOf === null || row.asOf === "") && row.retro !== true;
+}
+
+/**
+ * The runs of real-time loss claims, by HIS words (ruled 5 Nov 2026):
+ *
+ * - only real-time loss claims count (isRealtimeLoss);
+ * - a run is a sequence of them, and its contribution is the HIGHEST claim
+ * in it -- the figure he gave, whatever app or other figure he cites;
+ * - a row's explicit `run` (a whole number, written by the ledger writer
+ * where his words say which run a claim continues -- "since I started")
+ * places it; otherwise a gap of more than `bandGapDays` since the last
+ * claim starts a new run, and a shorter one continues it;
+ * - the total is the sum of the runs' peaks.
+ *
+ * Walked in the order he said them (date, then id).
+ *
+ * @returns {{ runs: Array<{ run: number, start: string, end: string, peak: number, row: string, rows: string[] }>,
+ * runOf: Map<string, number>, claims: Array<{ id: string, date: string, run: number }>, total: number }}
+ */
+export function lossRuns(rows, schema) {
+ const s = measureSchema(schema);
+ const claims = chronological((rows ?? []).filter((r) => isRealtimeLoss(r, s)));
+ const byRun = new Map();
+ const runOf = new Map();
+ let prev = null;
+ let next = 0;
+ for (const c of claims) {
+ let run;
+ if (Number.isInteger(c.run) && c.run >= 0) run = c.run;
+ else if (prev && Math.round(daysBetween(prev.date, c.date)) <= s.bandGapDays) run = runOf.get(prev.id);
+ else run = next;
+ next = Math.max(next, run + 1);
+ runOf.set(c.id, run);
+ const v = Math.abs(Number(c.value));
+ const r = byRun.get(run);
+ if (!r) byRun.set(run, { run, start: c.date, end: c.date, peak: v, row: c.id, rows: [c.id] });
+ else {
+ r.rows.push(c.id);
+ if (dateKey(c.date) > dateKey(r.end)) r.end = c.date;
+ if (dateKey(c.date) < dateKey(r.start)) r.start = c.date;
+ if (v > r.peak) { r.peak = v; r.row = c.id; }
+ }
+ prev = c;
+ }
+ const runs = [...byRun.values()].sort((a, b) => a.run - b.run);
+ 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)) };
+}
+
+// ---------------------------------------------------------------------------
+// A row as an event
+// ---------------------------------------------------------------------------
+
+/** A row's kind on the instruments, from its form and its track. */
+export function kindOf(row, schema) {
+ const s = measureSchema(schema);
+ const role = s.tracks.find((t) => t.key === row?.scope)?.role ?? null;
+ switch (row?.population) {
+ case "current": return "stated";
+ case "past": return "remembered";
+ case "delta": return Number(row.value) < 0 ? "lost" : "gained";
+ case "goal": return "goal";
+ case "goal_loss": return "goalLoss";
+ case "overweight_by": return "overBy";
+ case "promise": return "promise";
+ case "promise_check": return "promiseCheck";
+ case "promise_claim": return "promiseClaim";
+ case "promise_outcome": return "promiseOutcome";
+ case "status": return role === "regime" ? "diet" : "status";
+ default: return row?.population ?? null;
+ }
+}
+
+/** A hidden row's source: an X post when its link or channel says so, else a clip. */
+const rowSource = (row) => (/(^|\/\/)(x|twitter)\.com\//.test(String(row?.citeUrl ?? "")) || /-x$/i.test(String(row?.channel ?? "")) ? "post" : "clip");
+
+/** An entry's source kind: a clip, a post, or a card (anything else). */
+const entrySource = (entry) => (entry?.type === "clip" ? "clip" : entry?.type === "post" ? "post" : "card");
+
+function eventOf(row, schema, runOf) {
+ const s = measureSchema(schema);
+ const kind = kindOf(row, s);
+ const role = s.tracks.find((t) => t.key === row.scope)?.role ?? null;
+ const n = Number(row.value);
+ return {
+ row: row.id,
+ scope: row.scope,
+ date: row.date ?? null,
+ asOf: row.asOf ?? null,
+ kind,
+ value: role === "regime" || !Number.isFinite(n) || row.value === null || row.value === "" ? null : n,
+ qualifier: measureQualifier(row, s),
+ display: measureDisplay(row, s),
+ label: row.label ?? null,
+ quote: row.quote ?? null,
+ deadline: row.deadline ?? null,
+ due: isIso(row.due) ? row.due : null,
+ regime: role === "regime" ? String(row.value) : null,
+ event: role === "regime" ? row.event ?? null : null,
+ run: kind === "lost" && runOf.has(row.id) ? runOf.get(row.id) : null,
+ speaker: speakerOf(row),
+ outcome: row.population === "promise_outcome" && typeof row.outcome === "string" ? row.outcome : null,
+ };
+}
+
+/**
+ * Who said the row: null for the subject (no `speaker`), else the speaker's
+ * key ("madamsavvy"). A row by another speaker never moves the subject's
+ * numbers -- current, lost, net, goals, diet, the totals -- it only feeds the
+ * promises (a promise_claim).
+ */
+export const speakerOf = (row) => (typeof row?.speaker === "string" && row.speaker.trim() ? row.speaker.trim() : null);
+
+// ---------------------------------------------------------------------------
+// When a row lands: the spoken number in the clip's words
+// ---------------------------------------------------------------------------
+
+const ONES = { zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19 };
+const TENS = { twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 };
+const norm = (w) => String(w ?? "").toLowerCase().replace(/[“”"',!?;:()\[\]]/g, "").replace(/\.$/, "").replace(/^\$/, "");
+
+/**
+ * The numbers said in a run of words: `{ i, value }` for each, `i` the index
+ * of its first word -- digits ("291.5", "60", "58.2lbs") and number words
+ * ("two hundred ninety one point five", "a hundred", "fifty eight point two").
+ *
+ * @param {Array<{ text: string }>} words
+ */
+export function spokenNumbers(words) {
+ const toks = words.map((w) => norm(w.text));
+ const out = [];
+ for (let i = 0; i < toks.length; i += 1) {
+ const t = toks[i];
+ const digits = /^(\d+(?:\.\d+)?)(?:lbs?|pounds?)?$/.exec(t);
+ if (digits) { out.push({ i, value: Number(digits[1]) }); continue; }
+ const starts = t in ONES || t in TENS || (t === "a" && toks[i + 1] === "hundred");
+ if (!starts) continue;
+ let total = 0;
+ let cur = 0;
+ let j = i;
+ let any = false;
+ for (; j < toks.length; j += 1) {
+ const w = toks[j];
+ if (w in ONES) { cur += ONES[w]; any = true; } else if (w in TENS) { cur += TENS[w]; any = true; } else if (w === "a" && toks[j + 1] === "hundred") { cur += 1; } else if (w === "hundred") { cur = (cur || 1) * 100; any = true; } else if (w === "thousand") { total += (cur || 1) * 1000; cur = 0; any = true; } else if (w === "and" && any && (toks[j + 1] in ONES || toks[j + 1] in TENS)) { /* "a hundred and ten" */ } else break;
+ }
+ let value = total + cur;
+ // "point five", "point one five": the digits after the point, one word each.
+ if (toks[j] === "point" && toks[j + 1] in ONES && ONES[toks[j + 1]] < 10) {
+ let frac = "";
+ let k = j + 1;
+ while (k < toks.length && toks[k] in ONES && ONES[toks[k]] < 10) { frac += String(ONES[toks[k]]); k += 1; }
+ value = Number(`${value}.${frac}`);
+ j = k;
+ }
+ if (any) out.push({ i, value });
+ i = j - 1;
+ }
+ return out;
+}
+
+/** The words that name a regime when he says it, beyond its key and label. */
+const REGIME_WORDS = { glp1: ["ozempic", "ozimpic", "wegovy", "mounjaro", "glp", "glp-1", "semaglutide", "jab"], fasting: ["fasting", "fast"], calories: ["calories", "calorie"], carnivore: ["carnivore"], keto: ["keto", "ketogenic"] };
+
+/** The figure the row's quote says, as he would say it: the magnitude, for a loss or a loss goal. */
+function spokenTargets(row, kind) {
+ if (!["stated", "remembered", "lost", "gained", "goal", "goalLoss", "overBy"].includes(kind)) return null;
+ const out = [];
+ const n = Number(row.value);
+ if (Number.isFinite(n)) out.push(Math.abs(n));
+ // A range he gave ("220-240", "330-340 lb"): either end is his figure.
+ const range = /(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)/.exec(String(row.display ?? ""));
+ if (range) out.push(Number(range[1]), Number(range[2]));
+ return out.length ? out : null;
+}
+
+/**
+ * The source second the row's figure is said in `words` (`[{ text, start }]`,
+ * source seconds), searched from `anchor` (a second before it) to the end,
+ * then anywhere: the first word of the spoken number (a figure row), or the
+ * regime's word (a diet row). Null when the words never say it.
+ */
+export function spokenAt(row, kind, words, anchor = -Infinity, schema = null) {
+ if (!Array.isArray(words) || !words.length) return null;
+ const pick = (hits) => hits.find((h) => words[h].start >= anchor - 1) ?? hits[0] ?? null;
+ const targets = spokenTargets(row, kind);
+ if (targets !== null) {
+ const nums = spokenNumbers(words);
+ const exact = nums.filter((n) => targets.some((v) => Math.abs(n.value - v) < 0.05)).map((n) => n.i);
+ const i = pick(exact);
+ return i === null ? null : words[i].start;
+ }
+ if (kind === "diet") {
+ const key = String(row.value ?? "");
+ const label = schema ? measureSchema(schema).regimes.find((r) => r.key === key)?.label ?? "" : "";
+ const names = new Set([key, ...(REGIME_WORDS[key] ?? []), ...label.toLowerCase().split(/[^a-z0-9-]+/).filter((w) => w.length > 3)]);
+ const hits = words.map((w, i) => (names.has(norm(w.text)) ? i : -1)).filter((i) => i >= 0);
+ const i = pick(hits);
+ return i === null ? null : words[i].start;
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// The slice
+// ---------------------------------------------------------------------------
+
+/**
+ * The rows of the cut's entries: entry id → the in-scope row ids it shows, in
+ * ledger order -- each row's `entryId`, and each entry's ledger pin
+ * (`claim: "<row id>"`).
+ */
+export function pinnedRows(timeline, rows) {
+ const ids = new Set(rows.map((r) => r.id));
+ const out = new Map();
+ const add = (entryId, rowId) => {
+ if (!ids.has(rowId)) return;
+ const list = out.get(entryId) ?? [];
+ if (!list.includes(rowId)) list.push(rowId);
+ out.set(entryId, list);
+ };
+ const inCut = new Set((timeline ?? []).map((e) => e?.id));
+ for (const r of rows) if (r.entryId && inCut.has(r.entryId)) add(r.entryId, r.id);
+ for (const e of timeline ?? []) if (typeof e?.claim === "string" && e.claim.trim()) add(e.id, e.claim.trim());
+ const order = new Map(rows.map((r, i) => [r.id, i]));
+ for (const list of out.values()) list.sort((a, b) => order.get(a) - order.get(b));
+ return out;
+}
+
+/**
+ * The measure slice of a cut.
+ *
+ * @param {object} manifest the variant's manifest: `ledgerSchema`, `render`,
+ * `timeline` (the cut's entries), and `ledger` -- the WHOLE ledger, or pass
+ * it as `opts.ledger` (a variant's manifest keeps only the pinned rows).
+ * @param {{ segments: Array<{ id: string, start: number, duration: number }> }} schedule
+ * the deck schedule (deck.mjs deckSchedule's document, or one like it).
+ * @param {{ ledger?: object[], asOf?: string|null,
+ * words?: Map<string, { words: Array<{ text: string, start: number }>, from?: string }>,
+ * clock?: Map<string, number>, gaps?: Map<string, Array<{ from: number, to: number }>> }} [opts]
+ * `words` each clip's words in SOURCE seconds; `clock` the source second
+ * each clip's segment starts at (its cut record's, else the play window's);
+ * `gaps` a clip's gaps. A clip with none of them lands on its quoteStart,
+ * against its own start.
+ */
+export function measureSlice(manifest, schedule, opts = {}) {
+ const settings = resolveMeasure(manifest, { asOf: opts.asOf ?? null });
+ const s = settings.schema;
+ const problems = measureSettingsProblems(manifest);
+ if (problems.length) throw new Error(problems.join("; "));
+ const scopes = new Set(settings.scopes);
+ const ledger = (opts.ledger ?? manifest.ledger ?? []).filter((r) => isObj(r) && typeof r.id === "string");
+ const rows = ledger.filter((r) => scopes.has(r.scope));
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ // HIS rows: every number the instruments draw is the subject's own.
+ const own = rows.filter((r) => speakerOf(r) === null);
+ const { runs, runOf, claims: lossClaims, total } = lossRuns(own, s);
+ const runById = new Map(runs.map((r) => [r.run, r]));
+
+ // ---- events: each pinned row at the cut second it lands -------------------
+ const timeline = manifest.timeline ?? [];
+ const entryById = new Map(timeline.map((e) => [e.id, e]));
+ const segs = (schedule?.segments ?? []).filter((g) => entryById.has(g.id));
+ const segIndex = new Map(segs.map((g, i) => [g.id, i]));
+ const pins = pinnedRows(timeline.filter((e) => segIndex.has(e.id)), rows);
+ const shown = new Set();
+ const events = [];
+ for (const seg of segs) {
+ const entry = entryById.get(seg.id);
+ const ids = pins.get(seg.id) ?? [];
+ const from = opts.clock?.get(seg.id) ?? entry.cutStart ?? entry.start ?? null;
+ const gaps = opts.gaps?.get(seg.id) ?? null;
+ const words = opts.words?.get(seg.id) ?? null;
+ const toCut = (src) => {
+ if (!Number.isFinite(src) || !Number.isFinite(from)) return null;
+ const off = offsetIn(src, from, gaps);
+ return r3(Math.min(seg.start + seg.duration, Math.max(seg.start, seg.start + off)));
+ };
+ for (const id of ids) {
+ if (shown.has(id)) continue;
+ const row = byId.get(id);
+ const ev = eventOf(row, s, runOf);
+ // His figure's own second when the words have it; searched from the
+ // row's cite when that is inside the clip (an entry showing two rows
+ // says them at two seconds), else from the quote's start.
+ const inWindow = (v) => Number.isFinite(v) && Number.isFinite(entry.start) && Number.isFinite(entry.end) && v >= entry.start && v <= entry.end;
+ const anchor = ids.length > 1 && inWindow(row.cite) ? row.cite : entry.quoteStart ?? entry.start ?? -Infinity;
+ const said = entry.type === "clip" && words ? spokenAt(row, ev.kind, words.words, anchor, s) : null;
+ let t = said !== null ? toCut(said) : null;
+ let tFrom = t !== null ? (words.from === "cues" ? "cues" : "words") : null;
+ if (t === null && entry.type === "clip") {
+ const q = ids.length > 1 && inWindow(row.cite) ? row.cite : entry.quoteStart;
+ t = toCut(q);
+ if (t !== null) tFrom = "quote";
+ }
+ if (t === null) { t = r3(seg.start); tFrom = "segment"; }
+ events.push({ t, tFrom, segment: seg.id, ...ev, source: entrySource(entry), _seg: segIndex.get(seg.id) });
+ shown.add(id);
+ }
+ }
+ events.sort((a, b) => a.t - b.t || a._seg - b._seg || dateKey(a.date).localeCompare(dateKey(b.date)) || String(a.row).localeCompare(String(b.row)));
+ for (const e of events) delete e._seg;
+ const hidden = chronological(rows.filter((r) => !shown.has(r.id)))
+ .map((r) => ({ t: null, tFrom: null, segment: null, ...eventOf(r, s, runOf), source: rowSource(r) }));
+
+ // ---- the record's own figures, for the state's fixed ends -----------------
+ const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null;
+ const regimeTrack = s.tracks.find((t) => t.role === "regime" && scopes.has(t.key))?.key ?? null;
+ const readings = chronological(own.filter((r) => r.scope === valueTrack && (r.population === "current" || r.population === "past") && Number.isFinite(Number(r.value))));
+ const firstReading = [...readings].sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || String(a.id).localeCompare(String(b.id)))[0] ?? null;
+ const netFrom = firstReading ? { value: Number(firstReading.value), date: plotDate(firstReading), row: firstReading.id } : null;
+
+ /**
+ * 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).
+ */
+ 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;
+ };
+ 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" };
+ }
+ const stated = readings.filter((r) => r.population === "current" && dateKey(r.date) <= dateKey(d));
+ const last = stated[stated.length - 1];
+ return last ? { value: Number(last.value), row: last.id, from: "stated" } : null;
+ };
+ const goalOf = (row) => {
+ const base = row.population === "goal_loss" ? goalBase(row) : null;
+ const cell = goalCell(row, base, s);
+ return { value: cell.value, loss: cell.loss, deadline: cell.deadline, due: isIso(row.due) ? row.due : null, row: row.id, display: cell.display, base };
+ };
+
+ /** A promise_claim as a promise carries it: who, when said, the day she says she paid, his-or-her words. */
+ /** A promise_outcome as a promise carries it. */
+ const outcomeOf = (row) => ({ kind: row.outcome, date: row.date ?? null, row: row.id });
+ const claimOf = (row) => ({ row: row.id, speaker: speakerOf(row), date: row.date ?? null, paidOn: isIso(row.paidOn) ? row.paidOn : null, label: row.label ?? row.display ?? null });
+
+ // ---- the state after each event -------------------------------------------
+ let current = null;
+ const remembered = [];
+ let goal = null;
+ const goals = [];
+ const peaks = new Map();
+ let regime = null;
+ let dietN = 0;
+ const promises = new Map();
+ const snapshot = (t) => {
+ const lostRuns = [...peaks.entries()].sort((a, b) => a[0] - b[0]).map(([run, p]) => ({ run, start: runById.get(run)?.start ?? null, peak: p.peak, row: p.row }));
+ const off = regimeTrack ? offOf(s, regimeTrack)?.key ?? null : null;
+ return {
+ t,
+ current: current ? { ...current } : null,
+ remembered: remembered.map((x) => ({ ...x })),
+ goal: goal ? { ...goal, ...(goal.base ? { base: { ...goal.base } } : {}) } : null,
+ goals: [...goals],
+ lost: { total: r1(lostRuns.reduce((n, r) => n + r.peak, 0)), runs: lostRuns },
+ net: {
+ from: netFrom ? { ...netFrom } : null,
+ to: current ? { value: current.value, date: current.asOf ?? current.date, row: current.row } : null,
+ value: netFrom && current ? r1(current.value - netFrom.value) : null,
+ },
+ diet: regime && regime.key !== off ? { regime: regime.key, display: regime.display, row: regime.row, n: dietN, since: regime.since } : null,
+ promises: [...promises.values()].map((p) => ({ ...p, checks: [...p.checks], claims: p.claims.map((c) => ({ ...c })), outcome: p.outcome ? { ...p.outcome } : null })),
+ };
+ };
+ const state = [snapshot(0)];
+ for (const ev of events) {
+ const row = byId.get(ev.row);
+ // Another speaker's row feeds the promises and nothing else.
+ if (ev.speaker !== null && ev.kind !== "promiseClaim" && ev.kind !== "promiseOutcome") { state.push(snapshot(ev.t)); continue; }
+ if (ev.kind === "stated" && ev.value !== null) current = { value: ev.value, qualifier: ev.qualifier, row: ev.row, date: ev.date, asOf: ev.asOf };
+ else if (ev.kind === "remembered" && ev.value !== null) remembered.push({ value: ev.value, asOf: ev.asOf, row: ev.row, date: ev.date });
+ else if (ev.kind === "goal" || ev.kind === "goalLoss") { goal = goalOf(row); goals.push(ev.row); }
+ else if (ev.kind === "lost" && ev.run !== null) {
+ const v = Math.abs(ev.value);
+ const p = peaks.get(ev.run);
+ if (!p || v > p.peak) peaks.set(ev.run, { peak: v, row: ev.row });
+ } else if (ev.kind === "diet" && row.scope === regimeTrack) {
+ const was = regime;
+ regime = nextRegime(regime, row, s);
+ const off = offOf(s, regimeTrack)?.key ?? null;
+ if (regime && regime.key !== off && (!was || was.key !== regime.key)) dietN += 1;
+ } else if (ev.kind === "promise") {
+ promises.set(ev.row, { row: ev.row, said: ev.date, what: ev.display, due: ev.due, kept: row.kept === true, checks: [], claims: [], outcome: null });
+ } else if (ev.kind === "promiseCheck") {
+ const p = promises.get(row.promise);
+ if (p) { p.checks.push(ev.row); if (row.kept === true) p.kept = true; }
+ } else if (ev.kind === "promiseClaim") {
+ const p = promises.get(row.promise);
+ if (p) p.claims.push(claimOf(row));
+ } else if (ev.kind === "promiseOutcome") {
+ // How it ended: the latest outcome shown; "kept" keeps it.
+ const p = promises.get(row.promise);
+ if (p && ev.outcome) { p.outcome = outcomeOf(row); if (ev.outcome === "kept") p.kept = true; }
+ }
+ state.push(snapshot(ev.t));
+ }
+ // `asOf` is the state's own bookkeeping: the current reading carries the
+ // date the contract names, and NET its plot date.
+ for (const st of state) if (st.current) delete st.current.asOf;
+
+ // ---- totals over the whole record in scope --------------------------------
+ const all = chronological(own);
+ const lastStated = [...readings].filter((r) => r.population === "current").pop() ?? null;
+ const goalRows = all.filter((r) => r.population === "goal" || r.population === "goal_loss");
+ const repeats = {};
+ for (const r of goalRows) { const d = measureDisplay(r, s); repeats[d] = (repeats[d] ?? 0) + 1; }
+ const goalRepeats = Object.fromEntries(Object.entries(repeats).filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));
+ // THE PEAK DRIFT: the weight he remembers starting from, retold. A
+ // remembered weight above every weight he ever stated at the time, about a
+ // day inside the stated record -- so the 2008 wedding is not a start, and
+ // neither is a floor or a ladder rung below what he was saying then.
+ const stated = readings.filter((r) => r.population === "current");
+ const maxStated = stated.length ? Math.max(...stated.map((r) => Number(r.value))) : Infinity;
+ const firstStated = stated.length ? stated.map((r) => dateKey(r.date)).sort()[0] : null;
+ const peakDrift = [...new Set(readings.filter((r) => r.population === "past" && r.asOf && firstStated && dateKey(r.asOf) >= firstStated && Number(r.value) > maxStated).map((r) => Number(r.value)))].sort((a, b) => a - b);
+ // UNDER 300: a weight he stated below it, or "under 300" itself -- never a
+ // bound the other way ("over 240" is not a weight under 300).
+ const under = stated.filter((r) => {
+ const q = measureQualifier(r, s);
+ return q !== ">" && (Number(r.value) < 300 || (Number(r.value) === 300 && q === "<"));
+ });
+ const dates = all.map((r) => plotDate(r)).filter(Boolean).map(dateKey).sort();
+ const promiseRows = all.filter((r) => r.population === "promise");
+ const checksOf = (id) => all.filter((r) => r.population === "promise_check" && r.promise === id);
+ const outcomeRowOf = (id) => chronological(rows).filter((r) => r.population === "promise_outcome" && r.promise === id && typeof r.outcome === "string").pop() ?? null;
+ const claimsOf = (id) => chronological(rows).filter((r) => r.population === "promise_claim" && r.promise === id).map(claimOf);
+ let diets = 0;
+ try {
+ diets = measureTotals(own, s, { strict: false }).switches;
+ } catch {
+ diets = 0;
+ }
+ const totals = {
+ lost: total,
+ lostRuns: runs.map(({ run, start, end, peak, row, rows: ids }) => ({ run, start, end, peak, row, rows: ids })),
+ net: {
+ from: netFrom?.value ?? null,
+ to: lastStated ? Number(lastStated.value) : null,
+ value: netFrom && lastStated ? r1(Number(lastStated.value) - netFrom.value) : null,
+ fromRow: netFrom?.row ?? null,
+ toRow: lastStated?.id ?? null,
+ },
+ runs: runs.length,
+ goals: goalRows.length,
+ goalRepeats,
+ diets,
+ peakDrift,
+ under300: { said: under.length, rows: under.map((r) => r.id) },
+ promises: promiseRows.map((p) => {
+ const checks = checksOf(p.id);
+ const end = outcomeRowOf(p.id);
+ return {
+ row: p.id, said: p.date, what: measureDisplay(p, s), due: isIso(p.due) ? p.due : null,
+ kept: p.kept === true || checks.some((c) => c.kept === true) || end?.outcome === "kept",
+ checks: checks.map((c) => c.id), claims: claimsOf(p.id), outcome: end ? outcomeOf(end) : null,
+ };
+ }),
+ span: { from: dates[0] ?? null, to: dates[dates.length - 1] ?? null },
+ };
+
+ return {
+ version: MEASURE_SLICE_VERSION,
+ unit: s.unit,
+ scale: settings.scale,
+ asOfRender: settings.asOfRender,
+ scopes: settings.scopes,
+ events,
+ hidden,
+ state,
+ totals,
+ };
+}
diff --git a/umtool/report-to-video/measure-slice.test.mjs b/umtool/report-to-video/measure-slice.test.mjs
@@ -0,0 +1,278 @@
+// Tests for measure-slice.mjs: the odometer rule, a row's landing second, the
+// state after each event, the totals, the settings, and the deck schedule's
+// `measure`. Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ isRealtimeLoss, kindOf, lossRuns, measureOn, measureSettingsProblems, measureSlice, pinnedRows, spokenAt, spokenNumbers,
+ validateMeasureSettings,
+} from "./measure-slice.mjs";
+import { estimateSchedule, validateChrome } from "./deck.mjs";
+import { scheduleSlices } from "./modules/index.mjs";
+import { validateClaims } from "./factcheck.mjs";
+
+const SCHEMA = {
+ kind: "measure",
+ unit: "lb",
+ yMin: 210,
+ yMax: 400,
+ bandGapDays: 60,
+ tracks: [
+ { key: "weight", role: "value", label: "Weight" },
+ { key: "regime", role: "regime", label: "Diet", regimes: ["keto", "carnivore", "glp1", "off"] },
+ { key: "drinking", role: "regime", label: "Drinking", regimes: ["dry", "drinking"] },
+ ],
+ forms: ["current", "past", "delta", "goal", "goal_loss", "overweight_by", "status"],
+ regimes: [
+ { key: "keto", label: "Keto" },
+ { key: "carnivore", label: "Carnivore" },
+ { key: "glp1", label: "GLP-1" },
+ { key: "off", label: "No diet" },
+ { key: "dry", label: "Dry" },
+ { key: "drinking", label: "Drinking" },
+ ],
+ fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], appliesTo: { scope: "weight" }, render: "cell" }],
+};
+
+/** An adjudicated row, the six fields filled with the boring answer. */
+const row = (o) => ({
+ scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o,
+});
+
+const LEDGER = [
+ row({ id: "w01", date: "2024-01-01", population: "past", asOf: "2008-06-30", value: 368, display: "368 lb", entryId: "c1" }),
+ row({ id: "w02", date: "2024-01-05", population: "delta", value: -9, display: "-9", entryId: "c1" }),
+ row({ id: "w03", date: "2024-02-01", population: "delta", value: -19.4, display: "-19.4" }),
+ // A loss in the past with no date to put in asOf: marked retro, not counted.
+ row({ id: "w04", date: "2024-02-02", population: "delta", value: -64, display: "-64", retro: true, entryId: "c2" }),
+ // A retrospective (asOf): not counted either.
+ row({ id: "w05", date: "2024-02-03", population: "delta", value: -45, asOf: "2020-01-01", display: "-45" }),
+ // > 60 days on: a new run…
+ row({ id: "w06", date: "2025-04-01", population: "delta", value: -7.5, display: "-7.5", entryId: "c3" }),
+ row({ id: "w07", date: "2025-05-01", population: "past", asOf: "2025-03-20", value: 349, display: "349 lb", entryId: "c3" }),
+ row({ id: "w08", date: "2025-05-10", population: "current", value: 335, display: "335 lb", entryId: "c4" }),
+ row({ id: "w09", date: "2025-05-20", population: "delta", value: -40, qualifier: "≈", display: "-40", entryId: "c4" }),
+ // …a lower figure later in the same run does not lower its peak.
+ row({ id: "w10", date: "2025-06-05", population: "delta", value: -29.2, display: "-29.2", entryId: "c5" }),
+ row({ id: "w11", date: "2025-06-06", population: "goal_loss", value: -65, display: "lose 65", deadline: "by Christmas", due: "2025-12-25", entryId: "c5" }),
+ // An explicit run: a claim his words put in the 2024 run (it does not open run 2).
+ row({ id: "w12", date: "2025-09-01", population: "delta", value: -30, run: 0, display: "-30" }),
+ row({ id: "r01", date: "2025-04-01", scope: "regime", population: "status", value: "keto", event: "start", display: "keto", entryId: "c3" }),
+ // "Off GLP-1" while on keto: keto stands (the off-scope fix).
+ row({ id: "r02", date: "2025-05-10", scope: "regime", population: "status", value: "glp1", event: "off", display: "off GLP-1", entryId: "c4" }),
+ row({ id: "r03", date: "2025-06-05", scope: "regime", population: "status", value: "carnivore", event: "start", display: "carnivore", entryId: "c5" }),
+ row({ id: "d01", date: "2025-05-10", scope: "drinking", population: "status", value: "dry", event: "start", display: "dry", entryId: "c4" }),
+ row({ id: "p01", date: "2025-06-05", population: "promise", value: null, display: "post a video of the scale", entryId: "c5" }),
+ row({ id: "p02", date: "2025-07-01", population: "promise_check", value: null, display: "pull up a video", promise: "p01" }),
+];
+
+const TIMELINE = [
+ { type: "title", id: "z0", seconds: 4 },
+ { type: "clip", id: "c1", video: "v1", start: 100, end: 120, quoteStart: 104 },
+ { type: "clip", id: "c2", video: "v2", start: 10, end: 20, quoteStart: 12 },
+ { type: "clip", id: "c3", video: "v3", start: 50, end: 70, quoteStart: 51 },
+ { type: "clip", id: "c4", video: "v4", start: 0, end: 30, quoteStart: 2, claim: "w08" },
+ { type: "clip", id: "c5", video: "v5", start: 200, end: 230, quoteStart: 205 },
+];
+
+const SEGMENTS = [
+ { id: "z0", start: 0, duration: 4 },
+ { id: "c1", start: 4, duration: 20 },
+ { id: "c2", start: 24, duration: 10 },
+ { id: "c3", start: 34, duration: 20 },
+ { id: "c4", start: 54, duration: 30 },
+ { id: "c5", start: 84, duration: 30 },
+];
+
+const manifest = (measure = { scopes: ["weight", "regime"], scale: { min: 220, max: 400 } }) => ({
+ ledgerSchema: SCHEMA,
+ ledger: LEDGER,
+ timeline: TIMELINE,
+ render: { fps: 30, transition: 0, chrome: { engine: "hyperframes", layout: "deck", deck: { measure } } },
+});
+
+// c4's words: "I weighed three hundred thirty five … I'm down about forty pounds".
+const words = (list) => list.map(([text, start]) => ({ text, start, end: start + 0.2 }));
+const WORDS = new Map([
+ ["c4", { from: "words", words: words([["I", 3], ["weighed", 3.3], ["three", 4], ["hundred", 4.3], ["thirty", 4.6], ["five", 4.9], ["and", 10], ["I'm", 11], ["down", 11.3], ["about", 11.6], ["forty", 12], ["pounds", 12.4]]) }],
+]);
+const CLOCK = new Map([["c1", 100], ["c2", 10], ["c3", 50], ["c4", 0], ["c5", 200]]);
+
+test("the odometer: the highest real-time claim per run, summed; a gap past bandGapDays starts a run; a row's run wins", () => {
+ const { runs, runOf, total } = lossRuns(LEDGER, SCHEMA);
+ assert.deepEqual(runs.map((r) => [r.run, r.start, r.peak, r.row]), [[0, "2024-01-05", 30, "w12"], [1, "2025-04-01", 40, "w09"]]);
+ assert.equal(total, 70);
+ assert.equal(runOf.has("w04"), false, "a retro loss is not on the odometer");
+ assert.equal(runOf.has("w05"), false, "a retrospective (asOf) is not either");
+ assert.equal(runOf.get("w12"), 0, "his words put w12 in the first run");
+ assert.equal(isRealtimeLoss(row({ population: "delta", value: 5 }), SCHEMA), false, "a gain is no loss");
+ // Without the explicit run, w12 is three months after w10: a run of its own.
+ const plain = lossRuns(LEDGER.map((r) => (r.id === "w12" ? { ...r, run: undefined } : r)), SCHEMA);
+ assert.deepEqual(plain.runs.map((r) => r.peak), [19.4, 40, 30]);
+ assert.equal(plain.total, 89.4);
+});
+
+test("the numbers he says: digits and words, a point, a hundred", () => {
+ const ns = (s) => spokenNumbers(s.split(" ").map((text) => ({ text }))).map((n) => n.value);
+ assert.deepEqual(ns("at two hundred ninety one point five for a total"), [291.5]);
+ assert.deepEqual(ns("I'm down fifty eight point two"), [58.2]);
+ assert.deepEqual(ns("about a hundred and ten to go, 60 lbs and 291.5"), [110, 60, 291.5]);
+ assert.equal(spokenAt({ value: -40 }, "lost", WORDS.get("c4").words), 12);
+ assert.equal(spokenAt({ value: 335 }, "stated", WORDS.get("c4").words), 4);
+ assert.equal(spokenAt({ value: 999 }, "stated", WORDS.get("c4").words), null);
+ assert.equal(spokenAt({ value: "keto" }, "diet", words([["on", 1], ["keto", 2]]), -Infinity, SCHEMA), 2);
+ assert.equal(kindOf({ scope: "regime", population: "status" }, SCHEMA), "diet");
+ assert.equal(kindOf({ population: "promise_check" }, SCHEMA), "promiseCheck");
+});
+
+test("events: the rows the cut shows, in cut order, at the second the figure is said", () => {
+ const sl = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ assert.equal(sl.version, 1);
+ assert.deepEqual(sl.scopes, ["weight", "regime"]);
+ assert.deepEqual(sl.scale, { min: 220, max: 400 });
+ assert.equal(sl.asOfRender, "2025-07-10");
+ const at = Object.fromEntries(sl.events.map((e) => [e.row, [e.t, e.tFrom, e.segment]]));
+ // c4's two rows at their words: 54 + 4 and 54 + 12; its "off GLP-1" at the quote.
+ assert.deepEqual(at.w08, [58, "words", "c4"]);
+ assert.deepEqual(at.w09, [66, "words", "c4"]);
+ assert.deepEqual(at.r02, [56, "quote", "c4"]);
+ // No words: the quote's start, mapped through the clip's clock.
+ assert.deepEqual(at.w02, [8, "quote", "c1"]);
+ assert.deepEqual(at.w04, [26, "quote", "c2"]);
+ for (let i = 1; i < sl.events.length; i += 1) assert.ok(sl.events[i].t >= sl.events[i - 1].t, "in cut order");
+ // Scopes: no drinking row, shown or hidden.
+ assert.ok(![...sl.events, ...sl.hidden].some((e) => e.row === "d01"));
+ // Hidden: in scope, on no entry of the cut.
+ assert.deepEqual(sl.hidden.map((e) => e.row), ["w03", "w05", "p02", "w12"]);
+ assert.ok(sl.hidden.every((e) => e.t === null));
+ const w09 = sl.events.find((e) => e.row === "w09");
+ assert.equal(w09.kind, "lost");
+ assert.equal(w09.run, 1);
+ assert.equal(w09.qualifier, "≈");
+ assert.equal(sl.events.find((e) => e.row === "w04").run, null, "retro: on screen, not on the odometer");
+});
+
+test("state: after each event, from the shown rows only", () => {
+ const sl = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ assert.equal(sl.state.length, sl.events.length + 1);
+ assert.equal(sl.state[0].t, 0);
+ assert.equal(sl.state[0].current, null);
+ assert.deepEqual(sl.state[0].lost, { total: 0, runs: [] });
+ const after = (id) => sl.state[sl.events.findIndex((e) => e.row === id) + 1];
+ assert.deepEqual(after("w08").current, { value: 335, qualifier: null, row: "w08", date: "2025-05-10" });
+ assert.deepEqual(after("w08").net, { from: { value: 368, date: "2008-06-30", row: "w01" }, to: { value: 335, date: "2025-05-10", row: "w08" }, value: -33 });
+ // Keto stands through "off GLP-1".
+ assert.equal(after("r02").diet.regime, "keto");
+ assert.equal(after("r02").diet.n, 1);
+ const last = sl.state[sl.state.length - 1];
+ assert.equal(last.diet.regime, "carnivore");
+ assert.equal(last.diet.n, 2);
+ // The odometer as the cut has shown it: w12 is hidden, so run 0's peak is the 9 shown.
+ assert.deepEqual(last.lost, { total: 49, runs: [{ run: 0, start: "2024-01-05", peak: 9, row: "w02" }, { run: 1, start: "2025-04-01", peak: 40, row: "w09" }] });
+ for (let i = 1; i < sl.state.length; i += 1) assert.ok(sl.state[i].lost.total >= sl.state[i - 1].lost.total, "the odometer only goes up");
+ // "Lose 65" against the start of its run: the 349 he remembers (asOf 20 March, 12 days before).
+ assert.deepEqual(last.goal, { value: 284, loss: 65, deadline: "by Christmas", due: "2025-12-25", row: "w11", display: "284 lb", base: { value: 349, row: "w07", from: "runStart" } });
+ assert.deepEqual(last.goals, ["w11"]);
+ assert.deepEqual(last.remembered.map((r) => r.row), ["w01", "w07"]);
+ assert.deepEqual(last.promises, [{ row: "p01", said: "2025-06-05", what: "post a video of the scale", due: null, kept: false, checks: [], claims: [], outcome: null }]);
+});
+
+test("totals: the whole record in scope", () => {
+ const sl = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const t = sl.totals;
+ assert.equal(t.lost, 70);
+ assert.equal(t.runs, 2);
+ assert.deepEqual(t.net, { from: 368, to: 335, value: -33, fromRow: "w01", toRow: "w08" });
+ assert.equal(t.goals, 1);
+ assert.deepEqual(t.promises, [{ row: "p01", said: "2025-06-05", what: "post a video of the scale", due: null, kept: false, checks: ["p02"], claims: [], outcome: null }]);
+ assert.deepEqual(t.span, { from: "2008-06-30", to: "2025-09-01" });
+ assert.deepEqual(t.under300, { said: 0, rows: [] });
+ assert.equal(t.diets, 1, "keto -> carnivore is one change; off GLP-1 none");
+});
+
+test("the settings: their shape, their scopes against the ledger, and when a cut writes a slice", () => {
+ assert.deepEqual(validateMeasureSettings(undefined), []);
+ assert.deepEqual(validateMeasureSettings({ scopes: ["weight"], scale: { min: 220, max: 400 }, asOf: "2026-11-05" }), []);
+ assert.deepEqual(validateMeasureSettings({ scopes: [], scale: { min: 4, max: 2 }, asOf: "Nov 5", x: 1 }), [
+ "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf)",
+ "render.chrome.deck.measure.scopes must be a list of the ledger's track keys (at least one)",
+ "render.chrome.deck.measure.scale.min must be below scale.max",
+ "render.chrome.deck.measure.asOf must be a date (YYYY-MM-DD)",
+ ]);
+ assert.deepEqual(measureSettingsProblems(manifest({ scopes: ["weight", "gym"] })), [
+ 'render.chrome.deck.measure.scopes: "gym" is not a track of the ledger (weight, regime, drinking)',
+ ]);
+ assert.deepEqual(measureSettingsProblems({ ...manifest(), ledgerSchema: undefined }), ['render.chrome.deck.measure needs a measure ledger (ledgerSchema.kind "measure")']);
+ assert.equal(measureOn(manifest()), true);
+ assert.equal(measureOn({ ...manifest(), render: { chrome: { layout: "deck", deck: {} } } }), false);
+ assert.throws(() => measureSlice(manifest({ scopes: ["gym"] }), { segments: SEGMENTS }), /not a track/);
+ // The deck refuses a bad one where it refuses everything else.
+ const m = manifest({ scale: { min: 1 } });
+ assert.match(validateChrome(m.render.chrome, m.render).join("\n"), /deck\.measure\.scale must be \{ min, max \}/);
+ // No scopes: every track.
+ assert.deepEqual(measureSlice(manifest({}), { segments: SEGMENTS }, { asOf: "2025-07-10" }).scopes, ["weight", "regime", "drinking"]);
+});
+
+test("the deck schedule carries `measure` only for a measure cut, and the slices hand it on", () => {
+ const m = manifest();
+ const doc = estimateSchedule(m);
+ assert.ok(doc.measure, "a measure cut's schedule carries the slice");
+ assert.equal(doc.measure.events.length, LEDGER.filter((r) => r.entryId && r.scope !== "drinking").length);
+ assert.equal(scheduleSlices(doc).measure, doc.measure);
+ const plain = estimateSchedule({ ...m, render: { ...m.render, chrome: { engine: "hyperframes", layout: "deck", deck: {} } } });
+ assert.equal("measure" in plain, false, "no setting: the schedule it always was");
+ assert.equal("measure" in scheduleSlices(plain), false);
+ // The ledger pin and the entryId name the same rows.
+ assert.deepEqual(pinnedRows(TIMELINE, LEDGER).get("c4"), ["w08", "w09", "r02", "d01"]);
+ assert.deepEqual(validateClaims(m), []);
+});
+
+test("another speaker's rows feed the promises and move none of his numbers", () => {
+ const plain = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const savvy = [
+ row({ id: "s01", date: "2025-06-06", population: "promise_claim", value: null, speaker: "madamsavvy", promise: "p01", paidOn: "2025-06-06",
+ display: "bought the 5 bags", label: "\"I bought the 5 bags\"", citeUrl: "https://x.com/MadamSavvy/status/1", entryId: "c5" }),
+ // Her figures are hers: no reading, loss or goal of his.
+ row({ id: "s02", date: "2025-06-07", population: "current", value: 250, speaker: "madamsavvy", display: "250 lb", entryId: "c5" }),
+ row({ id: "s03", date: "2025-06-07", population: "delta", value: -99, speaker: "madamsavvy", display: "-99", entryId: "c5" }),
+ row({ id: "s04", date: "2025-06-08", population: "goal_loss", value: -10, speaker: "madamsavvy", display: "lose 10" }),
+ ];
+ const m = { ...manifest(), ledger: [...LEDGER, ...savvy] };
+ const sl = measureSlice(m, { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const strip = (t) => JSON.stringify({ ...t, promises: t.promises.map(({ claims: _c, ...p }) => p) });
+ assert.equal(strip(sl.totals), strip(plain.totals), "the totals are his alone");
+ const claim = sl.events.find((e) => e.row === "s01");
+ assert.equal(claim.kind, "promiseClaim");
+ assert.equal(claim.speaker, "madamsavvy");
+ assert.equal(sl.events.find((e) => e.row === "s03").run, null, "her loss is no run of his");
+ const last = sl.state[sl.state.length - 1];
+ const was = plain.state[plain.state.length - 1];
+ for (const k of ["current", "lost", "net", "goal", "goals", "diet", "remembered"]) assert.deepEqual(last[k], was[k], k);
+ assert.deepEqual(last.promises[0].claims, [{ row: "s01", speaker: "madamsavvy", date: "2025-06-06", paidOn: "2025-06-06", label: "\"I bought the 5 bags\"" }]);
+ assert.deepEqual(sl.totals.promises[0].claims.map((c) => c.row), ["s01"]);
+ assert.deepEqual(plain.state.at(-1).promises[0].claims, [], "a promise with no claim has an empty list");
+});
+
+test("a promise's outcome: how it ended, and \"kept\" keeps it -- the totals untouched", () => {
+ const plain = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const strip = (t) => JSON.stringify({ ...t, promises: t.promises.map(({ outcome: _o, kept: _k, ...p }) => p) });
+ const withOutcome = (outcome, speaker) => measureSlice({
+ ...manifest(),
+ ledger: [...LEDGER, row({ id: "o01", date: "2025-06-20", population: "promise_outcome", value: null, promise: "p01", outcome, ...(speaker ? { speaker } : {}),
+ display: outcome, label: `${outcome} by 20 June`, entryId: "c5" })],
+ }, { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" });
+ const refunded = withOutcome("refunded", "madamsavvy");
+ assert.equal(strip(refunded.totals), strip(plain.totals), "an outcome moves no total");
+ const ev = refunded.events.find((e) => e.row === "o01");
+ assert.deepEqual([ev.kind, ev.outcome, ev.speaker], ["promiseOutcome", "refunded", "madamsavvy"]);
+ const p = refunded.state.at(-1).promises[0];
+ assert.deepEqual(p.outcome, { kind: "refunded", date: "2025-06-20", row: "o01" });
+ assert.equal(p.kept, false, "refunded is not kept");
+ assert.deepEqual(refunded.totals.promises[0].outcome, { kind: "refunded", date: "2025-06-20", row: "o01" });
+ for (const k of ["current", "lost", "net", "goal", "diet"]) assert.deepEqual(refunded.state.at(-1)[k], plain.state.at(-1)[k], k);
+ const kept = withOutcome("kept");
+ assert.equal(kept.state.at(-1).promises[0].kept, true);
+ assert.equal(kept.totals.promises[0].kept, true);
+ assert.equal(plain.state.at(-1).promises[0].outcome, null);
+});
diff --git a/umtool/report-to-video/measure-totals.mjs b/umtool/report-to-video/measure-totals.mjs
@@ -0,0 +1,1626 @@
+// The MEASURE ledger kind: one quantity over time, plus what regime he says he
+// is on while it moves.
+//
+// ---------------------------------------------------------------------------
+// Why a second kind rather than a second manifest field
+// ---------------------------------------------------------------------------
+// The headcount ledger (ledger-totals.mjs) answers "how many people work for
+// him", and every part of it -- four named companies, a sum-of-payrolls, a
+// population baseline -- is about a count that is the sum of its parts. A weight
+// is not. There is one number, it is nobody's sum, and the interesting thing
+// beside it is not another number but a WORD: what he says he is doing about it.
+//
+// So `measure` keeps the ledger's SHAPE (one dated claim per row, the same six
+// adjudication fields, the same "our number vs his number" discipline) and
+// replaces the arithmetic:
+//
+// scope which TRACK the claim feeds -- a value track or a regime track
+// population the claim's FORM -- current / past / delta / goal / …
+// value a number in the schema's unit, or a regime key
+// event start | on | stop | off, for regime claims only
+// asOf the date the claim is ABOUT, when that is not the date he said it
+//
+// `asOf` is the one genuinely new field and it earns its place: a retrospective
+// ("I was almost 400 when I took that fight") is evidence about 2023 uttered in
+// 2025, and plotting it in 2025 would draw a weight gain that never happened.
+// Everything plots at `asOf ?? date`, and the two dates being different is
+// exactly what `retro_mismatch` reads.
+//
+// ---------------------------------------------------------------------------
+// Why the band can say "unknown"
+// ---------------------------------------------------------------------------
+// A regime segment is an assertion that he was on something for a stretch of
+// time, and the only evidence for it is that he said so at one end. Carrying
+// that forward indefinitely would put a claim on screen nobody made: six months
+// of silence after "I'm doing keto" is not six months of keto. So a segment is
+// asserted for `bandGapDays` (60) past the last claim that supports it, and the
+// rest of the silence is drawn HATCHED and labelled unknown.
+//
+// That is the same rule the headcount chart follows by refusing to draw a
+// midpoint: where the corpus is silent, the picture says silent.
+
+import {
+ LEDGER_BUILTIN_KEYS,
+ SCOPE_CONFIDENCE,
+ VALUE_KINDS,
+ addDays,
+ chronological,
+ dateKey,
+ daysBetween,
+ dayOf,
+ gapWords,
+ isStr,
+} from "./ledger-shared.mjs";
+
+/** What a regime claim can be doing. `on` is "still on it", not a change. */
+export const EVENTS = ["start", "on", "stop", "off"];
+
+/** The events that OPEN or sustain a segment, against those that close one. */
+const OPENING = new Set(["start", "on"]);
+const CLOSING = new Set(["stop", "off"]);
+
+/**
+ * Whether a `stop`/`off` claim ends what is open on its track.
+ *
+ * AN OFF CLOSES THE REGIME IT NAMES, and nothing else. "Off GLP-1" said while
+ * he is three weeks into keto is a statement about GLP-1; read as "off" the
+ * track, it put "No diet" in the DIET cell — a word no row says — and counted a
+ * change of diet that never happened. So the claim closes the track only when
+ * the open regime IS the one it names, or nothing (or already the off regime)
+ * is open, where the old reading and this one agree.
+ *
+ * @param {string|null} openKey the regime open on the track, or null
+ * @param {string} named the regime the claim says he is off
+ * @param {string|null} offKey the track's own off regime, if it has one
+ */
+export function offCloses(openKey, named, offKey = null) {
+ if (openKey == null) return true;
+ if (offKey != null && openKey === offKey) return true;
+ return openKey === named;
+}
+
+/** The forms a value claim can take, when the schema does not name its own. */
+export const DEFAULT_FORMS = ["current", "past", "delta", "goal", "overweight_by", "status"];
+
+/**
+ * The forms a PROMISE is written in (weight video rev 9): `promise`, what he
+ * says he will do ("post a video of the scale"; `due` when he gave a day);
+ * `promise_check`, his own later word about it; and `promise_claim`, ANOTHER
+ * party's statement about it ("I bought the 5 bags"; `speaker`, `paidOn`);
+ * and `promise_outcome`, how it ended (`outcome`: kept, refunded or
+ * withdrawn -- a promise can end without being kept). `promise` names the
+ * promise row on the last three; `kept: true` on a promise or a check, or an
+ * outcome "kept", says it was kept. Built into every measure schema.
+ */
+export const PROMISE_FORMS = ["promise", "promise_check", "promise_claim", "promise_outcome"];
+
+/** How a promise ended (a promise_outcome's `outcome`). */
+export const PROMISE_OUTCOMES = ["kept", "refunded", "withdrawn"];
+
+/** The two forms that are a reading of the quantity itself, so they plot. */
+export const PLOTTING_FORMS = new Set(["current", "past"]);
+
+/**
+ * What a regime can BE, beyond a plain state of affairs.
+ *
+ * `pledge` is a stop — the automatic rule reads it, and any drink inside the
+ * window breaks it. `bounded` is a limit rather than a stop, and no automatic
+ * rule can read it. `lapse` is the act that breaks either.
+ */
+export const REGIME_KINDS = ["pledge", "bounded", "lapse"];
+
+/**
+ * Is this a promise at all? Both shapes of one are, and everything that counts
+ * promises — the scoreboard's PLEDGES, the schema's lapse cross-check, the
+ * walk's open-pledge ledger — counts both.
+ *
+ * The two differ in HOW they break, and nowhere else. A rule that said
+ * otherwise would put "27 pledges" and "16 of them broken" on the same board
+ * out of two different definitions of a pledge.
+ */
+export const isPledgeKind = (kind) => kind === "pledge" || kind === "bounded";
+
+/** How long a regime claim is allowed to speak for, in days, before silence. */
+export const DEFAULT_BAND_GAP_DAYS = 60;
+
+/**
+ * How soon after a pledge a lapse still counts as breaking it.
+ *
+ * Not a judgement about willpower. It is the window inside which the two claims
+ * are ABOUT EACH OTHER: "I've stopped drinking" and, two days later, "had a few
+ * at the game" are one event with two halves. Six months later they are two
+ * unrelated facts, and a rule that joined them would be inventing the story
+ * rather than reading it.
+ */
+export const DEFAULT_PLEDGE_DAYS = 30;
+
+/**
+ * Silences whose UNDRAWN remainder is shorter than this get no hatched segment.
+ *
+ * The band's right edge is the last thing the ledger says about ANYTHING, so a
+ * regime that lapses a few days before a weight claim leaves a sliver of hatch
+ * nobody can read and nobody meant. Dropping it leaves a hole, which looks the
+ * same and claims nothing.
+ *
+ * It is DRAWING SUPPRESSION AND NOTHING ELSE. The `regime-gap` decision is
+ * recorded from the lapse itself, before this runs — it used to be read back
+ * off the band, which meant a 63-day silence produced no segment and therefore
+ * no decision, and the inbox went quiet about exactly the case the rule exists
+ * to catch.
+ */
+const MIN_UNKNOWN_DAYS = 7;
+
+/** The six measure predicates. Named, computed, never asserted. */
+export const MEASURE_PREDICATES = [
+ "contradicts_recent",
+ "retro_mismatch",
+ "regime_flip",
+ "same_day_conflict",
+ "not_his_number",
+ "quit_unannounced",
+ "broke_pledge",
+];
+
+/** Thresholds. One definition, because the inbox and the chart both cite them. */
+export const MEASURE_THRESHOLDS = {
+ /** two readings this close in time … */
+ recentDays: 14,
+ /** … differing by more than this are a contradiction, not a fluctuation. */
+ recentDelta: 15,
+ /** a retrospective this far from the contemporaneous record is a mismatch. */
+ retroDelta: 20,
+ /** how far either side of `asOf` to look for the contemporaneous record. */
+ retroWindowDays: 120,
+ /** a regime change this soon after the last one is a flip. */
+ flipDays: 30,
+};
+
+// ---------------------------------------------------------------------------
+// The schema
+// ---------------------------------------------------------------------------
+
+/**
+ * The kinds a declared field may take, and what each one means on a row.
+ *
+ * A closed list, because the whole point of declaring a field is that three
+ * readers -- the arithmetic, the bench and `umtool check` -- agree about what a
+ * legal answer is. An open `kind` would put the agreement back in prose.
+ */
+export const FIELD_KINDS = ["text", "enum", "number", "bool", "rowRef", "seconds"];
+
+/**
+ * Where a declared field SHOWS, when it shows at all.
+ *
+ * `none` is the default and is not a lesser answer: `breaks` decides whether a
+ * pledge was broken and never appears on screen as itself. `cell` prefixes the
+ * row's own cell text; `gloss` is one quiet sub-line under the first row of the
+ * walk that carries it.
+ */
+export const FIELD_RENDERS = ["none", "cell", "gloss"];
+
+/** How long a `text` field may be when the schema does not say. */
+export const DEFAULT_FIELD_MAXLENGTH = 200;
+
+/** The row facets an `appliesTo` may narrow on. */
+const APPLIES_FACETS = ["scope", "value", "role", "population", "event"];
+
+/**
+ * The declared fields, normalised, cross-checked and loud about every way a
+ * schema can be wrong.
+ *
+ * Loud rather than lenient for the same reason the track/regime cross-check
+ * above is: a field the arithmetic silently drops is a column of adjudication
+ * work that goes into the manifest and never comes out of it, and nothing says
+ * so. The four ways: a kind nobody implements, an enum with no options to
+ * choose from, two fields fighting over one key, and a field named after a
+ * built-in -- which would not be a new field at all, it would be a second,
+ * differently-validated door onto `display`.
+ */
+function normaliseFields(raw) {
+ const out = [];
+ const seen = new Set();
+ for (const f of raw ?? []) {
+ const key = String(f?.key ?? "").trim();
+ if (!key) {
+ throw new Error("measure schema: a `fields` entry has no `key`");
+ }
+ if (seen.has(key)) {
+ throw new Error(`measure schema: two \`fields\` entries declare \`${key}\``);
+ }
+ if (LEDGER_BUILTIN_KEYS.has(key)) {
+ throw new Error(
+ `measure schema: \`fields\` declares \`${key}\`, which is a built-in row key ` +
+ "— a declared field cannot be a second door onto one the code already means",
+ );
+ }
+ seen.add(key);
+ if (!FIELD_KINDS.includes(f?.kind)) {
+ throw new Error(
+ `measure schema: field \`${key}\` has kind \`${f?.kind ?? ""}\` — one of ` +
+ FIELD_KINDS.join(", "),
+ );
+ }
+ const render = f.render == null ? "none" : String(f.render);
+ if (!FIELD_RENDERS.includes(render)) {
+ throw new Error(
+ `measure schema: field \`${key}\` renders as \`${render}\` — one of ` +
+ FIELD_RENDERS.join(", "),
+ );
+ }
+ const options = Array.isArray(f.options) ? f.options.map(String).filter((o) => o.length) : null;
+ if (f.kind === "enum" && !options?.length) {
+ throw new Error(`measure schema: enum field \`${key}\` declares no \`options\``);
+ }
+ let appliesTo = null;
+ if (f.appliesTo && typeof f.appliesTo === "object") {
+ appliesTo = {};
+ for (const facet of APPLIES_FACETS) {
+ if (f.appliesTo[facet] != null) appliesTo[facet] = String(f.appliesTo[facet]);
+ }
+ if (!Object.keys(appliesTo).length) appliesTo = null;
+ }
+ out.push({
+ key,
+ label: f.label ?? key,
+ kind: f.kind,
+ help: f.help ?? null,
+ options,
+ maxLength:
+ f.kind === "text"
+ ? Number.isFinite(f.maxLength) ? f.maxLength : DEFAULT_FIELD_MAXLENGTH
+ : null,
+ min: Number.isFinite(f.min) ? f.min : null,
+ max: Number.isFinite(f.max) ? f.max : null,
+ appliesTo,
+ render,
+ });
+ }
+ return out;
+}
+
+
+/**
+ * The schema with every default filled in, so no reader has to know them.
+ *
+ * A track's `role` is EXPLICIT. Guessing it from the key ("regime" looks like a
+ * regime track) would work for exactly one manifest and then silently plot a
+ * regime key on the value axis for the next one.
+ */
+export function measureSchema(schema) {
+ const s = schema ?? {};
+ const tracks = (s.tracks ?? []).map((t) => ({
+ key: String(t.key),
+ label: t.label ?? String(t.key),
+ shortLabel: t.shortLabel ?? null,
+ color: t.color ?? null,
+ role: t.role === "regime" ? "regime" : "value",
+ /**
+ * Which regimes are THIS track's, when the schema says.
+ *
+ * `regimes[]` is one flat list because for one regime track it may as well
+ * be. With two -- a diet and a drink -- it is a list of six words in which
+ * nothing says which three belong to which strip, and the failure is
+ * silent: a `dry` claim on the diet track opens a segment, draws a band and
+ * reads as a diet. Naming them per track is what makes that a loud error
+ * instead, and it is the only cross-check between `tracks` and `regimes`
+ * that exists.
+ */
+ regimes: Array.isArray(t.regimes) ? t.regimes.map(String) : null,
+ /** THIS track's word for "the rule is over", resolved below. */
+ offKey: null,
+ }));
+ const regimes = (s.regimes ?? []).map((r) => ({
+ key: String(r.key),
+ label: r.label ?? String(r.key),
+ color: r.color ?? null,
+ /**
+ * What this regime IS, when the schema says: a promise, a BOUNDED promise,
+ * or the breaking of one. Absent on every regime that has never needed it
+ * -- a diet is none of the three -- and absent is what every shipped
+ * manifest carries, so nothing that does not declare `kind` gains a flag.
+ *
+ * `bounded` is a promise he put a LIMIT on rather than a stop to: "two
+ * nights a week", "about 20% as much". The automatic rule cannot read it —
+ * every drink inside thirty days would break "two nights a week", and it
+ * is precisely the drinks that do NOT that make the pledge a bound. So a
+ * bounded pledge breaks only where a `breaks` reference says it does.
+ */
+ kind: REGIME_KINDS.includes(r.kind) ? r.kind : null,
+ }));
+ // Loud, and by name. A regime a track claims and the schema never declares
+ // draws nothing, flags nothing and says nothing -- the band is simply shorter
+ // than the evidence, which is the one failure mode this file exists to make
+ // impossible.
+ for (const t of tracks) {
+ if (!t.regimes) continue;
+ const missing = t.regimes.filter((k) => !regimes.some((r) => r.key === k));
+ if (missing.length) {
+ throw new Error(
+ `measure schema: track \`${t.key}\` names regime${missing.length === 1 ? "" : "s"} ` +
+ `no \`regimes\` entry declares — ${missing.join(", ")}`,
+ );
+ }
+ // A lapse is only a lapse FROM something. A track that declares one and no
+ // pledge would produce a `broke_pledge` that can never fire, which reads on
+ // the board as "he never broke one" -- an assertion the ledger has not
+ // made. Loud, and by name, for the same reason the check above is.
+ const kindsHere = t.regimes.map((k) => regimes.find((r) => r.key === k)?.kind ?? null);
+ if (kindsHere.includes("lapse") && !kindsHere.some(isPledgeKind)) {
+ throw new Error(
+ `measure schema: track \`${t.key}\` declares a \`lapse\` regime and no \`pledge\` ` +
+ "— a lapse is only meaningful against something it lapses from",
+ );
+ }
+ }
+ // The same check for a schema whose tracks do not enumerate their regimes:
+ // one flat list, so the question is only whether a pledge exists at all.
+ if (
+ regimes.some((r) => r.kind === "lapse") &&
+ !regimes.some((r) => isPledgeKind(r.kind)) &&
+ !tracks.some((t) => t.regimes)
+ ) {
+ throw new Error(
+ "measure schema: a `lapse` regime is declared and no `pledge` is " +
+ "— a lapse is only meaningful against something it lapses from",
+ );
+ }
+ // WHOSE `off` IS IT? A per-track answer, because an off label is a WORD, and
+ // a word written for one strip is a lie on another. `offKey` is one flat key
+ // for the whole schema, and with two regime tracks that put "No diet" in the
+ // DRINKING cell the moment he said he had stopped being dry — the diet
+ // track's word, on the drinking strip, asserting something no row says.
+ //
+ // Four rules, in order, each of which can be answered off the schema alone:
+ //
+ // 1. the track names its own (`offRegime`) — the escape hatch a manifest
+ // uses to state the truth once and for all;
+ // 2. an off-shaped regime (`off`, or `off_<anything>`) that THIS track
+ // declares and no other regime track does — sole ownership, which is
+ // what "the track's own word" means when nothing says it outright;
+ // 3. a shared `off` belongs to the FIRST regime track, the same convention
+ // `switches`, `band` and `final.regime` have always kept: one flat list
+ // is authored around one strip, and that strip is the first one;
+ // 4. otherwise NOTHING. The drawing says so with a dash in our own quiet
+ // colour rather than borrowing a word he did not use — which is the
+ // whole difference between reporting a silence and inventing a status.
+ const fields = normaliseFields(s.fields);
+ const globalOff = regimes.some((r) => r.key === "off") ? "off" : null;
+ const firstRegimeTrack = tracks.find((t) => t.role === "regime") ?? null;
+ tracks.forEach((t, i) => {
+ if (t.role !== "regime") return;
+ const raw = (s.tracks ?? [])[i] ?? {};
+ const declared = (k) => regimes.some((r) => r.key === k);
+ const named = raw.offRegime ? String(raw.offRegime) : null;
+ if (named && declared(named)) { t.offKey = named; return; }
+ const others = tracks.filter((x, j) => j !== i && x.role === "regime");
+ const sole = (t.regimes ?? [])
+ .filter((k) => k === "off" || k.startsWith("off_"))
+ .find((k) => declared(k) && !others.some((x) => (x.regimes ?? []).includes(k)));
+ if (sole) { t.offKey = sole; return; }
+ t.offKey = globalOff && firstRegimeTrack === t ? globalOff : null;
+ });
+
+ return {
+ kind: "measure",
+ unit: s.unit ?? "",
+ yLabel: s.yLabel ?? (s.unit ? String(s.unit).toUpperCase() : "VALUE"),
+ yMin: Number.isFinite(s.yMin) ? s.yMin : null,
+ yMax: Number.isFinite(s.yMax) ? s.yMax : null,
+ from: s.from ?? null,
+ to: s.to ?? null,
+ tracks,
+ // The PROMISE forms are every measure ledger's (what he says he will do,
+ // and a later word about it): built in, so a schema written before them
+ // carries them without saying so.
+ forms: [...new Set([...(s.forms?.length ? s.forms.map(String) : DEFAULT_FORMS), ...PROMISE_FORMS])],
+ regimes,
+ /**
+ * The fields THIS manifest declares beyond the built-ins.
+ *
+ * Empty on every manifest written before this one, which is the whole
+ * compatibility contract: no `fields`, no behaviour, byte for byte.
+ */
+ fields,
+ bandGapDays: Number.isFinite(s.bandGapDays) ? s.bandGapDays : DEFAULT_BAND_GAP_DAYS,
+ /** How soon after a pledge a lapse still breaks it. */
+ pledgeDays: Number.isFinite(s.pledgeDays) ? s.pledgeDays : DEFAULT_PLEDGE_DAYS,
+ /**
+ * The regime a `stop` hands over to, when the schema declares one.
+ *
+ * Schema-wide, and the walk still reads it: `open`, `prevChange` and the
+ * band are about WHICH SEGMENT is running, and one flat off segment is a
+ * true enough answer for all of them. It is the LABEL that cannot be
+ * shared, and that is `tracks[].offKey`.
+ */
+ offKey: globalOff,
+ };
+}
+
+/** The vocabulary a page or an editor may offer. Derived, never restated. */
+export function measureVocab(schema) {
+ const s = measureSchema(schema);
+ return {
+ kind: "measure",
+ scopes: s.tracks.map((t) => t.key),
+ populations: s.forms,
+ valueKinds: VALUE_KINDS,
+ scopeConfidence: SCOPE_CONFIDENCE,
+ events: EVENTS,
+ regimes: s.regimes.map((r) => r.key),
+ tracks: s.tracks,
+ regimeList: s.regimes,
+ /** The declared fields, so a bench can draw one control per field. */
+ fields: s.fields,
+ unit: s.unit,
+ schema: s,
+ };
+}
+
+const trackOf = (s, key) => s.tracks.find((t) => t.key === key) ?? null;
+const regimeOf = (s, key) => s.regimes.find((r) => r.key === key) ?? null;
+
+/**
+ * Which of the gate fields a measure entry is missing or has wrong.
+ *
+ * The same six as headcount, plus TWO that only exist here and are not
+ * optional extras: a regime claim with no `event` cannot open or close a
+ * segment, and one whose `value` is not a declared regime cannot be drawn at
+ * all. Both would fail SILENTLY -- the band would simply be shorter than the
+ * evidence -- which is the failure mode the gate exists to make loud.
+ */
+export function measureGaps(entry, schema) {
+ const s = measureSchema(schema);
+ const gaps = [];
+ const tr = trackOf(s, entry?.scope);
+ if (!tr) gaps.push("scope");
+ if (!isStr(entry?.scopeBasis)) gaps.push("scopeBasis");
+ if (!SCOPE_CONFIDENCE.includes(entry?.scopeConfidence)) gaps.push("scopeConfidence");
+ if (!s.forms.includes(entry?.population)) gaps.push("population");
+ if (!VALUE_KINDS.includes(entry?.valueKind)) gaps.push("valueKind");
+ if (!Array.isArray(entry?.flags)) gaps.push("flags");
+ if (tr?.role === "regime") {
+ if (!EVENTS.includes(entry?.event)) gaps.push("event");
+ if (!regimeOf(s, entry?.value)) gaps.push("value");
+ }
+ return gaps;
+}
+
+/**
+ * Whether a declared field is offered on THIS row.
+ *
+ * `appliesTo` narrows a field to the rows it can mean anything on: `breaks` is
+ * a question about a drink, and offering it on a weight reading is how a bench
+ * ends up carrying an answer no arithmetic will ever read.
+ */
+export function fieldApplies(field, entry, schema) {
+ const a = field?.appliesTo;
+ if (!a) return true;
+ const s = measureSchema(schema);
+ const tr = trackOf(s, entry?.scope);
+ const got = {
+ scope: entry?.scope ?? null,
+ value: entry?.value ?? null,
+ role: tr?.role ?? null,
+ population: entry?.population ?? null,
+ event: entry?.event ?? null,
+ };
+ return Object.entries(a).every(([k, want]) => String(got[k] ?? "") === want);
+}
+
+/**
+ * The declared-field half of a claim edit: what to write, what to delete, and a
+ * loud error for anything else.
+ *
+ * Called AFTER the built-ins have been validated and BEFORE the write, so a
+ * patch that is half legal writes nothing at all. Keys the schema does not
+ * declare are not this function's business and are left alone — the caller has
+ * already ruled on the built-ins, and a key in neither set is what
+ * `LEDGER_BUILTIN_KEYS` and `umtool check` are for.
+ *
+ * `null` and `""` CLEAR, for every kind. A field an operator has emptied is a
+ * field they are saying nothing about, and leaving `""` on the row would put an
+ * answer of "" in front of the next reader.
+ *
+ * @param {object} entry the row as it stands
+ * @param {object} patch the incoming edit
+ * @param {object} schema `manifest.ledgerSchema`
+ * @param {Array<object>} [ledger] needed only to resolve a `rowRef`
+ * @returns {{ set: Record<string, unknown>, clear: string[] }}
+ */
+export function validateFields(entry, patch, schema, ledger = []) {
+ const s = measureSchema(schema);
+ const set = {};
+ const clear = [];
+ const merged = { ...(entry ?? {}), ...(patch ?? {}) };
+ for (const f of s.fields) {
+ if (!(patch && Object.prototype.hasOwnProperty.call(patch, f.key))) continue;
+ const raw = patch[f.key];
+ const bad = (why) => {
+ throw new Error(`\`${f.key}\` (${f.label}): ${why}`);
+ };
+ if (raw == null || raw === "") { clear.push(f.key); continue; }
+ if (!fieldApplies(f, merged, s)) {
+ bad(
+ "this row does not carry it — " +
+ Object.entries(f.appliesTo).map(([k, v]) => `${k} must be ${v}`).join(", "),
+ );
+ }
+ switch (f.kind) {
+ case "text": {
+ if (typeof raw !== "string") bad("must be text");
+ const v = raw.trim();
+ if (!v) { clear.push(f.key); break; }
+ if (v.length > f.maxLength) bad(`${v.length} characters, and ${f.maxLength} is the most`);
+ set[f.key] = v;
+ break;
+ }
+ case "enum": {
+ const v = String(raw);
+ if (!f.options.includes(v)) bad(`\`${v}\` is not one of ${f.options.join(" ")}`);
+ set[f.key] = v;
+ break;
+ }
+ case "number": {
+ const n = Number(raw);
+ if (!Number.isFinite(n)) bad("must be a number");
+ if (f.min != null && n < f.min) bad(`${n} is below ${f.min}`);
+ if (f.max != null && n > f.max) bad(`${n} is above ${f.max}`);
+ set[f.key] = n;
+ break;
+ }
+ case "seconds": {
+ const n = Number(raw);
+ if (!Number.isFinite(n)) bad("must be a number of seconds");
+ if (n < 0) bad(`${n} is before the start of the clip`);
+ set[f.key] = n;
+ break;
+ }
+ case "bool": {
+ // STRICT. `"false"` is a truthy string and a bug, never a value: a
+ // checkbox posted as text is exactly how a flag comes back on for
+ // every row it was turned off on.
+ if (typeof raw !== "boolean") bad("must be true or false, not a string");
+ set[f.key] = raw;
+ break;
+ }
+ case "rowRef": {
+ const v = String(raw);
+ if (v === entry?.id) bad("a row cannot refer to itself");
+ if (!(ledger ?? []).some((r) => r?.id === v)) bad(`no ledger row has the id \`${v}\``);
+ set[f.key] = v;
+ break;
+ }
+ default:
+ bad(`kind \`${f.kind}\` has no rule`);
+ }
+ }
+ return { set, clear };
+}
+
+/** The date a claim is ABOUT, which is the date it is drawn at. */
+export const plotDate = (entry) => entry?.asOf ?? entry?.date ?? null;
+
+/**
+ * The bound a row puts on its own figure, when a `render: "cell"` field says.
+ *
+ * "Over 240", "almost 390", "close to 380-390" — he bounded the number rather
+ * than giving it, and the board has been printing the bound as though it were
+ * the figure. The glyph goes in FRONT of the display and nowhere else: the
+ * NUMBER is unchanged everywhere it is used, because a bound is still the only
+ * figure he gave and the arithmetic has nothing else to work with.
+ *
+ * Idempotent — a display an operator has already written as `>300 lb` is left
+ * alone, which is what lets `restate()` swap the number in one without the
+ * glyph coming back twice.
+ */
+export function measureQualifier(entry, schema) {
+ const s = measureSchema(schema);
+ const f = s.fields.find((x) => x.render === "cell" && x.kind === "enum");
+ if (!f) return null;
+ const q = entry?.[f.key];
+ return q && f.options.includes(String(q)) ? String(q) : null;
+}
+
+function withQualifier(text, entry, s) {
+ const q = measureQualifier(entry, s);
+ if (!q) return text;
+ const t = String(text);
+ const f = s.fields.find((x) => x.render === "cell" && x.kind === "enum");
+ return f.options.some((o) => t.startsWith(o)) ? t : `${q}${t}`;
+}
+
+/** A claim's own words for its figure, or the figure with its unit. */
+export function measureDisplay(entry, schema) {
+ const s = measureSchema(schema);
+ if (entry?.display) return withQualifier(String(entry.display), entry, s);
+ const tr = trackOf(s, entry?.scope);
+ if (tr?.role === "regime") {
+ const r = regimeOf(s, entry?.value);
+ return r ? r.label : String(entry?.value ?? "—");
+ }
+ if (entry?.value == null) return "—";
+ const n = Number(entry.value);
+ const sign = entry.population === "delta" && n > 0 ? "+" : "";
+ return withQualifier(s.unit ? `${sign}${n} ${s.unit}` : `${sign}${n}`, entry, s);
+}
+
+// ---------------------------------------------------------------------------
+// The band
+// ---------------------------------------------------------------------------
+
+/**
+ * Regime segments, and the silences between them.
+ *
+ * @param {Array<object>} claims regime-track claims, in plot-date order
+ * @param {object} s a normalised schema
+ * @param {string|null} bandTo the right edge — the last thing the ledger says
+ */
+function buildBand(claims, s, bandTo) {
+ const gap = s.bandGapDays;
+ const band = [];
+ /** Every silence longer than `bandGapDays`, drawn or not. The decisions. */
+ const gaps = [];
+ /** The segment being asserted: regime, when it opened, and what supports it. */
+ let cur = null;
+
+ const close = (to, reason) => {
+ if (!cur) return;
+ if (dayOf(to) > dayOf(cur.from)) {
+ band.push({ ...cur, to, reason });
+ }
+ cur = null;
+ };
+
+ /** Silence long enough that the segment stops speaking for itself. */
+ const lapse = (at) => {
+ if (!cur) return;
+ if (daysBetween(cur.lastAt, at) <= gap) return;
+ const edge = addDays(cur.lastAt, gap);
+ // The SILENCE, not the undrawn remainder: the operator is being pointed at
+ // a stretch to go and find claims in, and that stretch runs from the last
+ // thing he said to the next one.
+ gaps.push({
+ from: cur.lastAt,
+ to: at,
+ days: Math.round(daysBetween(cur.lastAt, at)),
+ regime: cur.regime,
+ after: cur.ids[cur.ids.length - 1] ?? null,
+ });
+ close(edge, "silence");
+ if (daysBetween(edge, at) >= MIN_UNKNOWN_DAYS) {
+ band.push({
+ unknown: true,
+ regime: null,
+ label: "he says nothing",
+ from: edge,
+ to: at,
+ ids: [],
+ reason: "silence",
+ });
+ }
+ };
+
+ for (const c of claims) {
+ const at = plotDate(c);
+ if (!at) continue;
+ lapse(at);
+ const R = regimeOf(s, c.value);
+ if (!R) continue;
+
+ if (OPENING.has(c.event)) {
+ if (cur && cur.regime === R.key) {
+ cur.lastAt = at;
+ cur.ids.push(c.id);
+ } else {
+ close(at, "replaced");
+ cur = { regime: R.key, label: R.label, color: R.color, from: at, lastAt: at, ids: [c.id] };
+ }
+ continue;
+ }
+ if (CLOSING.has(c.event)) {
+ // An off for a regime that is not the one drawn leaves the band alone.
+ if (cur && !offCloses(cur.regime, R.key, s.offKey)) {
+ cur.lastAt = at;
+ cur.ids.push(c.id);
+ continue;
+ }
+ close(at, "stopped");
+ // A quit is itself a claim about what he is on: nothing. Drawn as such
+ // when the schema declares an `off` regime, and left as silence when it
+ // does not -- inventing an "off" the author never defined would be
+ // putting a word on screen nobody chose.
+ if (s.offKey && R.key !== s.offKey) {
+ const off = regimeOf(s, s.offKey);
+ cur = { regime: off.key, label: off.label, color: off.color, from: at, lastAt: at, ids: [c.id] };
+ } else if (s.offKey && R.key === s.offKey) {
+ cur = { regime: R.key, label: R.label, color: R.color, from: at, lastAt: at, ids: [c.id] };
+ }
+ }
+ }
+
+ if (cur && bandTo) {
+ lapse(bandTo);
+ close(bandTo, "open");
+ }
+ return { band, gaps };
+}
+
+// ---------------------------------------------------------------------------
+// The predicates
+// ---------------------------------------------------------------------------
+
+const fmt = (n, unit) => (unit ? `${n} ${unit}` : String(n));
+
+/** Two readings of the same quantity, close in time, far apart in value. */
+function contradictsRecent(pt, prev, s) {
+ if (!prev) return null;
+ const days = Math.abs(daysBetween(prev.at, pt.at));
+ const diff = Math.abs(pt.value - prev.value);
+ if (days > MEASURE_THRESHOLDS.recentDays) return null;
+ if (diff <= MEASURE_THRESHOLDS.recentDelta) return null;
+ return {
+ rule: "contradicts_recent",
+ text:
+ `he says ${fmt(pt.value, s.unit)}; he said ${fmt(prev.value, s.unit)} ` +
+ `${gapWords(prev.at, pt.at)} — ${fmt(diff, s.unit)} apart`,
+ against: prev.id,
+ };
+}
+
+/** What he says NOW he weighed THEN, against what he said at the time. */
+function retroMismatch(pt, contemporaneous, s) {
+ if (pt.form !== "past") return null;
+ const near = contemporaneous
+ .filter(
+ (o) =>
+ o.id !== pt.id &&
+ o.form === "current" &&
+ Math.abs(daysBetween(o.at, pt.at)) <= MEASURE_THRESHOLDS.retroWindowDays,
+ )
+ .sort((a, b) => Math.abs(daysBetween(a.at, pt.at)) - Math.abs(daysBetween(b.at, pt.at)))[0];
+ if (!near) return null;
+ const diff = Math.abs(pt.value - near.value);
+ if (diff <= MEASURE_THRESHOLDS.retroDelta) return null;
+ return {
+ rule: "retro_mismatch",
+ text:
+ `he now says ${fmt(pt.value, s.unit)} for ${pt.at}; at the time he said ` +
+ `${fmt(near.value, s.unit)} (${near.at}) — ${fmt(diff, s.unit)} apart`,
+ against: near.id,
+ };
+}
+
+/** A regime that replaced another one before a month was out. */
+function regimeFlip(c, prevChange, s) {
+ if (!prevChange) return null;
+ const days = daysBetween(prevChange.at, c.at);
+ if (!(days >= 0 && days < MEASURE_THRESHOLDS.flipDays)) return null;
+ return {
+ rule: "regime_flip",
+ text:
+ `${regimeOf(s, prevChange.regime)?.label ?? prevChange.regime} ` +
+ `${gapWords(prevChange.at, c.at)}, now ${regimeOf(s, c.regime)?.label ?? c.regime}`,
+ against: prevChange.id,
+ };
+}
+
+/** A new regime with no word about the one it displaced. */
+function quitUnannounced(c, open, s) {
+ if (!open || open.regime === c.regime) return null;
+ if (s.offKey && open.regime === s.offKey) return null;
+ if (open.stopped) return null;
+ return {
+ rule: "quit_unannounced",
+ text:
+ `he starts ${regimeOf(s, c.regime)?.label ?? c.regime} and never says he stopped ` +
+ `${regimeOf(s, open.regime)?.label ?? open.regime} (${open.at})`,
+ against: open.id,
+ };
+}
+
+/**
+ * He said he had stopped, and then he says he did it again.
+ *
+ * The one predicate in this file that is about a PROMISE rather than about a
+ * number. It fires on the lapse, never on the pledge -- the pledge was true
+ * when he made it, and striking the row where a man says he is quitting as
+ * though the row itself were the lie is not what the ledger shows.
+ *
+ * `days` is on the flag because the panel's chip reads it out ("drank · 2 days
+ * after quitting") and re-deriving it there would be a second arithmetic over
+ * the same two dates.
+ */
+function brokePledge(c, pledge, s, { explicit = false } = {}) {
+ if (!pledge) return null;
+ const days = Math.round(daysBetween(pledge.at, c.at));
+ // AN EXPLICIT BREAK IS NOT SUBJECT TO THE WINDOW. The window is a proxy for
+ // "these two claims are about each other", and a `breaks` reference is the
+ // adjudicator saying so outright — a proxy does not get to overrule the thing
+ // it stands in for. The bound that keeps a bounded pledge finite is on the
+ // OPEN state, in the walk, and it lets a named pledge through for the same
+ // reason.
+ if (!(days >= 0 && (explicit || days <= s.pledgeDays))) return null;
+ const pledgeLabel = regimeOf(s, pledge.regime)?.label ?? pledge.regime;
+ return {
+ rule: "broke_pledge",
+ text:
+ `${pledgeLabel} on ${pledge.at}, ` +
+ `${regimeOf(s, c.regime)?.label ?? c.regime.toLowerCase()} ${gapWords(pledge.at, c.at).replace(/ earlier$/, " later")}`,
+ against: pledge.id,
+ days,
+ /** The pledge, by key and by name — the chip quotes the board's own word. */
+ pledgeRegime: pledge.regime,
+ pledgeLabel,
+ /** Did the adjudicator name this pair, or did the window find it? */
+ explicit,
+ };
+}
+
+/** Two claims on the same track, the same day, saying different things. */
+function sameDayConflict(c, peers, s) {
+ const other = peers.find((o) => o.id !== c.id && o.value != null && o.value !== c.value);
+ if (!other) return null;
+ const tr = trackOf(s, c.scope);
+ const one = tr?.role === "regime"
+ ? `${regimeOf(s, c.value)?.label ?? c.value} and ${regimeOf(s, other.value)?.label ?? other.value}`
+ : `${fmt(c.value, s.unit)} and ${fmt(other.value, s.unit)}`;
+ return {
+ rule: "same_day_conflict",
+ text: `two different ${tr?.label ?? c.scope} claims the same day — ${one}`,
+ against: other.id,
+ };
+}
+
+/** Our arithmetic or our midpoint, wearing his voice. Unchanged in meaning. */
+function notHisNumber(c) {
+ if (c.valueKind === "uttered") return null;
+ return {
+ rule: "not_his_number",
+ text: c.valueKind === "derived" ? "our arithmetic, not his figure" : "our midpoint, not his figure",
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The walk
+// ---------------------------------------------------------------------------
+
+export class UnadjudicatedMeasureLedger extends Error {
+ constructor(entries) {
+ const ids = entries.map((e) => e?.id ?? "?");
+ super(
+ `${ids.length} ledger entr${ids.length === 1 ? "y is" : "ies are"} unadjudicated ` +
+ `(${ids.slice(0, 6).join(", ")}${ids.length > 6 ? ", …" : ""}). ` +
+ "The series and the band both lie if you act on an unadjudicated ledger — " +
+ "work the inbox first.",
+ );
+ this.name = "UnadjudicatedLedger";
+ this.entries = entries;
+ this.ids = ids;
+ }
+}
+
+/**
+ * Points, band, predicates and the final state — one pass, in plot-date order.
+ *
+ * @param {Array<object>} ledger
+ * @param {object} schema `manifest.ledgerSchema`
+ * @param {{ strict?: boolean }} [opts] strict:false computes over whatever is
+ * adjudicated, so an inbox can show coherence rows while work proceeds.
+ */
+export function measureTotals(ledger, schema, { strict = true } = {}) {
+ const s = measureSchema(schema);
+ const all = chronological(ledger).sort((a, b) => {
+ const d = dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b)));
+ if (d !== 0) return d;
+ const u = dateKey(a.date).localeCompare(dateKey(b.date));
+ return u !== 0 ? u : String(a.id).localeCompare(String(b.id));
+ });
+ const pending = all.filter((e) => measureGaps(e, s).length);
+ if (strict && pending.length) throw new UnadjudicatedMeasureLedger(pending);
+
+ const usable = all.filter((e) => !measureGaps(e, s).length && e.scopeConfidence !== "unresolved");
+
+ // Every claim that carries a reading of the quantity itself, at the date it
+ // is about. `past` rides the same line as `current`: he is describing the
+ // same scale, and separating them into two series would hide the one thing
+ // worth seeing, which is where the two disagree.
+ const points = usable
+ .filter((e) => trackOf(s, e.scope)?.role === "value")
+ .filter((e) => PLOTTING_FORMS.has(e.population) && Number.isFinite(Number(e.value)))
+ .map((e) => ({
+ id: e.id,
+ at: plotDate(e),
+ date: e.date,
+ asOf: e.asOf ?? null,
+ value: Number(e.value),
+ form: e.population,
+ scope: e.scope,
+ display: measureDisplay(e, s),
+ hedged: !!e.hedged,
+ entryId: e.entryId ?? null,
+ }));
+
+ // The three forms that are ABOUT the quantity without being a reading of it.
+ // None of them may join the line: "down fifty pounds" is not a weight, and
+ // drawing it at y=50 is the same class of error as plotting a midpoint.
+ const marksFor = (form) =>
+ usable
+ .filter(
+ (e) =>
+ trackOf(s, e.scope)?.role === "value" &&
+ e.population === form &&
+ Number.isFinite(Number(e.value)),
+ )
+ .map((e) => ({
+ id: e.id,
+ at: plotDate(e),
+ value: Number(e.value),
+ display: measureDisplay(e, s),
+ entryId: e.entryId ?? null,
+ }));
+ const marks = {
+ delta: marksFor("delta"),
+ goal: marksFor("goal"),
+ overweightBy: marksFor("overweight_by"),
+ };
+
+ const lastAt = all.map(plotDate).filter(Boolean).map(dateKey).sort().pop() ?? null;
+ const bandTo = s.to && lastAt ? (dateKey(s.to) < lastAt ? s.to : lastAt) : (lastAt ?? s.to);
+
+ // ONE BAND PER REGIME TRACK. It used to be one band over every regime claim
+ // there was, which is correct for exactly one regime track and nonsense for
+ // two: a `dry` opening on the drinking track CLOSED the keto segment on the
+ // diet track, because to a flattened walk they are the same strip changing
+ // its mind. `totals.band` stays the first regime track's, so every existing
+ // consumer -- the chart's one row, the closing card, regimeGaps() -- reads
+ // exactly what it read before.
+ const regimeTracks = s.tracks.filter((t) => t.role === "regime");
+ const bands = {};
+ for (const t of regimeTracks) {
+ bands[t.key] = buildBand(usable.filter((e) => e.scope === t.key), s, bandTo);
+ }
+ const firstRegime = regimeTracks[0] ?? null;
+ const band = firstRegime ? bands[firstRegime.key].band : [];
+ const gaps = firstRegime ? bands[firstRegime.key].gaps : [];
+
+ // ---- the walk, for the predicates and the rail ----
+ // Keyed by FORM as well as track and date, and that is not a detail. "I'm at
+ // 339, and I want to be 300 by Christmas" is one sentence: a `current` and a
+ // `goal`, on one day, holding two different numbers -- and keyed on the track
+ // alone it flagged both rows as a contradiction. They are not comparable, and
+ // neither is a `delta` against a reading. Two goals the same day still are.
+ const byTrackDate = new Map();
+ for (const e of usable) {
+ const k = `${e.scope}|${dateKey(plotDate(e))}|${e.population}`;
+ if (!byTrackDate.has(k)) byTrackDate.set(k, []);
+ byTrackDate.get(k).push({ id: e.id, value: e.value });
+ }
+
+ const steps = [];
+ const series = Object.fromEntries(s.tracks.map((t) => [t.key, []]));
+ let prevPoint = null;
+ // Per TRACK, all three of them. `regime_flip` and `quit_unannounced` both ask
+ // "what was he on before this", and shared across two regime tracks the
+ // answer is whichever strip spoke last -- so a pledge to stop drinking read
+ // as an unannounced quit of keto, and a diet started a fortnight after a
+ // pledge read as a flip. Same for the counter: a switch is a switch OF
+ // SOMETHING.
+ const prevChange = new Map();
+ const open = new Map();
+ /**
+ * The pledge each regime track has open, and the ones already broken.
+ *
+ * Separate from `open` on purpose. `open` is what he is on; this is what he
+ * PROMISED, and the two part company at exactly the moment that matters --
+ * the drink. Keyed by track for the same reason everything else here is: a
+ * pledge about alcohol has nothing to say about a diet.
+ */
+ const openPledge = new Map();
+ const brokenPledges = new Set();
+ const isBounded = (kind) => kind === "bounded";
+ /**
+ * Every pledge some later row NAMES as the one it broke.
+ *
+ * Read once, off the ledger, because the open window below has to know
+ * whether a bounded pledge is still owed an answer. A pledge nobody marked
+ * goes quiet after `pledgeDays`; one the adjudicator has named stays open
+ * until the row that names it arrives, whenever that is. The window is a
+ * proxy for "these two claims are about each other" and the mark is the
+ * adjudicator saying so, so the mark outranks it.
+ */
+ const namedPledges = new Set(
+ (ledger ?? []).map((e) => e?.breaks).filter((v) => isStr(v)).map(String),
+ );
+ /**
+ * The pledge open on this track AT THIS DATE, or none.
+ *
+ * A BOUNDED pledge survives an unmarked drink and therefore needs some other
+ * end, or it goes on collecting lapses years after he stopped talking about
+ * it. `pledgeDays` is that end — the same window the automatic rule uses,
+ * doing the same job in the one place a bounded pledge lets it.
+ */
+ const livePledge = (scope, at) => {
+ const p = openPledge.get(scope) ?? null;
+ if (!p || !isBounded(p.kind) || namedPledges.has(p.id)) return p;
+ if (Math.round(daysBetween(p.at, at)) <= s.pledgeDays) return p;
+ openPledge.delete(scope);
+ return null;
+ };
+ const switchesBy = new Map(regimeTracks.map((t) => [t.key, 0]));
+ const counted = () => Object.fromEntries(switchesBy);
+ /** The first regime track's count, which is what `switches` has always meant. */
+ const firstSwitches = () => (firstRegime ? switchesBy.get(firstRegime.key) ?? 0 : 0);
+ let lastValue = null;
+ let lastRegime = null;
+
+ for (const e of all) {
+ const gaps = measureGaps(e, s);
+ const ruled = gaps.length === 0;
+ const settled = ruled && e.scopeConfidence !== "unresolved";
+ const tr = trackOf(s, e.scope);
+ const at = plotDate(e);
+ const flags = [];
+
+ const pt = points.find((p) => p.id === e.id) ?? null;
+
+ if (settled) {
+ const f0 = notHisNumber(e);
+ if (f0) flags.push(f0);
+ const peers = byTrackDate.get(`${e.scope}|${dateKey(at)}|${e.population}`) ?? [];
+ const f1 = sameDayConflict({ ...e }, peers, s);
+ if (f1) flags.push(f1);
+
+ if (pt) {
+ // Only `current` against `current`. A retrospective plotted three days
+ // from a contemporaneous reading is exactly what `retro_mismatch` is
+ // for, and letting this predicate see it too reports one disagreement
+ // twice under two different names.
+ if (pt.form === "current") {
+ const f2 = contradictsRecent(pt, prevPoint, s);
+ if (f2) flags.push(f2);
+ }
+ const f3 = retroMismatch(pt, points, s);
+ if (f3) flags.push(f3);
+ }
+
+ if (tr?.role === "regime") {
+ const R = regimeOf(s, e.value);
+ const here = { id: e.id, at, regime: R?.key ?? null };
+ const wasOpen = open.get(e.scope) ?? null;
+ const isFirst = firstRegime && e.scope === firstRegime.key;
+ const bump = () => switchesBy.set(e.scope, (switchesBy.get(e.scope) ?? 0) + 1);
+ if (OPENING.has(e.event) && R) {
+ // THE PLEDGE LEDGER IS THE ADJUDICATION'S OWN EVENT SEMANTICS, and it
+ // is kept OUTSIDE the "did the word on the board change" test.
+ //
+ // `start` is an act — he makes the promise, he takes the drink.
+ // `on` is a report: "I'm nine days dry" is not a new pledge, and "I
+ // was a four-days-a-week drinker" is not a fresh drink against one.
+ // Counting every opening made 122 pledges out of 27 and 58 breaks out
+ // of the fourteen the adjudication names.
+ //
+ // Outside the gate because a habitual admission moves the board to
+ // Drinking without breaking anything, and the fresh drink that DOES
+ // break the pledge then finds the regime already changed. That is the
+ // d030 case exactly: the pledge stands until d032, ten days later.
+ //
+ // A BOUNDED pledge is the one shape the window cannot read. "Two
+ // nights a week is all he's allowed" is not broken by drinking; it is
+ // broken by drinking MORE than that, and only the adjudicator can say
+ // which drink did. So a bounded pledge breaks where — and only where —
+ // a `breaks` reference names it.
+ const pledge = livePledge(e.scope, at);
+ const explicit = isStr(e.breaks) && !!pledge && e.breaks === pledge.id;
+ const isLapse = R.kind === "lapse" && e.event === "start";
+ const breakable =
+ isLapse && pledge && !brokenPledges.has(pledge.id) &&
+ (isBounded(pledge.kind) ? explicit : true);
+ const broke = breakable ? brokePledge(here, pledge, s, { explicit }) : null;
+ if (broke) {
+ flags.push(broke);
+ brokenPledges.add(pledge.id);
+ }
+ // A promise replaces the one before it; a fresh drink ends the one it
+ // was taken against, inside the window or not — he is drinking now
+ // either way, and a pledge left open would go on collecting lapses
+ // that have nothing to do with it. A recounted drink ends nothing.
+ if (isPledgeKind(R.kind) && e.event === "start") {
+ openPledge.set(e.scope, { id: e.id, at, regime: R.key, kind: R.kind });
+ } else if (isLapse && pledge && (!isBounded(pledge.kind) || broke)) {
+ // …AND AN UNMARKED DRINK DOES NOT CLOSE A BOUNDED ONE. Closing it
+ // would be reading "he drank" as "the bound is over", which is the
+ // one inference a bound exists to refuse — and the marked violation
+ // that arrives a fortnight later would then find nothing open.
+ openPledge.delete(e.scope);
+ }
+
+ if (!wasOpen || wasOpen.regime !== R.key) {
+ // ONE EVENT, ONE NAME. A drink two days after "I've stopped
+ // drinking" is a broken pledge; it is also, mechanically, an
+ // unannounced quit and a flip, and all three firing on the one
+ // claim reads in the inbox as three separate findings about one
+ // drink. The specific name wins and the two generic ones are
+ // suppressed. (This CHANGES the inbox output for drinking-track
+ // admissions, which is a queue the operator works — and it changes
+ // it again now that a recounted drink no longer takes the specific
+ // name and so keeps the generic ones.)
+ if (!broke) {
+ const f4 = quitUnannounced(here, wasOpen, s);
+ if (f4) flags.push(f4);
+ const f5 = regimeFlip(here, prevChange.get(e.scope) ?? null, s);
+ if (f5) flags.push(f5);
+ }
+ if (wasOpen) bump();
+ prevChange.set(e.scope, here);
+ open.set(e.scope, { id: e.id, at, regime: R.key, stopped: false });
+ } else {
+ wasOpen.at = at;
+ }
+ if (isFirst) {
+ lastRegime = {
+ key: R.key, label: R.label, at, event: e.event,
+ since: prevChange.get(e.scope)?.at ?? at,
+ };
+ }
+ } else if (CLOSING.has(e.event) && R &&
+ !offCloses(wasOpen && !wasOpen.stopped ? wasOpen.regime : null, R.key, s.offKey)) {
+ // AN OFF FOR ANOTHER REGIME: no switch, no close, the open rule stands
+ // (see `offCloses`). Deliberately a branch that does nothing.
+ } else if (CLOSING.has(e.event) && R) {
+ // He said the rule was over, out loud, before doing it again. That is
+ // not a broken pledge and calling it one would be the overreach that
+ // makes every other red mark on the board suspect.
+ openPledge.delete(e.scope);
+ if (wasOpen && !wasOpen.stopped) bump();
+ open.set(e.scope, s.offKey ? { id: e.id, at, regime: s.offKey, stopped: true } : null);
+ prevChange.set(e.scope, { id: e.id, at, regime: s.offKey ?? R.key });
+ const off = s.offKey ? regimeOf(s, s.offKey) : null;
+ if (isFirst) {
+ lastRegime = {
+ key: off?.key ?? null,
+ label: off?.label ?? `off ${R.label}`,
+ at,
+ event: e.event,
+ since: at,
+ };
+ }
+ }
+ series[e.scope].push({ id: e.id, date: at, value: e.value, event: e.event });
+ } else if (pt) {
+ // `current` only, for both. `final.value` is what the rail's cell says,
+ // and the rail rolls on a contemporaneous reading and nothing else --
+ // a retrospective is about a date the walk has already gone past, and
+ // the two disagreeing would put one number in the tally and a different
+ // one in the closing card.
+ if (pt.form === "current") {
+ prevPoint = pt;
+ lastValue = { value: pt.value, at, display: pt.display };
+ }
+ series[e.scope].push({ id: e.id, date: at, value: pt.value });
+ }
+ }
+
+ for (const raw of e.flags ?? []) {
+ if (isStr(raw)) flags.push({ rule: "adjudicator", text: raw });
+ }
+
+ steps.push({
+ id: e.id,
+ date: e.date,
+ at,
+ asOf: e.asOf ?? null,
+ scope: e.scope ?? null,
+ role: tr?.role ?? null,
+ scopeConfidence: e.scopeConfidence ?? null,
+ scopeBasis: e.scopeBasis ?? null,
+ population: e.population ?? null,
+ form: e.population ?? null,
+ valueKind: e.valueKind ?? null,
+ value: e.value ?? null,
+ event: e.event ?? null,
+ /** The pledge this row is adjudicated to have broken, when one is named. */
+ breaks: isStr(e.breaks) ? String(e.breaks) : null,
+ display: e.display ?? (ruled ? measureDisplay(e, s) : null),
+ label: e.label ?? null,
+ quote: e.quote ?? null,
+ src: e.src ?? null,
+ entryId: e.entryId ?? null,
+ roles: Array.isArray(e.roles) && e.roles.length ? e.roles : null,
+ // No y position, ever, for anything that is not a reading. The same rule
+ // the headcount walk keeps for "several" and "very few".
+ qualitative: !pt,
+ plotted: !!pt,
+ /**
+ * Whether the walk actually COUNTED this row.
+ *
+ * Every consumer that wants "the rows that are real" was reconstructing
+ * it — points ∪ marks ∪ series ids, which misses `goal_loss` because it
+ * is in none of the three. The walk already knows; it just never said.
+ */
+ settled,
+ /** The first regime track's count, which is what this has always been. */
+ switches: firstSwitches(),
+ /** …and every track's, for a rail whose counter names a different one. */
+ switchesByTrack: counted(),
+ flags,
+ });
+ }
+
+ // What he is on NOW, as far as the ledger knows — and only a segment the band
+ // is still asserting counts. `reason`, not `!unknown`: a segment closed with
+ // reason "silence" has EXPIRED, and reading it here put "Keto, since March"
+ // in the closing card sixty days after the chart stopped drawing it.
+ const last = band[band.length - 1] ?? null;
+ const tail = last && last.reason === "open" ? last : null;
+
+ return {
+ kind: "measure",
+ schema: s,
+ steps,
+ points,
+ marks,
+ /** The FIRST regime track's, unchanged. `bands` carries all of them. */
+ band,
+ /** Every silence longer than `bandGapDays` — what a `regime-gap` row is. */
+ gaps,
+ /** `{ [trackKey]: { band, gaps } }` — one entry per regime track. */
+ bands,
+ series,
+ switches: firstSwitches(),
+ switchesByTrack: counted(),
+ unresolved: all.filter((e) => e.scopeConfidence === "unresolved").map((e) => e.id),
+ unadjudicated: pending.map((e) => e.id),
+ final: {
+ value: lastValue?.value ?? null,
+ valueAt: lastValue?.at ?? null,
+ display: lastValue?.display ?? null,
+ regime: tail ? tail.regime : null,
+ regimeLabel: tail ? tail.label : null,
+ regimeSince: tail ? tail.from : null,
+ lastRegime,
+ switches: firstSwitches(),
+ switchesByTrack: counted(),
+ },
+ };
+}
+
+/**
+ * The silences, as decisions. "He said nothing about what he was on here."
+ *
+ * Read off `totals.gaps`, which the walk records, and NOT off the band. The
+ * band is what gets drawn, and what gets drawn is subject to a suppression rule
+ * that has nothing to do with whether the silence matters.
+ */
+export function regimeGaps(totals) {
+ return (totals?.gaps ?? []).map((g) => ({ from: g.from, to: g.to, days: g.days }));
+}
+
+/**
+ * The same silences, on EVERY regime track, each tagged with whose it is.
+ *
+ * `regimeGaps()` answers for the first track and always did; a second regime
+ * track's silences would simply never reach the inbox, which is the quiet
+ * failure the gap rule exists to prevent.
+ */
+export function allRegimeGaps(totals) {
+ const out = [];
+ for (const [track, b] of Object.entries(totals?.bands ?? {})) {
+ for (const g of b.gaps ?? []) out.push({ track, from: g.from, to: g.to, days: g.days });
+ }
+ return out.sort((a, b) => String(a.from).localeCompare(String(b.from)));
+}
+
+// ---------------------------------------------------------------------------
+// The scoreboard
+// ---------------------------------------------------------------------------
+
+/**
+ * Every number the panel's totals line and the finale's scoreboard say, from
+ * ONE walk of the steps the ledger already produced.
+ *
+ * `final` is the closing figure for each; `running` is the same figures after
+ * every claim, in the walk's order and keyed by claim id. Two shapes rather
+ * than two functions, because the alternative was the totals line deriving
+ * "broken" one way at second 400 and the scoreboard deriving it another way at
+ * second 680 — and the whole argument of the cut rests on the two agreeing.
+ *
+ * Nothing here invents a figure. Every count is of ledger rows, every reading
+ * is one he gave, and the only arithmetic is subtraction of two of his own
+ * numbers — which is why the finale can say "every number here is a row in the
+ * ledger" and be telling the truth.
+ */
+export function measureScoreboard(totals) {
+ const s = totals.schema;
+ const regimeTracks = s.tracks.filter((t) => t.role === "regime");
+ const firstRegime = regimeTracks[0] ?? null;
+ const valueTrack = s.tracks.find((t) => t.role === "value") ?? null;
+ const kindOf = (k) => regimeOf(s, k)?.kind ?? null;
+
+ const running = [];
+ let diets = 0;
+ let pledges = 0;
+ let broken = 0;
+ let goals = 0;
+ let lastGoal = null;
+ let firstReading = null;
+ let lastReading = null;
+ let shortest = null;
+ let from = null;
+ let to = null;
+
+ for (const st of totals.steps) {
+ if (st.settled) {
+ if (st.at) {
+ if (from == null || dateKey(st.at) < dateKey(from)) from = st.at;
+ if (to == null || dateKey(st.at) > dateKey(to)) to = st.at;
+ }
+ // The DIETS count is the ledger's own switch counter, per track, not a
+ // second walk of the same rows. There were two implementations of "how
+ // many times has he changed his mind" once before and they disagreed on
+ // screen, in the same frame.
+ if (firstRegime) diets = st.switchesByTrack?.[firstRegime.key] ?? diets;
+
+ // A PLEDGE IS A `start`. The same rule the walk keeps, for the same
+ // reason: `on` is a report, not a promise. "I'm nine days dry" opened a
+ // new pledge under `OPENING`, and 27 promises scored 122.
+ //
+ // BOTH SHAPES COUNT. A bounded pledge is a promise he put a limit on
+ // rather than a stop to, and it is still a promise — counting only the
+ // stops would drop the 11 `cutting` starts and put "16 PLEDGES" on a
+ // board whose next figure is how many of 27 he broke.
+ if (st.role === "regime" && st.event === "start" && isPledgeKind(kindOf(st.value))) {
+ pledges += 1;
+ }
+ if (st.scope === valueTrack?.key) {
+ // THE NET SPANS THE WHOLE RECORD, and both ends of it are readings in
+ // the sense the CURRENT cell uses.
+ //
+ // It was the first and last `current` and nothing else, on the argument
+ // that a retrospective is about a date the walk has gone past. That is
+ // true of where a reading PLOTS and false of what it tells you: on the
+ // diet manifest it made the net "351 lb in 2025 → 338 lb in 2026", a
+ // thirteen-pound reading of an eight-year record, because for years he
+ // gave retrospectives and almost no contemporaneous figures. And it was
+ // never the rule the cell keeps — `freshestReading()` lets a `past`
+ // whose `asOf` is later win, so the closing figure could disagree with
+ // the number that had been on screen all film.
+ //
+ // So: the EARLIEST reading he gives, of either form, against the
+ // freshest one by the cell's own rule.
+ if (PLOTTING_FORMS.has(st.form) && Number.isFinite(Number(st.value))) {
+ const r = { value: Number(st.value), at: st.at, id: st.id };
+ if (!firstReading) firstReading = r;
+ if (freshestReading({ value: st.value, population: st.form }, st.at, lastReading)) {
+ lastReading = r;
+ }
+ }
+ if (st.form === "goal" || st.form === "goal_loss") {
+ goals += 1;
+ lastGoal = {
+ id: st.id, at: st.at, value: st.value, form: st.form,
+ display: st.display ?? null, deadline: st.deadline ?? null,
+ };
+ }
+ }
+ }
+
+ const bp = (st.flags ?? []).find((f) => f.rule === "broke_pledge");
+ if (bp) {
+ broken += 1;
+ if (!shortest || bp.days < shortest.days) {
+ shortest = { days: bp.days, pledge: bp.against, lapse: st.id, at: st.at };
+ }
+ }
+
+ // ONE DERIVATION. The finale's totals accumulate on screen during the roll
+ // and the closing scoreboard is the last entry of this same series, so the
+ // running figures carry every field the scoreboard shows — goals and the
+ // span included. Two walks of the same rows disagreed on screen once and it
+ // is not happening again for the sake of two more lines here.
+ running.push({
+ id: st.id,
+ at: st.at ?? null,
+ diets,
+ pledges,
+ broken,
+ goals,
+ days: from && st.at ? Math.round(daysBetween(from, st.at)) : 0,
+ net:
+ firstReading && lastReading && lastReading.id !== firstReading.id
+ ? Number((lastReading.value - firstReading.value).toFixed(1))
+ : null,
+ });
+ }
+
+ const days = from && to ? Math.round(daysBetween(from, to)) : 0;
+ return {
+ final: {
+ // A rounded remainder can reach twelve, and "4 YEARS, 12 MONTHS" is not a
+ // span anybody states. It carries — here AND in the finale's own span
+ // field, which is a second copy of the same two lines for the same reason
+ // the drums are a second copy of the same figures.
+ span: {
+ from, to, days,
+ ...(() => {
+ let years = Math.floor(days / 365.25);
+ let months = Math.round((days - years * 365.25) / 30.44);
+ if (months >= 12) { years += 1; months = 0; }
+ return { years, months };
+ })(),
+ claims: totals.steps.length,
+ },
+ diets: {
+ count: diets,
+ track: firstRegime?.key ?? null,
+ label: firstRegime?.shortLabel ?? firstRegime?.label ?? null,
+ everyDays: diets > 0 ? Math.round(days / diets) : null,
+ },
+ goals: { count: goals, last: lastGoal },
+ pledges: { count: pledges, broken, shortest },
+ net: {
+ from: firstReading?.value ?? null,
+ fromAt: firstReading?.at ?? null,
+ to: lastReading?.value ?? null,
+ toAt: lastReading?.at ?? null,
+ delta:
+ firstReading && lastReading
+ ? Number((lastReading.value - firstReading.value).toFixed(1))
+ : null,
+ unit: s.unit,
+ },
+ },
+ running,
+ };
+}
+
+/**
+ * The two boards the rev 6 finale needs, and the series that carries one to the
+ * other.
+ *
+ * Rev 6 pins every live row to a clip, so most of the ledger never reaches the
+ * screen during the cut. The orchestrator's ruling: the live panel derives from
+ * the ON-CAMERA rows alone -- a hidden row must not move a visible number with
+ * no visible cause -- and the combined figure is a thing the film reveals at
+ * the end. So there are two boards, and both of them are `measureScoreboard()`
+ * over a different walk. One derivation, two inputs, which is what stops the
+ * two disagreeing about what a pledge is.
+ *
+ * `bridge` is the series finale B ticks through, and it exists because the two
+ * walks ARE NOT ADDABLE. A count over a superset is not the count over the
+ * subset plus a per-row increment: a diet switch depends on its neighbour and a
+ * broken pledge on its pair, so a lapse whose pledge has no clip breaks nothing
+ * on camera and everything in the combined walk. `onCameraFinal + sum of hidden
+ * increments` therefore misses `combinedFinal`, and missing it is the one thing
+ * this sequence cannot do -- the last frame of the film is that number.
+ *
+ * The bridge is a DIFFERENCE OF THE TWO WALKS instead:
+ *
+ * bridge(i) = onCameraFinal + runningMax( combined(i) - onCamera(i) )
+ *
+ * where `onCamera(i)` is the on-camera walk's value as of the last on-camera
+ * row at or before position `i`. At the last row the difference is exactly
+ * `combinedFinal - onCameraFinal`. The running maximum is there because a
+ * difference of two monotone series is not itself monotone, and a total that
+ * ticks DOWN in the middle of the reveal reads as a bug rather than as an
+ * appendix.
+ *
+ * AND THE MAXIMUM IS CAPPED AT THE FINAL GAP. The two walks can pair the same
+ * lapse against different pledges -- a hidden lapse consumes a pledge the
+ * on-camera walk never saw broken, and a later on-camera lapse then breaks it
+ * FOR the on-camera walk -- so the difference can peak ABOVE the final gap in
+ * the middle and come back down. An uncapped maximum carries that peak to the
+ * last frame: this cut's board read 12 BROKEN against a ledger of 11, and
+ * rev 6 shipped 17 against 16, the same +1, at `d049`. The last frame of the
+ * film is the verdict, so the peak is clamped to the gap the verdict actually
+ * has. Still monotone -- a min with a constant cannot un-grow -- and now it
+ * lands exactly, which the sentence above used to claim and the maximum used
+ * to break.
+ */
+export function measureScoreboardSplit(totals, onCameraTotals) {
+ const combined = measureScoreboard(totals);
+ const onCamera = measureScoreboard(onCameraTotals);
+ const COUNTS = ["diets", "goals", "pledges", "broken"];
+ const byId = new Map(onCamera.running.map((r) => [r.id, r]));
+ const ZERO = { diets: 0, goals: 0, pledges: 0, broken: 0, days: 0, net: null };
+ /**
+ * THE SPAN IS NOT A COUNT and cannot be bridged as one. `days` is the
+ * distance from the walk's own first settled row, and the two walks do not
+ * start on the same day -- the record opens years before the footage does.
+ * A difference of the two therefore overshoots: the on-camera walk measures
+ * from 2018 while the combined one measures from 2013, so the gap at the last
+ * row is the whole of the earlier record and adding it to a span that already
+ * contains it counts those years twice. The span simply GROWS to the record's
+ * own, which is monotone, opens on the on-camera figure and ends on the
+ * combined one.
+ */
+ const spanOf = (r) => Math.max(camFinalDays, r.days ?? 0);
+ const camFinal = onCamera.running[onCamera.running.length - 1] ?? ZERO;
+ const camFinalDays = camFinal.days ?? 0;
+ const combFinal = combined.running[combined.running.length - 1] ?? ZERO;
+
+ let cam = ZERO;
+ const peak = { diets: 0, goals: 0, pledges: 0, broken: 0 };
+ const bridge = combined.running.map((r) => {
+ // The on-camera walk only moves at on-camera rows; between them it holds,
+ // which is what makes the difference attribute the growth to the hidden
+ // row that caused it.
+ cam = byId.get(r.id) ?? cam;
+ const out = { id: r.id, at: r.at, days: spanOf(r) };
+ for (const k of COUNTS) {
+ const gap = Math.max(0, (combFinal[k] ?? 0) - (camFinal[k] ?? 0));
+ peak[k] = Math.min(gap, Math.max(peak[k], (r[k] ?? 0) - (cam[k] ?? 0)));
+ out[k] = (camFinal[k] ?? 0) + peak[k];
+ }
+ // A net is two of his readings subtracted, not a tally, and either side of
+ // the difference can be null while he has given only one figure. With no
+ // on-camera net to carry there is nothing to add to, so the bridge simply
+ // shows the combined walk's own net -- which still lands on the verdict,
+ // because the verdict IS the combined walk's last value.
+ // AND IT TAKES NO RUNNING MAXIMUM. A count only goes up, so clamping it
+ // monotone costs nothing and buys a reveal that never stutters backwards.
+ // A net is a subtraction of two of his readings and moves both ways -- the
+ // whole argument of the rev 5 finale is watching it bounce -- so a maximum
+ // here would both misstate the middle and, because the largest gap is not
+ // the last one, MISS THE VERDICT: it read −35 against a record whose net is
+ // −52, on the last frame of the film.
+ // A FIGURE ALREADY ON SCREEN IS NEVER UN-SAID. The combined walk's net is
+ // null for the years before he gave two readings, and printing that null
+ // would take the on-camera net off the board an hour into the film and put
+ // an em dash where a number had been. It holds instead, and moves when
+ // there is something to move it by.
+ if (camFinal.net == null) out.net = r.net;
+ else if (r.net == null || cam.net == null) out.net = camFinal.net;
+ else out.net = Number((camFinal.net + (r.net - cam.net)).toFixed(1));
+ return out;
+ });
+
+ return { combined, onCamera, bridge };
+}
+
+// ---------------------------------------------------------------------------
+// The two rules a cell needs, and both drawings of it now ask the same file
+// ---------------------------------------------------------------------------
+
+/**
+ * Whether this claim is now the freshest READING of its track.
+ *
+ * `current` and nothing else used to fill the cell, on the reasoning that a
+ * retrospective is about a date the rail has already gone past. That holds
+ * right up until he stops giving contemporaneous figures: the diet cut sat on
+ * "240 lb as of 2022-06-15" for four minutes while three retrospectives about
+ * 2023 scrolled past under it, every one of them newer information about the
+ * same scale. So a `past` whose `asOf` is LATER than the reading on screen
+ * wins — the closing figure's rule, applied where it is visible.
+ *
+ * `prev` is the reading currently on screen for that track, or null.
+ */
+export function freshestReading(claim, at, prev) {
+ if (claim.value == null) return false;
+ if (claim.population === "current") return true;
+ if (claim.population !== "past") return false;
+ // WITH NOTHING ON SCREEN, A RETROSPECTIVE IS THE READING.
+ //
+ // The rule guarded against a retrospective overriding a contemporaneous
+ // figure, and `!!prev` was doing that job by refusing the case where there is
+ // nothing to override. Under rev 6's pinned-only board that became visible
+ // and wrong at once: the on-camera set opens on "390 lb, as of last year",
+ // the log prints it in the WEIGHT column, and the WEIGHT cell above it said
+ // "he has not given a figure" for five minutes. One board cannot make both
+ // statements about the same row.
+ return !prev || dateKey(at) > dateKey(prev.at);
+}
+
+/**
+ * A goal as a weight, when it can be one.
+ *
+ * "Lose forty" is not a weight. It becomes one only against the reading he had
+ * when he said it, and if he had not given one it stays the words he used —
+ * inventing an absolute out of nothing is the same error as plotting a midpoint
+ * as his figure.
+ */
+export function goalAbsolute(claim, base) {
+ if (claim.population === "goal_loss") {
+ return base ? Number((base.value + Number(claim.value)).toFixed(1)) : null;
+ }
+ return Number(claim.value);
+}
diff --git a/umtool/report-to-video/measure-totals.test.mjs b/umtool/report-to-video/measure-totals.test.mjs
@@ -0,0 +1,1076 @@
+// Tests for the MEASURE ledger kind (measure-totals.mjs, ledger-shared.mjs,
+// and ledger-totals.mjs's dispatch to them), ported from the diet-series
+// branch (scripts/report-to-video/ledger-totals.test.mjs there) with the
+// off-scope fix (offCloses). The headcount tests stay in ledger-totals.test.mjs;
+// the rail, panel and chart drawing tests of that branch are not ported (their
+// drawings are not on main). Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ ADJUDICATION_FIELDS,
+ EVENTS,
+ FIELD_KINDS,
+ LEDGER_BUILTIN_KEYS,
+ REGIME_KINDS,
+ MEASURE_PREDICATES,
+ claimVocab,
+ fieldApplies,
+ isPledgeKind,
+ ledgerFields,
+ ledgerKind,
+ regimeGaps,
+ adjudicationGaps,
+ ledgerTotals,
+ freshestReading,
+ measureSchema,
+ measureDisplay,
+ measureScoreboard,
+ measureScoreboardSplit,
+ measureTotals,
+ offCloses,
+ validateFields,
+} from "./ledger-totals.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const readFixture = (name) =>
+ JSON.parse(readFileSync(path.join(HERE, "fixtures", name), "utf8"));
+
+const SAMPLE = readFixture("measure-sample.manifest.json");
+const SCHEMA = SAMPLE.ledgerSchema;
+
+/** An adjudicated measure claim, with the boring answer for the six. */
+const mclaim = (o) => ({
+ scope: "weight",
+ scopeBasis: "he says it about himself",
+ scopeConfidence: "clear",
+ population: "current",
+ valueKind: "uttered",
+ flags: [],
+ ...o,
+});
+const totalsOf = (ledger, schema = SCHEMA) => ledgerTotals(ledger, { schema });
+
+const firedOn = (t, id) =>
+ (t.steps.find((s) => s.id === id)?.flags ?? []).map((f) => f.rule);
+
+/** A schema with a diet track and a drinking track, and both sets of regimes. */
+const TWO_TRACK = {
+ kind: "measure",
+ unit: "lb",
+ yLabel: "POUNDS",
+ from: "2025-01-01",
+ to: "2026-01-01",
+ bandGapDays: 60,
+ tracks: [
+ { key: "weight", role: "value", label: "His weight", color: "#22AB83" },
+ { key: "regime", role: "regime", label: "What he eats", shortLabel: "DIET", color: "#D2732F", regimes: ["keto", "carnivore", "off"] },
+ { key: "drinking", role: "regime", label: "What he drinks", shortLabel: "DRINKING", color: "#C55F9C", regimes: ["dry", "cutting", "drinking"] },
+ ],
+ forms: ["current", "past", "delta", "goal", "overweight_by", "status"],
+ regimes: [
+ { key: "keto", label: "Keto", color: "#D2732F" },
+ { key: "carnivore", label: "Carnivore", color: "#6A82DC" },
+ { key: "off", label: "No diet", color: "#98A29B" },
+ { key: "dry", label: "Dry", color: "#22AB83" },
+ { key: "cutting", label: "Cutting back", color: "#98A29B" },
+ { key: "drinking", label: "Drinking", color: "#C55F9C" },
+ ],
+};
+
+/** An adjudicated regime claim, on whichever track it names. */
+const reg = (o) => ({
+ scopeBasis: "he names it",
+ scopeConfidence: "clear",
+ population: "status",
+ valueKind: "uttered",
+ flags: [],
+ ...o,
+});
+
+
+const TWO_FIX = readFixture("measure-two-track.manifest.json");
+const twoTotals = () => totalsOf(TWO_FIX.ledger, TWO_FIX.ledgerSchema);
+const flagOn = (t, id, rule) =>
+ (t.steps.find((s) => s.id === id)?.flags ?? []).find((f) => f.rule === rule) ?? null;
+
+/** A drinking-track row, off the fixture's own template. */
+const drinkRow = (id, date, value, event) => ({
+ ...JSON.parse(JSON.stringify(TWO_FIX.ledger.find((r) => r.id === "p1"))),
+ id, date, value, event, entryId: null, display: value, label: id,
+});
+const seq = (...rows) => totalsOf(rows, TWO_FIX.ledgerSchema);
+
+/** A schema with one field of each kind, and nothing else new. */
+const fieldSchema = (fields) => ({
+ kind: "measure",
+ unit: "lb",
+ tracks: [
+ { key: "weight", role: "value", label: "WEIGHT" },
+ { key: "drinking", role: "regime", label: "DRINKING", regimes: ["dry", "drinking"] },
+ ],
+ regimes: [
+ { key: "dry", label: "Dry", kind: "pledge" },
+ { key: "drinking", label: "Drinking", kind: "lapse" },
+ ],
+ fields,
+});
+
+/** The two-track schema with `cutting` bounded rather than a plain stop. */
+const BOUNDED_SCHEMA = {
+ ...TWO_FIX.ledgerSchema,
+ regimes: TWO_FIX.ledgerSchema.regimes.map((r) =>
+ r.key === "cutting" ? { ...r, kind: "bounded" } : r,
+ ),
+ fields: [
+ { key: "breaks", label: "Breaks pledge", kind: "rowRef",
+ appliesTo: { scope: "drinking", value: "drinking", event: "start" } },
+ { key: "breaksWhy", label: "Why it breaks", kind: "text", maxLength: 200 },
+ ],
+};
+const bounded = (...rows) => totalsOf(rows, BOUNDED_SCHEMA);
+
+test("the kind, and the vocabulary, come off the schema", () => {
+ assert.equal(ledgerKind(SAMPLE), "measure");
+ const v = claimVocab(SAMPLE);
+ assert.deepEqual(v.scopes, ["weight", "regime"]);
+ // The schema's forms, then the promise forms every measure ledger carries.
+ assert.deepEqual(v.populations, ["current", "past", "delta", "goal", "overweight_by", "status", "promise", "promise_check", "promise_claim", "promise_outcome"]);
+ assert.deepEqual(v.events, EVENTS);
+ assert.deepEqual(v.regimes, ["keto", "carnivore", "off"]);
+ assert.equal(v.unit, "lb");
+});
+
+test("a measure claim is gated on the six, and a regime claim on two more", () => {
+ // A regime claim with no event cannot open or close a segment, and one whose
+ // value is not a declared regime cannot be drawn at all. Both would fail
+ // SILENTLY -- the band would just be shorter than the evidence.
+ assert.deepEqual(adjudicationGaps(mclaim({ id: "a", value: 300 }), SAMPLE), []);
+ assert.deepEqual(
+ adjudicationGaps(mclaim({ id: "b", scope: "regime", population: "status", value: "keto" }), SAMPLE),
+ ["event"],
+ );
+ assert.deepEqual(
+ adjudicationGaps(
+ mclaim({ id: "c", scope: "regime", population: "status", value: "paleo", event: "start" }),
+ SAMPLE,
+ ),
+ ["value"],
+ );
+ // The vocabulary is the SCHEMA's, not the headcount one.
+ assert.deepEqual(adjudicationGaps(mclaim({ id: "d", scope: "media" }), SAMPLE), ["scope"]);
+ assert.deepEqual(adjudicationGaps(mclaim({ id: "e", population: "employees" }), SAMPLE), ["population"]);
+});
+
+test("an unadjudicated measure ledger throws rather than plotting half a series", () => {
+ assert.throws(
+ () => totalsOf([{ id: "x", date: "2025-01-01", scope: "weight", value: 300 }]),
+ (err) => err.name === "UnadjudicatedLedger" && err.ids.includes("x"),
+ );
+});
+
+test("only `current` and `past` reach the line; the other forms are marks", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ assert.deepEqual(t.points.map((p) => p.id), ["w1", "w4", "w2", "w3", "w5"]);
+ assert.deepEqual(t.marks.delta.map((m) => m.id), ["d1"]);
+ assert.deepEqual(t.marks.goal.map((m) => m.id), ["g1"]);
+ assert.deepEqual(t.marks.overweightBy.map((m) => m.id), ["o1"]);
+});
+
+test("a retrospective plots at the date it is ABOUT, not the date he said it", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ const w4 = t.points.find((p) => p.id === "w4");
+ // Uttered 2026-02-01, about 2025-02-15. Plotting it at the utterance would
+ // draw a sixty-pound gain in 2026 that never happened.
+ assert.equal(w4.at, "2025-02-15");
+ assert.equal(w4.form, "past");
+ // …and the ordering is by the date it is about, so it lands between w1 and w2.
+ assert.deepEqual(t.points.map((p) => p.at), [
+ "2025-02-10", "2025-02-15", "2025-02-18", "2025-11-05", "2026-08-01",
+ ]);
+});
+
+test("the band opens on start, closes on a different start, and hands over on stop", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ const named = t.band.filter((b) => !b.unknown).map((b) => [b.regime, b.from, b.to]);
+ assert.deepEqual(named, [
+ ["keto", "2025-03-01", "2025-03-20"],
+ // carnivore is asserted for 60 days past the last claim that supports it,
+ // and no further.
+ ["carnivore", "2025-03-20", "2025-05-19"],
+ // a `stop` hands over to the schema's own `off` regime rather than to
+ // silence -- "he quit" IS a claim about what he is on.
+ ["off", "2026-01-15", "2026-03-16"],
+ ["keto", "2026-06-01", "2026-07-31"],
+ ]);
+});
+
+test("silence longer than bandGapDays is an `unknown` segment, not a longer regime", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ const drawn = t.band.filter((b) => b.unknown).map((b) => [b.from, b.to]);
+ assert.deepEqual(drawn, [
+ ["2025-05-19", "2026-01-15"],
+ ["2026-03-16", "2026-06-01"],
+ ]);
+ // The DECISION spans the whole silence, not just the undrawn remainder: the
+ // operator is being pointed at a stretch to go and find claims in, and that
+ // stretch runs from the last thing he said to the next one.
+ assert.deepEqual(regimeGaps(t).map((g) => [g.from, g.to, g.days]), [
+ ["2025-03-20", "2026-01-15", 301],
+ ["2026-01-15", "2026-06-01", 137],
+ // The last one has no hatch on the chart — the ledger's right edge is only
+ // a day past where the band expired — but the silence is still 61 days and
+ // the inbox is where that gets said.
+ ["2026-06-01", "2026-08-01", 61],
+ ]);
+});
+
+test("a gap is reported from the LAPSE, not from what survived the drawing rule", () => {
+ // Regression. The decision used to be read back off the band, and the band
+ // suppresses a hatched sliver under a week — so a 63-day silence produced no
+ // segment, therefore no decision, and the inbox went quiet about exactly the
+ // case the sixty-day rule exists to catch.
+ const at = (d) => [
+ mclaim({ id: "r1", date: "2025-01-01", scope: "regime", population: "status", value: "keto", event: "start" }),
+ mclaim({ id: "r2", date: d, scope: "regime", population: "status", value: "keto", event: "on" }),
+ ];
+
+ // 61 days: over the threshold by one, and the undrawn remainder is a single
+ // day, so nothing is hatched — and it is still a decision.
+ const one = totalsOf(at("2025-03-03"));
+ assert.equal(one.band.filter((b) => b.unknown).length, 0);
+ assert.deepEqual(regimeGaps(one).map((g) => g.days), [61]);
+
+ // 68 days: the remainder (eight) clears the drawing rule too, so it is both.
+ const six = totalsOf(at("2025-03-10"));
+ assert.equal(six.band.filter((b) => b.unknown).length, 1);
+ assert.deepEqual(regimeGaps(six).map((g) => g.days), [68]);
+
+ // 60 days exactly: not a lapse at all. One segment, no decision.
+ const none = totalsOf(at("2025-03-02"));
+ assert.deepEqual(regimeGaps(none), []);
+ assert.equal(none.band.length, 1);
+});
+
+test("a shorter silence is simply carried — the segment still speaks for it", () => {
+ const t = totalsOf([
+ mclaim({ id: "r1", date: "2025-01-01", scope: "regime", population: "status", value: "keto", event: "start" }),
+ mclaim({ id: "r2", date: "2025-02-10", scope: "regime", population: "status", value: "keto", event: "on" }),
+ ]);
+ // Forty days apart, under the sixty-day rule, so one segment and no hatch.
+ assert.equal(t.band.length, 1);
+ assert.equal(t.band[0].regime, "keto");
+ assert.deepEqual(t.band[0].ids, ["r1", "r2"]);
+});
+
+test("contradicts_recent: two readings close in time, far apart in value", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ // 380 on the 10th, 340 on the 18th: eight days, forty pounds.
+ assert.ok(firedOn(t, "w2").includes("contradicts_recent"));
+ const f = t.steps.find((s) => s.id === "w2").flags.find((x) => x.rule === "contradicts_recent");
+ assert.match(f.text, /340 lb; he said 380 lb 8 days earlier — 40 lb apart/);
+ assert.equal(f.against, "w1");
+ // Fluctuation is the SUBJECT, not a defect: fifteen pounds or less does not fire.
+ const mild = totalsOf([
+ mclaim({ id: "a", date: "2025-01-01", value: 340 }),
+ mclaim({ id: "b", date: "2025-01-08", value: 352 }),
+ ]);
+ assert.deepEqual(firedOn(mild, "b"), []);
+ // Nor does a big change with time to have happened in.
+ const slow = totalsOf([
+ mclaim({ id: "a", date: "2025-01-01", value: 400 }),
+ mclaim({ id: "b", date: "2025-06-01", value: 330 }),
+ ]);
+ assert.deepEqual(firedOn(slow, "b"), []);
+});
+
+test("retro_mismatch: what he says now he WAS, against what he said at the time", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ const f = t.steps.find((s) => s.id === "w4").flags.find((x) => x.rule === "retro_mismatch");
+ assert.ok(f);
+ assert.match(f.text, /he now says 400 lb for 2025-02-15; at the time he said 340 lb/);
+ // …and it is the ONLY thing that fires on it. A retrospective three days from
+ // a contemporaneous reading is one disagreement, and reporting it as
+ // `contradicts_recent` as well would be reporting it twice under two names.
+ assert.deepEqual(firedOn(t, "w4"), ["retro_mismatch"]);
+});
+
+test("regime_flip and quit_unannounced are different findings about the same claim", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ const rules = firedOn(t, "r2");
+ assert.ok(rules.includes("regime_flip"));
+ assert.ok(rules.includes("quit_unannounced"));
+ const flip = t.steps.find((s) => s.id === "r2").flags.find((x) => x.rule === "regime_flip");
+ assert.match(flip.text, /Keto 19 days earlier, now Carnivore/);
+ // A restart after an announced stop is neither: he said he stopped, and the
+ // gap is long enough that it is not a flip.
+ assert.deepEqual(firedOn(t, "r4"), []);
+});
+
+test("same_day_conflict: two claims on one track, one day, two answers", () => {
+ const t = totalsOf([
+ mclaim({ id: "a", date: "2025-01-01", value: 340 }),
+ mclaim({ id: "b", date: "2025-01-01", value: 355 }),
+ ]);
+ const f = t.steps.find((s) => s.id === "b").flags.find((x) => x.rule === "same_day_conflict");
+ assert.ok(f);
+ assert.match(f.text, /two different His weight claims the same day — 355 lb and 340 lb/);
+});
+
+test("not_his_number: our midpoint is never drawn as his figure", () => {
+ const t = totalsOf([mclaim({ id: "a", date: "2025-01-01", value: 337.5, valueKind: "synthetic" })]);
+ const f = t.steps.find((s) => s.id === "a").flags.find((x) => x.rule === "not_his_number");
+ assert.equal(f.text, "our midpoint, not his figure");
+});
+
+test("every predicate the module publishes actually fires somewhere", () => {
+ // The list and the code drifting apart is how a rule quietly stops existing.
+ const two = readFixture("measure-two-track.manifest.json");
+ const fired = new Set([
+ ...totalsOf(SAMPLE.ledger).steps.flatMap((s) => s.flags.map((f) => f.rule)),
+ // broke_pledge needs a track with a pledge AND a lapse on it, which the
+ // one-regime sample does not have and never will.
+ ...totalsOf(two.ledger, two.ledgerSchema).steps.flatMap((s) => s.flags.map((f) => f.rule)),
+ "same_day_conflict",
+ "not_his_number",
+ ]);
+ for (const rule of MEASURE_PREDICATES) assert.ok(fired.has(rule), `${rule} never fires`);
+});
+
+test("the switch counter counts changes of mind, and the final state is a LIVE segment", () => {
+ const t = totalsOf(SAMPLE.ledger);
+ // keto opens (not a change), carnivore replaces it, the stop, then keto again.
+ assert.equal(t.switches, 3);
+ assert.equal(t.final.value, 337);
+ // The sample's last keto segment EXPIRED — he said "keto, day three" on
+ // 2026-06-01 and nothing since, and the band stopped asserting it sixty days
+ // later. So there is no current regime, and saying "Keto, since June" in the
+ // closing card would be the card claiming what the chart refuses to draw.
+ assert.equal(t.band[t.band.length - 1].reason, "silence");
+ assert.equal(t.final.regime, null);
+ assert.equal(t.final.regimeSince, null);
+
+ // A claim inside the window keeps it live, and then it is reported.
+ const live = totalsOf([
+ ...SAMPLE.ledger,
+ mclaim({ id: "r5", date: "2026-07-15", scope: "regime", population: "status",
+ value: "keto", event: "on" }),
+ ]);
+ assert.equal(live.final.regime, "keto");
+ assert.equal(live.final.regimeSince, "2026-06-01");
+});
+
+test("same_day_conflict does not fire across FORMS", () => {
+ // "I'm at 339, and I want to be 300 by Christmas" is one sentence: a reading
+ // and a wish, on one day, holding two different numbers. Keyed on the track
+ // alone this flagged both rows as a contradiction.
+ const t = totalsOf([
+ mclaim({ id: "a", date: "2025-01-01", value: 339 }),
+ mclaim({ id: "b", date: "2025-01-01", population: "goal", value: 300 }),
+ ]);
+ assert.deepEqual(firedOn(t, "a"), []);
+ assert.deepEqual(firedOn(t, "b"), []);
+
+ // Two goals the same day still are a conflict — same form, same track, two
+ // answers.
+ const two = totalsOf([
+ mclaim({ id: "a", date: "2025-01-01", population: "goal", value: 300 }),
+ mclaim({ id: "b", date: "2025-01-01", population: "goal", value: 280 }),
+ ]);
+ assert.ok(firedOn(two, "b").includes("same_day_conflict"));
+});
+
+test("an `unresolved` scope feeds neither the line nor the band", () => {
+ const t = totalsOf([
+ mclaim({ id: "a", date: "2025-01-01", value: 340 }),
+ mclaim({ id: "b", date: "2025-02-01", value: 999, scopeConfidence: "unresolved" }),
+ ]);
+ assert.deepEqual(t.points.map((p) => p.id), ["a"]);
+ assert.deepEqual(t.unresolved, ["b"]);
+});
+
+test("a regime a track claims and the schema never declares is a loud error", () => {
+ const bad = {
+ ...TWO_TRACK,
+ tracks: [
+ TWO_TRACK.tracks[0],
+ { key: "drinking", role: "regime", regimes: ["dry", "sober", "tipsy"] },
+ ],
+ };
+ assert.throws(() => measureSchema(bad), /drinking/);
+ assert.throws(() => measureSchema(bad), /sober, tipsy/);
+ // …and a track that names none is not asked to, so no existing schema moves.
+ assert.doesNotThrow(() => measureSchema(SCHEMA));
+});
+
+test("each regime track gets its own band, and neither closes the other's", () => {
+ const led = [
+ reg({ id: "r1", date: "2025-02-01", scope: "regime", value: "keto", event: "start" }),
+ reg({ id: "d1", date: "2025-02-10", scope: "drinking", value: "dry", event: "start" }),
+ reg({ id: "d2", date: "2025-02-20", scope: "drinking", value: "drinking", event: "start" }),
+ reg({ id: "r2", date: "2025-03-01", scope: "regime", value: "keto", event: "on" }),
+ ];
+ const t = measureTotals(led, TWO_TRACK);
+
+ // The diet is ONE keto segment across the whole run. Flattened, the two
+ // drinking claims replaced it twice and it drew as three segments.
+ const diet = t.bands.regime.band;
+ assert.deepEqual(diet.map((b) => b.regime), ["keto"]);
+ assert.deepEqual(diet[0].ids, ["r1", "r2"]);
+
+ const drink = t.bands.drinking.band;
+ assert.deepEqual(drink.map((b) => b.regime), ["dry", "drinking"]);
+
+ // `totals.band` is still the FIRST regime track's, so nothing downstream had
+ // to learn a new field to keep drawing what it drew.
+ assert.deepEqual(t.band, diet);
+});
+
+test("the counter counts switches OF A TRACK, and the predicates read one track back", () => {
+ const led = [
+ reg({ id: "r1", date: "2025-02-01", scope: "regime", value: "keto", event: "start" }),
+ reg({ id: "d1", date: "2025-02-05", scope: "drinking", value: "dry", event: "start" }),
+ reg({ id: "r2", date: "2025-06-01", scope: "regime", value: "carnivore", event: "start" }),
+ ];
+ const t = measureTotals(led, TWO_TRACK);
+ assert.deepEqual(t.switchesByTrack, { regime: 1, drinking: 0 });
+ // `switches` is the first regime track's, which is what it has always been.
+ assert.equal(t.switches, 1);
+
+ // d1 starts a regime four days after keto started. Shared state made that a
+ // `regime_flip` (keto, four days ago, now Dry) and a `quit_unannounced`
+ // against keto — two findings about a claim that says nothing about food.
+ const d1 = t.steps.find((st) => st.id === "d1");
+ assert.deepEqual(d1.flags, []);
+ // …and carnivore in June still sees keto, four months back, as its own
+ // track's previous segment: not a flip, but nothing was ever said about
+ // stopping keto.
+ const r2 = t.steps.find((st) => st.id === "r2");
+ assert.deepEqual(r2.flags.map((f) => f.rule), ["quit_unannounced"]);
+ assert.equal(r2.flags[0].against, "r1");
+});
+
+test("broke_pledge: a drink two days after he says he has stopped", () => {
+ const f = flagOn(twoTotals(), "a1", "broke_pledge");
+ assert.ok(f, "a1 should break p1");
+ assert.equal(f.against, "p1");
+ assert.equal(f.days, 2);
+ assert.equal(f.text, "Dry on 2026-01-16, Drinking 2 days later");
+});
+
+test("broke_pledge fires once per pledge, not once per drink", () => {
+ // a2 is a week after a1 and the same pledge is behind both. Flagging it again
+ // would double every count the finale reads off the ledger.
+ assert.equal(flagOn(twoTotals(), "a2", "broke_pledge"), null);
+});
+
+test("broke_pledge stops at pledgeDays, and the schema says how many", () => {
+ // a3 is thirty-one days after p2 — one day outside the window.
+ assert.equal(flagOn(twoTotals(), "a3", "broke_pledge"), null);
+
+ // …and the window is read off the schema, not hardcoded. At 40 days it fires.
+ const wide = { ...TWO_FIX.ledgerSchema, pledgeDays: 40 };
+ const f = flagOn(totalsOf(TWO_FIX.ledger, wide), "a3", "broke_pledge");
+ assert.ok(f);
+ assert.equal(f.days, 31);
+});
+
+test("a pledge he called off out loud is not a pledge he broke", () => {
+ // p3 (cutting back) → s1 (he says the rule is over) → a4 (drinking again).
+ // Two weeks, well inside the window, and it is not a broken pledge: he said
+ // so first. This is the case that keeps the red mark worth anything.
+ const t = twoTotals();
+ assert.equal(flagOn(t, "a4", "broke_pledge"), null);
+ assert.equal(flagOn(t, "s1", "broke_pledge"), null);
+});
+
+test("broke_pledge suppresses the two generic names for the same event", () => {
+ // A drink after a pledge is mechanically also an unannounced quit and a flip.
+ // One event, one name — otherwise the inbox shows three findings about one
+ // drink and the operator adjudicates the same fact three times.
+ const t = twoTotals();
+ assert.deepEqual(firedOn(t, "a1"), ["broke_pledge"]);
+ // …and the suppression is scoped to the row that fires it. a3 is outside the
+ // window, so it keeps the generic finding it has always had.
+ assert.ok(firedOn(t, "a3").includes("quit_unannounced"));
+ assert.ok(!firedOn(t, "a3").includes("broke_pledge"));
+});
+
+test("no pledge row is flagged: the promise was not the lie", () => {
+ const t = twoTotals();
+ for (const id of ["p1", "p2", "p3"]) {
+ assert.equal(flagOn(t, id, "broke_pledge"), null, `${id} must not carry the flag`);
+ }
+});
+
+// The event semantics, which are the adjudication's own and were not the
+// walk's. `start` is an ACT — he makes the promise, he takes the drink. `on` is
+// a REPORT: "I'm nine days dry" is not a new pledge and "I was a four-days-a-
+// week drinker" is not a fresh drink taken against one.
+
+
+test("a recounted drink breaks nothing, and leaves the pledge standing", () => {
+ // The d030 case from the drinking adjudication: the pledge, a habitual claim
+ // the same day that the report explicitly rules "not a lapse", and the fresh
+ // drink ten days later that does break it. The middle row moves the board to
+ // Drinking, so the break has to fire on a row where the regime did NOT
+ // change — which is why the pledge ledger is kept outside that test.
+ const t = seq(
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-01-02", "drinking", "on"),
+ drinkRow("q3", "2026-01-11", "drinking", "start"),
+ );
+ assert.equal(flagOn(t, "q2", "broke_pledge"), null, "a recounted drink is not a lapse");
+ const f = flagOn(t, "q3", "broke_pledge");
+ assert.ok(f, "the fresh drink ten days later breaks it");
+ assert.equal(f.against, "q1");
+ assert.equal(f.days, 10);
+ // …and the generic names come back on the row that no longer takes the
+ // specific one. One event still has one name.
+ assert.ok(firedOn(t, "q2").includes("quit_unannounced"));
+ assert.deepEqual(firedOn(t, "q3"), ["broke_pledge"]);
+});
+
+test("a report that a pledge is holding is not a second pledge", () => {
+ // "I'm nine days dry" is `dry`/`on`. Counting it opened 122 pledges out of
+ // 27, and it would give a later drink something to break that he never
+ // promised twice.
+ const t = seq(
+ drinkRow("q1", "2026-01-01", "dry", "start"),
+ drinkRow("q2", "2026-01-10", "dry", "on"),
+ drinkRow("q3", "2026-02-20", "drinking", "start"),
+ );
+ assert.equal(measureScoreboard(t).final.pledges.count, 1);
+ // q3 is 50 days after the promise and 41 after the report: outside the window
+ // either way, and it must be measured from the PROMISE.
+ assert.equal(flagOn(t, "q3", "broke_pledge"), null);
+ const wide = { ...TWO_FIX.ledgerSchema, pledgeDays: 45 };
+ assert.equal(flagOn(totalsOf(
+ [drinkRow("q1", "2026-01-01", "dry", "start"),
+ drinkRow("q2", "2026-01-10", "dry", "on"),
+ drinkRow("q3", "2026-02-20", "drinking", "start")], wide), "q3", "broke_pledge"), null);
+});
+
+test("a report of drinking with no promise open opens nothing to break", () => {
+ const t = seq(
+ drinkRow("q1", "2026-01-01", "dry", "on"),
+ drinkRow("q2", "2026-01-05", "drinking", "start"),
+ );
+ assert.equal(measureScoreboard(t).final.pledges.count, 0);
+ assert.equal(flagOn(t, "q2", "broke_pledge"), null);
+});
+
+test("a lapse regime with no pledge anywhere is a schema error, by name", () => {
+ const bad = {
+ ...TWO_FIX.ledgerSchema,
+ regimes: TWO_FIX.ledgerSchema.regimes.map((r) =>
+ r.kind === "pledge" ? { key: r.key, label: r.label, color: r.color } : r,
+ ),
+ };
+ assert.throws(() => measureSchema(bad), /`drinking`.*`lapse`|lapse.*pledge/s);
+ // The message has to name the track, or nobody can find it in a schema with
+ // three of them.
+ try {
+ measureSchema(bad);
+ assert.fail("should have thrown");
+ } catch (err) {
+ assert.match(err.message, /drinking/);
+ }
+});
+
+test("a regime that declares no kind is neither, and nothing gains a flag", () => {
+ // Every shipped manifest is this one. The diet track's seven regimes carry no
+ // `kind`, so broke_pledge cannot fire on them however the dates fall.
+ const s = measureSchema(SAMPLE.ledgerSchema);
+ for (const r of s.regimes) assert.equal(r.kind, null);
+ assert.equal(s.pledgeDays, 30);
+ const t = totalsOf(SAMPLE.ledger);
+ assert.ok(!t.steps.some((st) => st.flags.some((f) => f.rule === "broke_pledge")));
+});
+
+test("the scoreboard's closing figures on the two-track fixture", () => {
+ const sb = measureScoreboard(twoTotals());
+ assert.equal(sb.final.pledges.count, 3);
+ assert.equal(sb.final.pledges.broken, 1);
+ assert.equal(sb.final.pledges.shortest.days, 2);
+ assert.equal(sb.final.pledges.shortest.pledge, "p1");
+ assert.equal(sb.final.pledges.shortest.lapse, "a1");
+ assert.equal(sb.final.goals.count, 2); // g1 (goal_loss) and g2 (goal)
+ assert.equal(sb.final.goals.last.id, "g2");
+ assert.equal(sb.final.diets.count, 1); // keto opens, carnivore replaces it
+ assert.equal(sb.final.net.delta, -28);
+ assert.equal(sb.final.net.unit, "lb");
+});
+
+test("the net spans the record, and both ends are the cell's own rule", () => {
+ // w3 is 305 on 2026-06-01. w4 says he WAS 312 on 2026-06-20 — a `past`, and
+ // the freshest thing the ledger holds.
+ //
+ // It used to be excluded, on the argument that mixing forms would put one
+ // number in the finale and a different one in the cell that had been on
+ // screen for fifteen minutes. That had it exactly backwards: the CURRENT cell
+ // is drawn by `freshestReading()`, which lets a `past` with a later `asOf`
+ // win, so the cell reads 312 and only the scoreboard said 305. One rule for
+ // both, and the rule is the one the viewer can see.
+ const sb = measureScoreboard(twoTotals());
+ assert.equal(sb.final.net.from, 340);
+ assert.equal(sb.final.net.fromAt, "2025-06-01");
+ assert.equal(sb.final.net.to, 312);
+ assert.equal(sb.final.net.toAt, "2026-06-20");
+ assert.equal(sb.running.at(-1).net, -28);
+});
+
+test("the net opens at the earliest reading, whatever form it took", () => {
+ // The old `from` was the earliest `current`, which on a man who spent years
+ // giving retrospectives and almost no contemporaneous figures is not the
+ // start of the record — on the diet manifest it read the last twelve months
+ // of an eight-year ledger. A `past` older than any `current` opens it now.
+ const rows = [
+ { id: "p0", date: "2025-07-01", asOf: "2024-01-01", scope: "weight",
+ population: "past", value: 400, display: "400 lb", plotted: true,
+ valueKind: "uttered", scopeConfidence: "read", scopeBasis: "said", flags: [],
+ hedged: false, unsourced: true, label: "400, remembered" },
+ ...JSON.parse(JSON.stringify(TWO_FIX.ledger)),
+ ];
+ const sb = measureScoreboard(totalsOf(rows, TWO_FIX.ledgerSchema));
+ assert.equal(sb.final.net.from, 400);
+ assert.equal(sb.final.net.fromAt, "2024-01-01");
+ assert.equal(sb.final.net.delta, -88);
+});
+
+test("the running figures are the closing ones, seen from partway", () => {
+ const sb = measureScoreboard(twoTotals());
+ const at = (id) => sb.running.find((r) => r.id === id);
+ // Before any drink: three pledges are not yet made, none is broken.
+ assert.equal(at("w1").pledges, 0);
+ assert.equal(at("w1").broken, 0);
+ assert.equal(at("w1").net, null); // one reading is not a net
+ // p1 is made, then broken two days later.
+ assert.equal(at("p1").pledges, 1);
+ assert.equal(at("p1").broken, 0);
+ assert.equal(at("a1").broken, 1);
+ // …and the last row of `running` is `final`, or the totals line and the
+ // scoreboard would disagree in the last second of the cut.
+ const last = sb.running.at(-1);
+ assert.equal(last.pledges, sb.final.pledges.count);
+ assert.equal(last.broken, sb.final.pledges.broken);
+ assert.equal(last.diets, sb.final.diets.count);
+ assert.equal(last.net, sb.final.net.delta);
+});
+
+test("the diet count is the ledger's switch counter, not a second walk of it", () => {
+ const t = twoTotals();
+ const sb = measureScoreboard(t);
+ assert.equal(sb.final.diets.count, t.switchesByTrack.regime);
+ assert.equal(sb.final.diets.track, "regime");
+});
+
+test("a ledger with no pledges scores zero rather than nothing", () => {
+ // The one-regime sample: no drinking track, no `kind` on anything.
+ const sb = measureScoreboard(totalsOf(SAMPLE.ledger));
+ assert.equal(sb.final.pledges.count, 0);
+ assert.equal(sb.final.pledges.broken, 0);
+ assert.equal(sb.final.pledges.shortest, null);
+ assert.equal(sb.final.diets.count, totalsOf(SAMPLE.ledger).switches);
+ assert.ok(sb.final.span.claims > 0);
+});
+
+test("an off label belongs to a track, and a shared one to the first", () => {
+ // The bug: one flat `offKey` put "No diet" — the diet track's word — in the
+ // DRINKING cell the moment he said he had stopped being dry.
+ const base = {
+ kind: "measure", unit: "lb",
+ tracks: [
+ { key: "weight", role: "value" },
+ { key: "regime", role: "regime", regimes: ["keto", "off"] },
+ { key: "drinking", role: "regime", regimes: ["dry", "drinking", "off"] },
+ ],
+ regimes: [
+ { key: "keto", label: "Keto" },
+ { key: "dry", label: "Dry", kind: "pledge" },
+ { key: "drinking", label: "Drinking", kind: "lapse" },
+ { key: "off", label: "No diet" },
+ ],
+ };
+ const offOf = (schema) =>
+ Object.fromEntries(measureSchema(schema).tracks.map((t) => [t.key, t.offKey]));
+
+ // Shared: the first regime track keeps it, the second gets nothing — the same
+ // convention `switches`, `band` and `final.regime` already keep.
+ assert.deepEqual(offOf(base), { weight: null, regime: "off", drinking: null });
+ // …and `offKey` stays schema-wide for the walk, which is about segments.
+ assert.equal(measureSchema(base).offKey, "off");
+
+ // Sole ownership needs nothing said outright: an off-shaped regime only one
+ // regime track declares is that track's.
+ const owned = JSON.parse(JSON.stringify(base));
+ owned.tracks[2].regimes = ["dry", "drinking", "off_drinking"];
+ owned.regimes.push({ key: "off_drinking", label: "Not saying" });
+ assert.deepEqual(offOf(owned), { weight: null, regime: "off", drinking: "off_drinking" });
+
+ // And a track may simply say so, which is how a manifest fixes this for good.
+ const named = JSON.parse(JSON.stringify(base));
+ named.tracks[2].offRegime = "off_drinking";
+ named.regimes.push({ key: "off_drinking", label: "Not saying" });
+ assert.deepEqual(offOf(named).drinking, "off_drinking");
+
+ // One regime track is the case every shipped manifest was: unchanged.
+ const one = JSON.parse(JSON.stringify(base));
+ one.tracks = one.tracks.slice(0, 2);
+ one.regimes = one.regimes.filter((r) => r.key !== "dry" && r.key !== "drinking");
+ assert.deepEqual(offOf(one), { weight: null, regime: "off" });
+});
+
+test("the bridge's peak is capped at the verdict's own gap", () => {
+ // The two walks pair the same lapse against different pledges: the hidden d1
+ // breaks p1 in the combined walk and consumes it, and the on-camera d2 then
+ // breaks p1 FOR the on-camera walk. Final gap zero, mid-walk difference +1 —
+ // and the running maximum used to carry that +1 to the last frame (the diet
+ // cut read 12 BROKEN against a ledger of 11; rev 6 shipped 17 against 16).
+ const S = {
+ ...TWO_TRACK,
+ pledgeDays: 30,
+ regimes: TWO_TRACK.regimes.map((r) =>
+ r.key === "dry" ? { ...r, kind: "pledge" } :
+ r.key === "drinking" ? { ...r, kind: "lapse" } : r),
+ };
+ const led = [
+ reg({ id: "p1", date: "2025-02-01", scope: "drinking", value: "dry", event: "start" }),
+ reg({ id: "d1", date: "2025-02-05", scope: "drinking", value: "drinking", event: "start" }),
+ reg({ id: "d2", date: "2025-02-10", scope: "drinking", value: "drinking", event: "start" }),
+ ];
+ const cam = new Set(["p1", "d2"]); // d1 has no clip
+ const split = measureScoreboardSplit(
+ totalsOf(led, S),
+ totalsOf(led.filter((c) => cam.has(c.id)), S),
+ );
+ assert.equal(split.combined.final.pledges.broken, 1, "the record breaks p1 once");
+ assert.equal(split.onCamera.final.pledges.broken, 1, "the camera also sees p1 break once");
+ const last = split.bridge[split.bridge.length - 1];
+ assert.equal(last.broken, 1, "the mid-walk peak must not ride to the verdict");
+ // …and capping it costs none of the monotonicity the maximum bought.
+ for (let i = 1; i < split.bridge.length; i += 1) {
+ assert.ok(split.bridge[i].broken >= split.bridge[i - 1].broken);
+ }
+});
+
+test("a manifest that declares no fields declares no fields", () => {
+ assert.deepEqual(ledgerFields({}), []);
+ assert.deepEqual(ledgerFields({ ledgerSchema: fieldSchema(undefined) }), []);
+ assert.deepEqual(claimVocab({}).fields, [], "and headcount has none either");
+ assert.deepEqual(measureSchema(fieldSchema([])).fields, []);
+});
+
+test("a declared field is normalised once, with its defaults filled in", () => {
+ const s = measureSchema(
+ fieldSchema([
+ { key: "gloss", label: "Gloss", kind: "text", render: "gloss" },
+ { key: "qualifier", kind: "enum", options: [">", "<", "≈"],
+ appliesTo: { scope: "weight" }, render: "cell" },
+ ]),
+ );
+ assert.deepEqual(s.fields.map((f) => f.key), ["gloss", "qualifier"]);
+ const [gloss, qual] = s.fields;
+ assert.equal(gloss.maxLength, 200, "a text field gets the default cap");
+ assert.equal(gloss.render, "gloss");
+ assert.equal(qual.label, "qualifier", "the key is the label when none is given");
+ assert.equal(qual.maxLength, null, "…and only text has one");
+ assert.deepEqual(qual.appliesTo, { scope: "weight" });
+ // One vocabulary, read by the bench and by the gate alike.
+ assert.deepEqual(
+ claimVocab({ ledgerSchema: fieldSchema(s.fields) }).fields.map((f) => f.key),
+ ["gloss", "qualifier"],
+ );
+});
+
+test("the four ways a fields[] declaration is wrong are all loud", () => {
+ assert.throws(() => measureSchema(fieldSchema([{ key: "x", kind: "colour" }])),
+ /field `x` has kind `colour`/);
+ assert.throws(() => measureSchema(fieldSchema([{ key: "x", kind: "enum" }])),
+ /enum field `x` declares no `options`/);
+ assert.throws(
+ () => measureSchema(fieldSchema([{ key: "x", kind: "text" }, { key: "x", kind: "text" }])),
+ /two `fields` entries declare `x`/,
+ );
+ // A field named after a built-in would be a second, differently-validated
+ // door onto a key the code already means.
+ assert.throws(() => measureSchema(fieldSchema([{ key: "display", kind: "text" }])),
+ /`display`, which is a built-in row key/);
+ assert.throws(() => measureSchema(fieldSchema([{ key: "x", kind: "text", render: "banner" }])),
+ /field `x` renders as `banner`/);
+ assert.throws(() => measureSchema(fieldSchema([{ kind: "text" }])), /has no `key`/);
+});
+
+test("every built-in a row carries is in LEDGER_BUILTIN_KEYS", () => {
+ // The gate `umtool check` reads: a key in neither this set nor `fields[]`
+ // is adjudication work nothing will ever read.
+ for (const k of Object.keys(TWO_FIX.ledger[0])) {
+ assert.ok(LEDGER_BUILTIN_KEYS.has(k), `${k} is a fixture row key and must be declared`);
+ }
+ for (const k of ["scopeBasis", "flags", "entryId", "hedged", "citeFrom", "unsourced"]) {
+ assert.ok(LEDGER_BUILTIN_KEYS.has(k));
+ }
+ assert.equal(LEDGER_BUILTIN_KEYS.has("gloss"), false, "…and a declared field is not one");
+});
+
+test("validateFields rules on one kind at a time, and clears on empty", () => {
+ const s = fieldSchema([
+ { key: "gloss", kind: "text", maxLength: 12 },
+ { key: "qualifier", kind: "enum", options: [">", "<"] },
+ { key: "weighed", kind: "number", min: 0, max: 500 },
+ { key: "guessed", kind: "bool" },
+ { key: "at", kind: "seconds" },
+ { key: "breaks", kind: "rowRef" },
+ ]);
+ const ledger = [{ id: "a1" }, { id: "p1" }];
+ const row = { id: "a1", scope: "weight" };
+ const ok = (patch) => validateFields(row, patch, s, ledger);
+ assert.deepEqual(ok({ gloss: " his own " }), { set: { gloss: "his own" }, clear: [] });
+ assert.deepEqual(ok({ qualifier: ">" }).set, { qualifier: ">" });
+ assert.deepEqual(ok({ weighed: "351" }).set, { weighed: 351 }, "a number arrives as text");
+ assert.deepEqual(ok({ guessed: true }).set, { guessed: true });
+ assert.deepEqual(ok({ at: 0 }).set, { at: 0 });
+ assert.deepEqual(ok({ breaks: "p1" }).set, { breaks: "p1" });
+ // Empty CLEARS, for every kind: a field an operator has emptied is one they
+ // are saying nothing about.
+ assert.deepEqual(ok({ gloss: "" }), { set: {}, clear: ["gloss"] });
+ assert.deepEqual(ok({ gloss: " " }), { set: {}, clear: ["gloss"] });
+ assert.deepEqual(ok({ qualifier: null }), { set: {}, clear: ["qualifier"] });
+ // …and a key the schema does not declare is not this function's business.
+ assert.deepEqual(ok({ display: "over 300 lb" }), { set: {}, clear: [] });
+ // Every violation, by name.
+ assert.throws(() => ok({ gloss: "far too long to fit" }), /19 characters, and 12 is the most/);
+ assert.throws(() => ok({ qualifier: "~" }), /`~` is not one of > </);
+ assert.throws(() => ok({ weighed: "heavy" }), /must be a number/);
+ assert.throws(() => ok({ weighed: 900 }), /900 is above 500/);
+ assert.throws(() => ok({ at: -1 }), /-1 is before the start of the clip/);
+ // "false" is a truthy string and a bug, never a value.
+ assert.throws(() => ok({ guessed: "false" }), /must be true or false, not a string/);
+ assert.throws(() => ok({ breaks: "a1" }), /a row cannot refer to itself/);
+ assert.throws(() => ok({ breaks: "nope" }), /no ledger row has the id `nope`/);
+});
+
+test("appliesTo refuses a field on a row that cannot carry it", () => {
+ const s = fieldSchema([
+ { key: "breaks", kind: "rowRef",
+ appliesTo: { scope: "drinking", value: "drinking", event: "start" } },
+ { key: "qualifier", kind: "enum", options: [">"], appliesTo: { role: "value" } },
+ ]);
+ const ledger = [{ id: "p1" }, { id: "a1" }];
+ const lapse = { id: "a1", scope: "drinking", value: "drinking", event: "start" };
+ const reading = { id: "w1", scope: "weight", population: "current" };
+ assert.deepEqual(validateFields(lapse, { breaks: "p1" }, s, ledger).set, { breaks: "p1" });
+ assert.deepEqual(validateFields(reading, { qualifier: ">" }, s, ledger).set, { qualifier: ">" });
+ assert.throws(
+ () => validateFields(reading, { breaks: "p1" }, s, ledger),
+ /this row does not carry it — scope must be drinking, value must be drinking, event must be start/,
+ );
+ assert.throws(() => validateFields(lapse, { qualifier: ">" }, s, ledger), /role must be value/);
+ // The PATCH is what is judged, not the row as it stands: an edit that makes
+ // the row eligible in the same save is a legal edit.
+ assert.deepEqual(
+ validateFields({ id: "a1", scope: "drinking", value: "dry", event: "start" },
+ { value: "drinking", breaks: "p1" }, s, ledger).set,
+ { breaks: "p1" },
+ );
+ // …and clearing is always allowed, whatever the row says now.
+ assert.deepEqual(validateFields(reading, { breaks: "" }, s, ledger), { set: {}, clear: ["breaks"] });
+ const [breaks] = measureSchema(s).fields;
+ assert.equal(fieldApplies(breaks, lapse, s), true);
+ assert.equal(fieldApplies(breaks, reading, s), false);
+});
+
+test("both shapes of a promise are a promise", () => {
+ assert.deepEqual(REGIME_KINDS, ["pledge", "bounded", "lapse"]);
+ assert.equal(isPledgeKind("pledge"), true);
+ assert.equal(isPledgeKind("bounded"), true);
+ assert.equal(isPledgeKind("lapse"), false);
+ assert.equal(isPledgeKind(null), false);
+ const s = measureSchema(BOUNDED_SCHEMA);
+ assert.equal(s.regimes.find((r) => r.key === "cutting").kind, "bounded");
+ assert.equal(s.regimes.find((r) => r.key === "dry").kind, "pledge");
+ // A track carrying a lapse and only a BOUNDED promise is a legal track: the
+ // cross-check is about whether a lapse has anything to lapse from.
+ assert.doesNotThrow(() =>
+ measureSchema({
+ kind: "measure",
+ tracks: [{ key: "d", role: "regime", regimes: ["cut", "drink"] }],
+ regimes: [{ key: "cut", kind: "bounded" }, { key: "drink", kind: "lapse" }],
+ }),
+ );
+});
+
+test("an unmarked drink does not break a bounded pledge, and does not close it", () => {
+ // THE RISK THIS RULE EXISTS FOR. He bounds his drinking; he drinks, inside
+ // the bound, which is what a bound is FOR; and a fortnight later he drinks in
+ // a way the adjudicator says violates it. Closing the pledge on the first
+ // drink leaves the second one with nothing to break.
+ const rows = [
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-01-05", "drinking", "start"),
+ drinkRow("q3", "2026-01-19", "drinking", "start"),
+ ];
+ rows[2].breaks = "q1";
+ rows[2].breaksWhy = "four nights running, against two a week";
+ const t = bounded(...rows);
+ assert.equal(flagOn(t, "q2", "broke_pledge"), null, "the unmarked drink breaks nothing");
+ const f = flagOn(t, "q3", "broke_pledge");
+ assert.ok(f, "the marked one breaks the pledge that was still open");
+ assert.equal(f.against, "q1");
+ assert.equal(f.days, 18);
+ assert.equal(f.explicit, true);
+ // …and the same three rows against a plain pledge are the old rule exactly:
+ // the FIRST drink breaks it and the marked one is a week too late to matter.
+ const plain = totalsOf(rows, TWO_FIX.ledgerSchema);
+ assert.equal(flagOn(plain, "q2", "broke_pledge").against, "q1");
+ assert.equal(flagOn(plain, "q3", "broke_pledge"), null);
+});
+
+test("a bounded pledge nobody marks is never broken", () => {
+ const t = bounded(
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-01-05", "drinking", "start"),
+ drinkRow("q3", "2026-01-09", "drinking", "start"),
+ );
+ for (const id of ["q2", "q3"]) assert.equal(flagOn(t, id, "broke_pledge"), null);
+ assert.equal(measureScoreboard(t).final.pledges.broken, 0);
+ // It still counts as a promise — the board says he made one and did not
+ // break it, which is a statement the ledger has actually made.
+ assert.equal(measureScoreboard(t).final.pledges.count, 1);
+});
+
+test("a marked break is not subject to the window", () => {
+ // The window stands in for "these two claims are about each other"; the mark
+ // is the adjudicator saying so outright, and a proxy does not overrule the
+ // thing it stands in for.
+ const rows = [
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-04-01", "drinking", "start"),
+ ];
+ rows[1].breaks = "q1";
+ const f = flagOn(bounded(...rows), "q2", "broke_pledge");
+ assert.ok(f, "ninety days later, and named");
+ assert.equal(f.days, 90);
+ assert.equal(f.explicit, true);
+});
+
+test("a bounded pledge nobody names goes quiet after pledgeDays", () => {
+ // Finite, or it collects lapses years after he stopped talking about it.
+ const t = bounded(
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-04-01", "drinking", "start"),
+ drinkRow("q3", "2026-04-02", "dry", "start"),
+ drinkRow("q4", "2026-04-05", "drinking", "start"),
+ );
+ assert.equal(flagOn(t, "q2", "broke_pledge"), null, "the bound has run out");
+ // …and the plain pledge that follows it breaks on the window, as it always
+ // has: the two rules live side by side on one track.
+ const f = flagOn(t, "q4", "broke_pledge");
+ assert.ok(f);
+ assert.equal(f.against, "q3");
+ assert.equal(f.explicit, false);
+});
+
+test("a breaks reference that names no open pledge marks nothing", () => {
+ const rows = [
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-01-10", "cutting", "start"),
+ drinkRow("q3", "2026-01-15", "drinking", "start"),
+ ];
+ // q1 was replaced by q2 nine days later; naming it is an adjudication error
+ // and must not reach back past the promise he is actually under.
+ rows[2].breaks = "q1";
+ const t = bounded(...rows);
+ assert.equal(flagOn(t, "q3", "broke_pledge"), null);
+ assert.equal(measureScoreboard(t).final.pledges.count, 2, "both promises still count");
+});
+
+test("PLEDGES counts the bounded ones too", () => {
+ const rows = [
+ drinkRow("q1", "2026-01-01", "dry", "start"),
+ drinkRow("q2", "2026-03-01", "cutting", "start"),
+ drinkRow("q3", "2026-05-01", "cutting", "on"),
+ ];
+ // Under the plain schema `cutting` is already a pledge, so the count is the
+ // same two either way — which is the point: bounding a promise changes how it
+ // BREAKS and nothing else about it.
+ assert.equal(measureScoreboard(bounded(...rows)).final.pledges.count, 2);
+ assert.equal(measureScoreboard(totalsOf(rows, TWO_FIX.ledgerSchema)).final.pledges.count, 2);
+ // A report is still not a promise, under either kind.
+ assert.equal(flagOn(bounded(...rows), "q3", "broke_pledge"), null);
+});
+
+test("a pledge he called off out loud is not a bounded pledge he broke either", () => {
+ const rows = [
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-01-05", "cutting", "stop"),
+ drinkRow("q3", "2026-01-08", "drinking", "start"),
+ ];
+ rows[2].breaks = "q1";
+ assert.equal(flagOn(bounded(...rows), "q3", "broke_pledge"), null);
+});
+
+test("the walk carries the breaks reference onto the step", () => {
+ const rows = [
+ drinkRow("q1", "2026-01-01", "cutting", "start"),
+ drinkRow("q2", "2026-01-10", "drinking", "start"),
+ ];
+ rows[1].breaks = "q1";
+ const t = bounded(...rows);
+ assert.equal(t.steps.find((s) => s.id === "q2").breaks, "q1");
+ assert.equal(t.steps.find((s) => s.id === "q1").breaks, null);
+});
+
+test("a bound prefixes the figure and nothing else changes", () => {
+ const m = JSON.parse(JSON.stringify(TWO_FIX));
+ m.ledgerSchema.fields = [
+ { key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "\u2248"],
+ appliesTo: { scope: "weight" }, render: "cell" },
+ ];
+ for (const c of m.ledger) if (c.id === "w2") c.qualifier = ">";
+ const w2 = m.ledger.find((c) => c.id === "w2");
+ assert.equal(w2.qualifier, ">");
+ assert.equal(measureDisplay({ ...w2, display: null }, m.ledgerSchema), ">317 lb");
+ // HIS OWN WORDS still win the wording; the bound is added in front of them.
+ assert.equal(measureDisplay(w2, m.ledgerSchema), ">317 lb");
+ // Idempotent, so a display an operator has already written survives a
+ // value correction without the glyph coming back twice.
+ assert.equal(measureDisplay({ ...w2, display: ">317 lb" }, m.ledgerSchema), ">317 lb");
+ // …and the NUMBER is untouched, everywhere it is used.
+ const totals = totalsOf(m.ledger, m.ledgerSchema);
+ const pt = totals.points.find((p) => p.id === "w2");
+ assert.equal(pt.value, 317);
+ assert.equal(pt.display, ">317 lb");
+ // A schema that declares no such field leaves the display alone.
+ const bare = { ...m.ledgerSchema, fields: [] };
+ assert.equal(measureDisplay({ ...w2, display: null }, bare), "317 lb");
+});
+
+test("offCloses: an off closes the regime it names, nothing else", () => {
+ assert.equal(offCloses(null, "glp1", "off"), true); // nothing open: off is the reading
+ assert.equal(offCloses("off", "glp1", "off"), true); // already off: stays off
+ assert.equal(offCloses("keto", "keto", "off"), true); // off what is open: closes it
+ assert.equal(offCloses("keto", "glp1", "off"), false); // off something else: keto stands
+ assert.equal(offCloses("keto", "carnivore", null), false);
+});
+
+test("an off for a regime that is not open neither switches the diet nor ends the band", () => {
+ const m = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-two-track.manifest.json"), "utf8"));
+ const keto = m.ledger.find((r) => r.id === "r1");
+ const base = m.ledger.filter((r) => r.scope === "regime" && r.id === "r1");
+ const offOther = { ...keto, id: "rx", date: "2025-07-01", value: "carnivore", event: "off",
+ display: "off Carnivore", label: "not carnivore", quote: "not doing carnivore", entryId: undefined };
+ const offSame = { ...offOther, id: "ry", value: "keto", display: "off Keto" };
+ const diets = (ledger) => measureScoreboard(measureTotals(ledger, m.ledgerSchema)).final.diets.count;
+ const bandOf = (ledger) => measureTotals(ledger, m.ledgerSchema).band.filter((b) => !b.unknown).map((b) => b.regime);
+ assert.equal(diets([...base, offOther]), diets(base), "off carnivore on keto is not a change of diet");
+ assert.deepEqual(bandOf([...base, offOther]), bandOf(base).length ? bandOf(base) : ["keto"]);
+ assert.ok(!bandOf([...base, offOther]).includes("off"), "keto's band is not cut to off");
+ assert.equal(diets([...base, offSame]), diets(base) + 1, "off keto on keto still is one");
+ const ketoEnd = (ledger) => measureTotals(ledger, m.ledgerSchema).band.find((b) => b.regime === "keto")?.reason;
+ assert.equal(ketoEnd([...base, offSame]), "stopped", "off keto ends keto's band");
+ assert.notEqual(ketoEnd([...base, offOther]), "stopped", "off carnivore does not");
+});
diff --git a/umtool/report-to-video/measure-words.mjs b/umtool/report-to-video/measure-words.mjs
@@ -0,0 +1,67 @@
+// The words a measure slice times its rows by (measure-slice.mjs): for each
+// clip of the cut that shows a measure row, its words in SOURCE seconds and
+// where they came from. Reads only. Plain ESM.
+//
+// The first of, per channels tree given (the project's own first -- its
+// `provenance.channelsDir` or `.shadow-channels/` -- then the corpus):
+//
+// timed words clip-words.mjs clipWords: the word-timings sidecar, a
+// whisper transcript's tokens, or the English caption track's
+// word starts -> "words"
+// the cues the cue record (`transcript.cues.json`), or the build's own
+// cue reader (`cues(entry)`), each cue's words spread over it
+// by their characters (fx.mjs fxWordsOf) -- an ESTIMATE, a
+// second or so either way -> "cues"
+//
+// A clip with neither lands on its quoteStart (the slice's fallback).
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { clipWords } from "./clip-words.mjs";
+import { fxWordsOf } from "./fx.mjs";
+import { hasLocalMedia } from "./local-media.mjs";
+
+/**
+ * @param {{ entries: object[], ids: Set<string>, provenance?: object,
+ * channelsDirs?: Array<string|null>, cues?: ((entry: object) => Promise<Array<{ start: number, end: number, text: string }>>) | null }} a
+ * `ids` the entries that show a measure row.
+ * @returns {Promise<Map<string, { words: Array<{ text: string, start: number, end: number }>, from: string }>>}
+ */
+export async function measureClipWords({ entries, ids, provenance = {}, channelsDirs = [], cues = null }) {
+ const out = new Map();
+ const dirs = [...new Set(channelsDirs.filter(Boolean))];
+ for (const e of entries) {
+ if (e?.type !== "clip" || !ids.has(e.id) || !Number.isFinite(e.start) || !Number.isFinite(e.end)) continue;
+ let got = null;
+ for (const dir of dirs) {
+ const w = await clipWords(e, provenance, e.start - 1, e.end + 1, { channelsDir: dir }).catch(() => null);
+ if (w?.words?.length) { got = { words: w.words.map((x) => ({ text: x.text, start: x.start, end: x.end ?? x.start })), from: "words" }; break; }
+ }
+ if (!got && !hasLocalMedia(e)) {
+ for (const dir of dirs) {
+ const spans = await cueFile(dir, e.channel ?? provenance.channelSlug, e.video);
+ const words = spans ? fxWordsOf(spans, e.start - 1, e.end + 1) : [];
+ if (words.length) { got = { words, from: "cues" }; break; }
+ }
+ }
+ if (!got && cues) {
+ const spans = await cues(e).catch(() => []);
+ const words = fxWordsOf(spans ?? [], e.start - 1, e.end + 1);
+ if (words.length) got = { words, from: "cues" };
+ }
+ if (got) out.set(e.id, got);
+ }
+ return out;
+}
+
+/** A video's cue record in a channels tree, or null. */
+async function cueFile(channelsDir, slug, video) {
+ if (!channelsDir || !slug || !video) return null;
+ try {
+ const dir = await resolveVideoDir(channelsDir, slug, video);
+ const doc = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8"));
+ return Array.isArray(doc?.cues) ? doc.cues : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs
@@ -133,6 +133,8 @@ export function scheduleSlices(doc) {
...(doc.flips ? { flips: doc.flips } : {}),
...(doc.stats ? { stats: doc.stats } : {}),
...(doc.fx ? { fx: doc.fx } : {}),
+ // The measure ledger's slice (measure-slice.mjs): every instrument module
+ // (dial, odometer, trail, goals, peak, promise, diet) reads it whole.
...(doc.measure ? { measure: doc.measure } : {}),
};
return out;
diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs
@@ -47,5 +47,5 @@ test("rail settings: spacing, pitch, and the deck's other keys refused by name",
assert.equal(resolveDeck(render({})).pip.pitch, undefined, "no pitch unless set: the deck resolves as it did");
assert.equal(rail.resolve(render({ spacing: "pitch" })).pip.pitch, 28);
assert.equal(rail.validate, settingsOf("rail").validate);
- assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts", "dial", "odometer", "trail"]);
+ assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "measure", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts", "dial", "odometer", "trail"]);
});
diff --git a/umtool/report-to-video/modules/settings.mjs b/umtool/report-to-video/modules/settings.mjs
@@ -20,6 +20,7 @@ import { validateChat } from "../chat.mjs";
import { validateChapter, validatePair, validateStatus } from "./story-settings.mjs";
import { MARKER_LEVELS, MARKER_LIMITS } from "../marker-limits.mjs";
import { validateDial, validateOdometer, validateTrail } from "../instruments.mjs";
+import { validateMeasureSettings } from "../measure-slice.mjs";
/**
* Every deck setting and its default. A manifest names only what it changes;
@@ -468,6 +469,9 @@ export const SETTINGS = Object.freeze([
validate: (v, { where }) => validateFinaleSettings(v, `${where}.finale`) },
{ id: "claims", key: "deck.claims", configKey: "render.chrome.deck.claims", deck: true,
validate: (v, { where }) => deckClaimShapeErrors(v, `${where}.claims`) },
+ // The measure ledger's slice (measure-slice.mjs), which the instruments draw from.
+ { id: "measure", key: "deck.measure", configKey: "render.chrome.deck.measure", deck: true,
+ validate: (v, { where }) => validateMeasureSettings(v, `${where}.measure`) },
{ id: "counter", key: "deck.counter", configKey: "render.chrome.deck.counter", deck: true,
validate: (v, { chrome, render }) => validateCounter(v, {
factcheck: chrome.factcheck, labelFits: (s, where) => counterLabelProblem(s, where, { fontBold: render.fontBold ?? null }),
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -48,6 +48,8 @@
"./gaps": "./gaps.mjs",
"./ladder-chunks": "./ladder-chunks.mjs",
"./ledger-totals": "./ledger-totals.mjs",
+ "./measure-slice": "./measure-slice.mjs",
+ "./measure-words": "./measure-words.mjs",
"./montage": "./montage.mjs",
"./montage-styles": "./montage-styles.mjs",
"./montage-rulings": "./montage-rulings.mjs",
diff --git a/umtool/report-to-video/panel-model.mjs b/umtool/report-to-video/panel-model.mjs
@@ -0,0 +1,106 @@
+// The measure panel's CELLS, as data: what each cell says after a row. No
+// HTML, no I/O, no browser.
+//
+// Ported from the diet-series branch's panel-model.mjs (scripts/report-to-video
+// there), which modelled the whole table panel -- geometry, row heights, the
+// log, the finale's two rolls. Only its cell rules are wanted on main: the
+// instrument modules (dial, odometer, goals, diet badge …) draw from ONE
+// slice (measure-slice.mjs), and the slice's per-event state is these rules
+// applied in the cut's order. The table panel's drawing is not ported.
+//
+// The three rules, each the branch's own:
+//
+// reading freshestReading(): a `current` always wins; a `past` wins only
+// when nothing is on the board or its asOf is LATER than what is.
+// goal goalAbsolute(): a `goal_loss` is a weight only against a reading
+// (the board's, else nothing) -- never one invented from nothing.
+// regime an opening row (start/on) puts its regime -- in HIS words, the
+// row's display -- in the cell; a closing one (stop/off) hands the
+// cell to THIS track's off regime, and only when it names what is
+// open (offCloses: "off GLP-1" said three weeks into keto leaves
+// Keto in the cell; the off-scope fix, eff32c8d).
+import { freshestReading, goalAbsolute, measureDisplay, measureQualifier, measureSchema, offCloses, plotDate } from "./measure-totals.mjs";
+
+/** The events that OPEN or sustain a regime segment, against those that close. */
+export const OPENING = new Set(["start", "on"]);
+export const CLOSING = new Set(["stop", "off"]);
+
+/** A regime of the schema, by key, or null. */
+export function regimeOf(schema, key) {
+ const s = measureSchema(schema);
+ return s.regimes.find((r) => r.key === key) ?? null;
+}
+
+/** The regime a `stop`/`off` on THIS track hands over to, or null for none. */
+export function offOf(schema, trackKey) {
+ const s = measureSchema(schema);
+ const k = s.tracks.find((t) => t.key === trackKey)?.offKey ?? null;
+ return k ? regimeOf(s, k) : null;
+}
+
+/**
+ * The reading cell after `row`: `prev` (or null) unless the row is the
+ * freshest reading of its track by the board's rule.
+ *
+ * @returns {{ value: number, at: string|null, display: string, qualifier: string|null, row: string } | null}
+ */
+export function nextReading(prev, row, schema) {
+ const at = plotDate(row);
+ if (!freshestReading(row, at, prev)) return prev;
+ return {
+ value: Number(row.value),
+ at,
+ display: measureDisplay(row, schema),
+ qualifier: measureQualifier(row, schema),
+ row: row.id,
+ };
+}
+
+/**
+ * A goal row as the cell holds it: a weight when it is one (a `goal`, or a
+ * `goal_loss` against `base`, a reading `{ value }`), else his words.
+ *
+ * @returns {{ value: number|null, loss: number|null, display: string, deadline: string|null, row: string }}
+ */
+export function goalCell(row, base, schema) {
+ const s = measureSchema(schema);
+ const abs = goalAbsolute(row, base);
+ const loss = row.population === "goal_loss" && Number.isFinite(Number(row.value)) ? Math.abs(Number(row.value)) : null;
+ return {
+ value: Number.isFinite(abs) ? abs : null,
+ loss,
+ display: Number.isFinite(abs) ? `${abs}${s.unit ? ` ${s.unit}` : ""}` : measureDisplay(row, s),
+ deadline: row.deadline ?? null,
+ row: row.id,
+ };
+}
+
+/**
+ * The regime cell of `row`'s track after it: `{ key, label, display, at,
+ * since, row }`, the off regime's word after a close that closes (null when
+ * the track has none), or `open` unchanged (a row that is not a regime claim,
+ * or an off for a regime that is not the one open).
+ *
+ * `display` is HIS words for it (the opening row's display), refreshed on
+ * every opening row, `on` included: a report that the rule is holding is the
+ * freshest thing he has said about what the rule is. `since` is when the
+ * regime in the cell opened: an `on` for the open regime keeps it, a `start` opens it again.
+ */
+export function nextRegime(open, row, schema) {
+ const s = measureSchema(schema);
+ const R = regimeOf(s, row?.value);
+ if (!R) return open;
+ const at = plotDate(row);
+ if (OPENING.has(row.event)) {
+ // `on` is a report that the rule holds: it keeps when the regime opened.
+ // `start` is the act -- a fresh start of the same regime opens it again.
+ const same = open && open.key === R.key && row.event === "on";
+ return { key: R.key, label: R.label, display: measureDisplay(row, s), at, since: same ? open.since : at, row: row.id };
+ }
+ if (CLOSING.has(row.event)) {
+ const off = offOf(s, row.scope);
+ if (!offCloses(open?.key ?? null, R.key, off?.key ?? null)) return open;
+ return off ? { key: off.key, label: off.label, display: off.label, at, since: at, row: row.id } : null;
+ }
+ return open;
+}
diff --git a/umtool/report-to-video/panel-model.test.mjs b/umtool/report-to-video/panel-model.test.mjs
@@ -0,0 +1,55 @@
+// Tests for panel-model.mjs: the measure cells' three rules. Run with:
+// pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { goalCell, nextReading, nextRegime, offOf, regimeOf } from "./panel-model.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const TWO = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-two-track.manifest.json"), "utf8"));
+const S = TWO.ledgerSchema;
+const row = (o) => ({ scope: "regime", population: "status", ...o });
+
+test("an off closes the regime it names, and nothing else (the off-scope fix)", () => {
+ const keto = nextRegime(null, row({ id: "r1", date: "2025-07-20", value: "keto", event: "start" }), S);
+ assert.equal(keto.key, "keto");
+ // "off carnivore" three weeks into keto: keto stands.
+ const still = nextRegime(keto, row({ id: "r2", date: "2025-08-10", value: "carnivore", event: "off" }), S);
+ assert.equal(still, keto);
+ // "off keto": the track's own off word takes the cell.
+ const off = nextRegime(keto, row({ id: "r3", date: "2025-09-01", value: "keto", event: "off" }), S);
+ assert.equal(off.key, offOf(S, "regime").key);
+ assert.equal(off.since, "2025-09-01");
+});
+
+test("the regime cell is in his words, and an `on` keeps when it opened", () => {
+ const a = nextRegime(null, row({ id: "r1", date: "2025-07-20", value: "keto", event: "start", display: "keto · no carbs" }), S);
+ const b = nextRegime(a, row({ id: "r2", date: "2025-08-06", value: "keto", event: "on", display: "Keto · 5 carbs a day" }), S);
+ assert.equal(b.display, "Keto · 5 carbs a day");
+ assert.equal(b.since, "2025-07-20");
+ assert.equal(b.row, "r2");
+ // A row that is no regime leaves the cell alone.
+ assert.equal(nextRegime(b, { id: "w1", scope: "weight", population: "current", value: 300 }, S), b);
+ assert.equal(regimeOf(S, "nope"), null);
+});
+
+test("a retrospective is the reading only when it is later than the board's", () => {
+ const cur = nextReading(null, { id: "w1", scope: "weight", population: "current", date: "2025-03-01", value: 340 }, S);
+ assert.equal(cur.value, 340);
+ const older = nextReading(cur, { id: "w2", scope: "weight", population: "past", date: "2025-04-01", asOf: "2024-01-01", value: 390 }, S);
+ assert.equal(older, cur);
+ const newer = nextReading(cur, { id: "w3", scope: "weight", population: "past", date: "2025-04-01", asOf: "2025-03-20", value: 335 }, S);
+ assert.equal(newer.value, 335);
+});
+
+test("a goal_loss is a weight only against a reading", () => {
+ const g = { id: "g1", scope: "weight", population: "goal_loss", value: -65, deadline: "by Christmas" };
+ assert.deepEqual(goalCell(g, { value: 349 }, S), { value: 284, loss: 65, display: "284 lb", deadline: "by Christmas", row: "g1" });
+ const words = goalCell(g, null, S);
+ assert.equal(words.value, null);
+ assert.equal(words.loss, 65);
+ assert.equal(goalCell({ id: "g2", scope: "weight", population: "goal", value: 250 }, null, S).value, 250);
+});