// The MEASURE ledger kind: one quantity over time, plus what regime he says he // is on while it moves. // // --------------------------------------------------------------------------- // Why a second kind rather than a second manifest field // --------------------------------------------------------------------------- // The headcount ledger (ledger-totals.mjs) answers "how many people work for // him", and every part of it -- four named companies, a sum-of-payrolls, a // population baseline -- is about a count that is the sum of its parts. A weight // is not. There is one number, it is nobody's sum, and the interesting thing // beside it is not another number but a WORD: what he says he is doing about it. // // So `measure` keeps the ledger's SHAPE (one dated claim per row, the same six // adjudication fields, the same "our number vs his number" discipline) and // replaces the arithmetic: // // scope which TRACK the claim feeds -- a value track or a regime track // population the claim's FORM -- current / past / delta / goal / … // value a number in the schema's unit, or a regime key // event start | on | stop | off, for regime claims only // asOf the date the claim is ABOUT, when that is not the date he said it // // `asOf` is the one genuinely new field and it earns its place: a retrospective // ("I was almost 400 when I took that fight") is evidence about 2023 uttered in // 2025, and plotting it in 2025 would draw a weight gain that never happened. // Everything plots at `asOf ?? date`, and the two dates being different is // exactly what `retro_mismatch` reads. // // --------------------------------------------------------------------------- // Why the band can say "unknown" // --------------------------------------------------------------------------- // A regime segment is an assertion that he was on something for a stretch of // time, and the only evidence for it is that he said so at one end. Carrying // that forward indefinitely would put a claim on screen nobody made: six months // of silence after "I'm doing keto" is not six months of keto. So a segment is // asserted for `bandGapDays` (60) past the last claim that supports it, and the // rest of the silence is drawn HATCHED and labelled unknown. // // That is the same rule the headcount chart follows by refusing to draw a // midpoint: where the corpus is silent, the picture says silent. import { LEDGER_BUILTIN_KEYS, SCOPE_CONFIDENCE, VALUE_KINDS, addDays, chronological, dateKey, daysBetween, dayOf, gapWords, isStr, } from "./ledger-shared.mjs"; /** What a regime claim can be doing. `on` is "still on it", not a change. */ export const EVENTS = ["start", "on", "stop", "off"]; /** The events that OPEN or sustain a segment, against those that close one. */ const OPENING = new Set(["start", "on"]); const CLOSING = new Set(["stop", "off"]); /** * Whether a `stop`/`off` claim ends what is open on its track. * * AN OFF CLOSES THE REGIME IT NAMES, and nothing else. "Off GLP-1" said while * he is three weeks into keto is a statement about GLP-1; read as "off" the * track, it put "No diet" in the DIET cell — a word no row says — and counted a * change of diet that never happened. So the claim closes the track only when * the open regime IS the one it names, or nothing (or already the off regime) * is open, where the old reading and this one agree. * * @param {string|null} openKey the regime open on the track, or null * @param {string} named the regime the claim says he is off * @param {string|null} offKey the track's own off regime, if it has one */ export function offCloses(openKey, named, offKey = null) { if (openKey == null) return true; if (offKey != null && openKey === offKey) return true; return openKey === named; } /** The forms a value claim can take, when the schema does not name its own. */ export const DEFAULT_FORMS = ["current", "past", "delta", "goal", "overweight_by", "status"]; /** * The forms a PROMISE is written in (weight video rev 9): `promise`, what he * says he will do ("post a video of the scale"; `due` when he gave a day); * `promise_check`, his own later word about it; and `promise_claim`, ANOTHER * party's statement about it ("I bought the 5 bags"; `speaker`, `paidOn`); * and `promise_outcome`, how it ended (`outcome`: kept, refunded or * withdrawn -- a promise can end without being kept). `promise` names the * promise row on the last three; `kept: true` on a promise or a check, or an * outcome "kept", says it was kept. Built into every measure schema. */ export const PROMISE_FORMS = ["promise", "promise_check", "promise_claim", "promise_outcome"]; /** How a promise ended (a promise_outcome's `outcome`). */ export const PROMISE_OUTCOMES = ["kept", "refunded", "withdrawn"]; /** The two forms that are a reading of the quantity itself, so they plot. */ export const PLOTTING_FORMS = new Set(["current", "past"]); /** * What a regime can BE, beyond a plain state of affairs. * * `pledge` is a stop — the automatic rule reads it, and any drink inside the * window breaks it. `bounded` is a limit rather than a stop, and no automatic * rule can read it. `lapse` is the act that breaks either. */ export const REGIME_KINDS = ["pledge", "bounded", "lapse"]; /** * Is this a promise at all? Both shapes of one are, and everything that counts * promises — the scoreboard's PLEDGES, the schema's lapse cross-check, the * walk's open-pledge ledger — counts both. * * The two differ in HOW they break, and nowhere else. A rule that said * otherwise would put "27 pledges" and "16 of them broken" on the same board * out of two different definitions of a pledge. */ export const isPledgeKind = (kind) => kind === "pledge" || kind === "bounded"; /** How long a regime claim is allowed to speak for, in days, before silence. */ export const DEFAULT_BAND_GAP_DAYS = 60; /** * How soon after a pledge a lapse still counts as breaking it. * * Not a judgement about willpower. It is the window inside which the two claims * are ABOUT EACH OTHER: "I've stopped drinking" and, two days later, "had a few * at the game" are one event with two halves. Six months later they are two * unrelated facts, and a rule that joined them would be inventing the story * rather than reading it. */ export const DEFAULT_PLEDGE_DAYS = 30; /** * Silences whose UNDRAWN remainder is shorter than this get no hatched segment. * * The band's right edge is the last thing the ledger says about ANYTHING, so a * regime that lapses a few days before a weight claim leaves a sliver of hatch * nobody can read and nobody meant. Dropping it leaves a hole, which looks the * same and claims nothing. * * It is DRAWING SUPPRESSION AND NOTHING ELSE. The `regime-gap` decision is * recorded from the lapse itself, before this runs — it used to be read back * off the band, which meant a 63-day silence produced no segment and therefore * no decision, and the inbox went quiet about exactly the case the rule exists * to catch. */ const MIN_UNKNOWN_DAYS = 7; /** The six measure predicates. Named, computed, never asserted. */ export const MEASURE_PREDICATES = [ "contradicts_recent", "retro_mismatch", "regime_flip", "same_day_conflict", "not_his_number", "quit_unannounced", "broke_pledge", ]; /** Thresholds. One definition, because the inbox and the chart both cite them. */ export const MEASURE_THRESHOLDS = { /** two readings this close in time … */ recentDays: 14, /** … differing by more than this are a contradiction, not a fluctuation. */ recentDelta: 15, /** a retrospective this far from the contemporaneous record is a mismatch. */ retroDelta: 20, /** how far either side of `asOf` to look for the contemporaneous record. */ retroWindowDays: 120, /** a regime change this soon after the last one is a flip. */ flipDays: 30, }; // --------------------------------------------------------------------------- // The schema // --------------------------------------------------------------------------- /** * The kinds a declared field may take, and what each one means on a row. * * A closed list, because the whole point of declaring a field is that three * readers -- the arithmetic, the bench and `umtool check` -- agree about what a * legal answer is. An open `kind` would put the agreement back in prose. */ export const FIELD_KINDS = ["text", "enum", "number", "bool", "rowRef", "seconds"]; /** * Where a declared field SHOWS, when it shows at all. * * `none` is the default and is not a lesser answer: `breaks` decides whether a * pledge was broken and never appears on screen as itself. `cell` prefixes the * row's own cell text; `gloss` is one quiet sub-line under the first row of the * walk that carries it. */ export const FIELD_RENDERS = ["none", "cell", "gloss"]; /** How long a `text` field may be when the schema does not say. */ export const DEFAULT_FIELD_MAXLENGTH = 200; /** The row facets an `appliesTo` may narrow on. */ const APPLIES_FACETS = ["scope", "value", "role", "population", "event"]; /** * The declared fields, normalised, cross-checked and loud about every way a * schema can be wrong. * * Loud rather than lenient for the same reason the track/regime cross-check * above is: a field the arithmetic silently drops is a column of adjudication * work that goes into the manifest and never comes out of it, and nothing says * so. The four ways: a kind nobody implements, an enum with no options to * choose from, two fields fighting over one key, and a field named after a * built-in -- which would not be a new field at all, it would be a second, * differently-validated door onto `display`. */ function normaliseFields(raw) { const out = []; const seen = new Set(); for (const f of raw ?? []) { const key = String(f?.key ?? "").trim(); if (!key) { throw new Error("measure schema: a `fields` entry has no `key`"); } if (seen.has(key)) { throw new Error(`measure schema: two \`fields\` entries declare \`${key}\``); } if (LEDGER_BUILTIN_KEYS.has(key)) { throw new Error( `measure schema: \`fields\` declares \`${key}\`, which is a built-in row key ` + "— a declared field cannot be a second door onto one the code already means", ); } seen.add(key); if (!FIELD_KINDS.includes(f?.kind)) { throw new Error( `measure schema: field \`${key}\` has kind \`${f?.kind ?? ""}\` — one of ` + FIELD_KINDS.join(", "), ); } const render = f.render == null ? "none" : String(f.render); if (!FIELD_RENDERS.includes(render)) { throw new Error( `measure schema: field \`${key}\` renders as \`${render}\` — one of ` + FIELD_RENDERS.join(", "), ); } const options = Array.isArray(f.options) ? f.options.map(String).filter((o) => o.length) : null; if (f.kind === "enum" && !options?.length) { throw new Error(`measure schema: enum field \`${key}\` declares no \`options\``); } let appliesTo = null; if (f.appliesTo && typeof f.appliesTo === "object") { appliesTo = {}; for (const facet of APPLIES_FACETS) { if (f.appliesTo[facet] != null) appliesTo[facet] = String(f.appliesTo[facet]); } if (!Object.keys(appliesTo).length) appliesTo = null; } out.push({ key, label: f.label ?? key, kind: f.kind, help: f.help ?? null, options, maxLength: f.kind === "text" ? Number.isFinite(f.maxLength) ? f.maxLength : DEFAULT_FIELD_MAXLENGTH : null, min: Number.isFinite(f.min) ? f.min : null, max: Number.isFinite(f.max) ? f.max : null, appliesTo, render, }); } return out; } /** * The schema with every default filled in, so no reader has to know them. * * A track's `role` is EXPLICIT. Guessing it from the key ("regime" looks like a * regime track) would work for exactly one manifest and then silently plot a * regime key on the value axis for the next one. */ export function measureSchema(schema) { const s = schema ?? {}; const tracks = (s.tracks ?? []).map((t) => ({ key: String(t.key), label: t.label ?? String(t.key), shortLabel: t.shortLabel ?? null, color: t.color ?? null, role: t.role === "regime" ? "regime" : "value", /** * Which regimes are THIS track's, when the schema says. * * `regimes[]` is one flat list because for one regime track it may as well * be. With two -- a diet and a drink -- it is a list of six words in which * nothing says which three belong to which strip, and the failure is * silent: a `dry` claim on the diet track opens a segment, draws a band and * reads as a diet. Naming them per track is what makes that a loud error * instead, and it is the only cross-check between `tracks` and `regimes` * that exists. */ regimes: Array.isArray(t.regimes) ? t.regimes.map(String) : null, /** THIS track's word for "the rule is over", resolved below. */ offKey: null, })); const regimes = (s.regimes ?? []).map((r) => ({ key: String(r.key), label: r.label ?? String(r.key), color: r.color ?? null, /** * What this regime IS, when the schema says: a promise, a BOUNDED promise, * or the breaking of one. Absent on every regime that has never needed it * -- a diet is none of the three -- and absent is what every shipped * manifest carries, so nothing that does not declare `kind` gains a flag. * * `bounded` is a promise he put a LIMIT on rather than a stop to: "two * nights a week", "about 20% as much". The automatic rule cannot read it — * every drink inside thirty days would break "two nights a week", and it * is precisely the drinks that do NOT that make the pledge a bound. So a * bounded pledge breaks only where a `breaks` reference says it does. */ kind: REGIME_KINDS.includes(r.kind) ? r.kind : null, })); // Loud, and by name. A regime a track claims and the schema never declares // draws nothing, flags nothing and says nothing -- the band is simply shorter // than the evidence, which is the one failure mode this file exists to make // impossible. for (const t of tracks) { if (!t.regimes) continue; const missing = t.regimes.filter((k) => !regimes.some((r) => r.key === k)); if (missing.length) { throw new Error( `measure schema: track \`${t.key}\` names regime${missing.length === 1 ? "" : "s"} ` + `no \`regimes\` entry declares — ${missing.join(", ")}`, ); } // A lapse is only a lapse FROM something. A track that declares one and no // pledge would produce a `broke_pledge` that can never fire, which reads on // the board as "he never broke one" -- an assertion the ledger has not // made. Loud, and by name, for the same reason the check above is. const kindsHere = t.regimes.map((k) => regimes.find((r) => r.key === k)?.kind ?? null); if (kindsHere.includes("lapse") && !kindsHere.some(isPledgeKind)) { throw new Error( `measure schema: track \`${t.key}\` declares a \`lapse\` regime and no \`pledge\` ` + "— a lapse is only meaningful against something it lapses from", ); } } // The same check for a schema whose tracks do not enumerate their regimes: // one flat list, so the question is only whether a pledge exists at all. if ( regimes.some((r) => r.kind === "lapse") && !regimes.some((r) => isPledgeKind(r.kind)) && !tracks.some((t) => t.regimes) ) { throw new Error( "measure schema: a `lapse` regime is declared and no `pledge` is " + "— a lapse is only meaningful against something it lapses from", ); } // WHOSE `off` IS IT? A per-track answer, because an off label is a WORD, and // a word written for one strip is a lie on another. `offKey` is one flat key // for the whole schema, and with two regime tracks that put "No diet" in the // DRINKING cell the moment he said he had stopped being dry — the diet // track's word, on the drinking strip, asserting something no row says. // // Four rules, in order, each of which can be answered off the schema alone: // // 1. the track names its own (`offRegime`) — the escape hatch a manifest // uses to state the truth once and for all; // 2. an off-shaped regime (`off`, or `off_`) that THIS track // declares and no other regime track does — sole ownership, which is // what "the track's own word" means when nothing says it outright; // 3. a shared `off` belongs to the FIRST regime track, the same convention // `switches`, `band` and `final.regime` have always kept: one flat list // is authored around one strip, and that strip is the first one; // 4. otherwise NOTHING. The drawing says so with a dash in our own quiet // colour rather than borrowing a word he did not use — which is the // whole difference between reporting a silence and inventing a status. const fields = normaliseFields(s.fields); const globalOff = regimes.some((r) => r.key === "off") ? "off" : null; const firstRegimeTrack = tracks.find((t) => t.role === "regime") ?? null; tracks.forEach((t, i) => { if (t.role !== "regime") return; const raw = (s.tracks ?? [])[i] ?? {}; const declared = (k) => regimes.some((r) => r.key === k); const named = raw.offRegime ? String(raw.offRegime) : null; if (named && declared(named)) { t.offKey = named; return; } const others = tracks.filter((x, j) => j !== i && x.role === "regime"); const sole = (t.regimes ?? []) .filter((k) => k === "off" || k.startsWith("off_")) .find((k) => declared(k) && !others.some((x) => (x.regimes ?? []).includes(k))); if (sole) { t.offKey = sole; return; } t.offKey = globalOff && firstRegimeTrack === t ? globalOff : null; }); return { kind: "measure", unit: s.unit ?? "", yLabel: s.yLabel ?? (s.unit ? String(s.unit).toUpperCase() : "VALUE"), yMin: Number.isFinite(s.yMin) ? s.yMin : null, yMax: Number.isFinite(s.yMax) ? s.yMax : null, from: s.from ?? null, to: s.to ?? null, tracks, // The PROMISE forms are every measure ledger's (what he says he will do, // and a later word about it): built in, so a schema written before them // carries them without saying so. forms: [...new Set([...(s.forms?.length ? s.forms.map(String) : DEFAULT_FORMS), ...PROMISE_FORMS])], regimes, /** * The fields THIS manifest declares beyond the built-ins. * * Empty on every manifest written before this one, which is the whole * compatibility contract: no `fields`, no behaviour, byte for byte. */ fields, bandGapDays: Number.isFinite(s.bandGapDays) ? s.bandGapDays : DEFAULT_BAND_GAP_DAYS, /** How soon after a pledge a lapse still breaks it. */ pledgeDays: Number.isFinite(s.pledgeDays) ? s.pledgeDays : DEFAULT_PLEDGE_DAYS, /** * The regime a `stop` hands over to, when the schema declares one. * * Schema-wide, and the walk still reads it: `open`, `prevChange` and the * band are about WHICH SEGMENT is running, and one flat off segment is a * true enough answer for all of them. It is the LABEL that cannot be * shared, and that is `tracks[].offKey`. */ offKey: globalOff, }; } /** The vocabulary a page or an editor may offer. Derived, never restated. */ export function measureVocab(schema) { const s = measureSchema(schema); return { kind: "measure", scopes: s.tracks.map((t) => t.key), populations: s.forms, valueKinds: VALUE_KINDS, scopeConfidence: SCOPE_CONFIDENCE, events: EVENTS, regimes: s.regimes.map((r) => r.key), tracks: s.tracks, regimeList: s.regimes, /** The declared fields, so a bench can draw one control per field. */ fields: s.fields, unit: s.unit, schema: s, }; } const trackOf = (s, key) => s.tracks.find((t) => t.key === key) ?? null; const regimeOf = (s, key) => s.regimes.find((r) => r.key === key) ?? null; /** * Which of the gate fields a measure entry is missing or has wrong. * * The same six as headcount, plus TWO that only exist here and are not * optional extras: a regime claim with no `event` cannot open or close a * segment, and one whose `value` is not a declared regime cannot be drawn at * all. Both would fail SILENTLY -- the band would simply be shorter than the * evidence -- which is the failure mode the gate exists to make loud. */ export function measureGaps(entry, schema) { const s = measureSchema(schema); const gaps = []; const tr = trackOf(s, entry?.scope); if (!tr) gaps.push("scope"); if (!isStr(entry?.scopeBasis)) gaps.push("scopeBasis"); if (!SCOPE_CONFIDENCE.includes(entry?.scopeConfidence)) gaps.push("scopeConfidence"); if (!s.forms.includes(entry?.population)) gaps.push("population"); if (!VALUE_KINDS.includes(entry?.valueKind)) gaps.push("valueKind"); if (!Array.isArray(entry?.flags)) gaps.push("flags"); if (tr?.role === "regime") { if (!EVENTS.includes(entry?.event)) gaps.push("event"); if (!regimeOf(s, entry?.value)) gaps.push("value"); } return gaps; } /** * Whether a declared field is offered on THIS row. * * `appliesTo` narrows a field to the rows it can mean anything on: `breaks` is * a question about a drink, and offering it on a weight reading is how a bench * ends up carrying an answer no arithmetic will ever read. */ export function fieldApplies(field, entry, schema) { const a = field?.appliesTo; if (!a) return true; const s = measureSchema(schema); const tr = trackOf(s, entry?.scope); const got = { scope: entry?.scope ?? null, value: entry?.value ?? null, role: tr?.role ?? null, population: entry?.population ?? null, event: entry?.event ?? null, }; return Object.entries(a).every(([k, want]) => String(got[k] ?? "") === want); } /** * The declared-field half of a claim edit: what to write, what to delete, and a * loud error for anything else. * * Called AFTER the built-ins have been validated and BEFORE the write, so a * patch that is half legal writes nothing at all. Keys the schema does not * declare are not this function's business and are left alone — the caller has * already ruled on the built-ins, and a key in neither set is what * `LEDGER_BUILTIN_KEYS` and `umtool check` are for. * * `null` and `""` CLEAR, for every kind. A field an operator has emptied is a * field they are saying nothing about, and leaving `""` on the row would put an * answer of "" in front of the next reader. * * @param {object} entry the row as it stands * @param {object} patch the incoming edit * @param {object} schema `manifest.ledgerSchema` * @param {Array} [ledger] needed only to resolve a `rowRef` * @returns {{ set: Record, 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} 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} 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; // Counted only when it is a usable claim of HIS: an `unresolved` scope (a joke, a misattributed line) and another // speaker's row (`speaker`) are in the record and on screen, never in a tally (operator, 6 Nov). const settled = ruled && e.scopeConfidence !== "unresolved" && !(typeof e.speaker === "string" && e.speaker.trim()); 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 range his words give ("330-340", "220–240 lb"), as `[lo, hi]`, or null. */ export function displayRange(display) { const m = /(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)/.exec(String(display ?? "")); if (!m) return null; const lo = Number(m[1]); const hi = Number(m[2]); return Number.isFinite(lo) && Number.isFinite(hi) && hi > lo ? [lo, hi] : null; } /** * Does a QUALIFIED reading agree with the SPECIFIC one in force -- so it is no * new figure and the current weight stays (operator, 6 Nov: "If a range is * provided (e.g. 'over 300') and we already match with a specific number * (e.g. 342), don't change the current weight")? `bound` and `specific` are * `{ value, qualifier?, range? }`. Agrees when `specific` is a plain number (no * qualifier, no range) and `bound` is a qualified one it satisfies: ">300" * by anything over 300, "<300" by anything under, "≈390" by 387 to 391 (the * dial's wedge), a range by anything inside it. A bound that CONTRADICTS the * specific reading (">300" against 291) is new information: it does not agree, * and it moves the reading as any other does. */ export function boundAgrees(bound, specific) { if (!bound || !specific) return false; const c = Number(specific.value); if (!Number.isFinite(c) || specific.qualifier || Array.isArray(specific.range)) return false; const v = Number(bound.value); const r = Array.isArray(bound.range) && bound.range.length === 2 ? bound.range : null; if (r) return c >= r[0] && c <= r[1]; if (!Number.isFinite(v)) return false; if (bound.qualifier === ">") return c > v; if (bound.qualifier === "<") return c < v; if (bound.qualifier === "≈") return c >= v - 3 && c <= v + 1; return false; } /** * 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); }