Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 3c5c912979d38c5b305354262d7b6db9c94c9289
parent 5c25855eff043b174bc31dc8b8c616c5b12260f8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 22:58:29 -0500

measure: port the diet-series measure data layer onto main

measure-totals.mjs and ledger-shared.mjs from diet-series-off-scope (the
branch tip, so offCloses -- an off closes the regime it names, and nothing
else, eff32c8d -- comes with them), unchanged. ledger-totals.mjs takes the
branch's dispatch: ledgerKind / ledgerSchemaOf / claimVocab / ledgerFields,
and adjudicationGaps / unadjudicatedOf / ledgerTotals branch to the measure
arithmetic when handed a manifest or schema whose ledgerSchema.kind is
"measure". With neither, every function is the headcount walk it was (its
tests unchanged and green).

panel-model.mjs is only the branch panel's CELL rules -- freshestReading,
goalAbsolute, and the regime cell with the off-scope fix -- for the measure
slice; the table panel's geometry, log and finale are not ported.

measure-totals.test.mjs carries the branch's 58 data-layer tests (the rail,
panel and chart drawing tests are not ported), with the two fixtures they
read.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/report-to-video/fixtures/measure-sample.manifest.json | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/fixtures/measure-two-track.manifest.json | 489+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/ledger-shared.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/ledger-totals.mjs | 176++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Aumtool/report-to-video/measure-totals.mjs | 1608+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/measure-totals.test.mjs | 1075+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/panel-model.mjs | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/panel-model.test.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 3744 insertions(+), 38 deletions(-)

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,97 @@ +// 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", +]); diff --git a/umtool/report-to-video/ledger-totals.mjs b/umtool/report-to-video/ledger-totals.mjs @@ -28,12 +28,124 @@ // 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, + allRegimeGaps, + freshestReading, + goalAbsolute, + measureDisplay, + 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 +157,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 +178,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 +205,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 +380,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 +390,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-totals.mjs b/umtool/report-to-video/measure-totals.mjs @@ -0,0 +1,1608 @@ +// 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 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, + forms: s.forms?.length ? s.forms.map(String) : DEFAULT_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,1075 @@ +// 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"]); + assert.deepEqual(v.populations, ["current", "past", "delta", "goal", "overweight_by", "status"]); + 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/panel-model.mjs b/umtool/report-to-video/panel-model.mjs @@ -0,0 +1,104 @@ +// 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). + */ +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)) { + const same = open && open.key === R.key; + 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); +});