// A MEASURE ledger's rows, checked (weight video rev 9): what `umtool ledger // add|set|rm` may write into `manifest.ledger`, against the manifest's own // `ledgerSchema`. Pure: manifest.mjs's addLedgerRow / updateLedgerRow / // removeLedgerRow write what this returns, under the manifest lock. // // A row is the built-in keys (ledger-shared.mjs LEDGER_BUILTIN_KEYS, each // with its type here) and the schema's declared `fields[]` (measure-totals // validateFields); any other key is refused by name -- a key nothing reads is // adjudication work that never comes out. A written row passes the gate the // arithmetic keeps (measureGaps): a scope that is a track, a form the schema // names, the six adjudication fields, and on a regime track a declared // regime and an event. The promise forms are every measure ledger's: // `promise` (what he says he will do), `promise_check` (his later word about // it) and `promise_claim` (another party's statement about it, with its // `speaker` and `paidOn`), the last two naming the promise in `promise`; // `kept: true` on a promise or a check; `promise_outcome` says how it ended // (`outcome`: kept, refunded, withdrawn). A row's `speaker` (absent: the // subject) is a lower-case key; another speaker's row moves none of his // numbers (measure-slice.mjs). import { EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, STAMP_NOTE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields, } from "umtool-report-to-video/ledger-totals"; import { analysisRowRefs } from "umtool-report-to-video/analysis-plan"; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const DATE_RE = /^\d{4}(?:-\d{2}(?:-\d{2})?)?$/; const DAY_RE = /^\d{4}-\d{2}-\d{2}$/; const ID_RE = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/; /** The forms whose value is a number in the schema's unit. */ const NUMERIC_FORMS = new Set(["current", "past", "delta", "goal", "goal_loss", "overweight_by"]); /** Each built-in key's type: what a CLI flag's text is parsed as, and what is checked. */ export const LEDGER_KEY_TYPES = Object.freeze({ id: "id", date: "date", asOf: "date?", scope: "text", population: "text", value: "value", event: "text?", display: "text?", label: "text?", quote: "text?", deadline: "text?", src: "text?", channel: "text?", video: "text?", cite: "seconds?", citeFrom: "text?", scopeBasis: "text", scopeConfidence: "text", valueKind: "text", flags: "list", hedged: "bool?", unsourced: "bool?", plotted: "bool?", hidden: "bool?", entryId: "text?", authorNote: "text?", run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", speaker: "speaker?", paidOn: "day?", outcome: "text?", stampNote: "text?", }); /** Is this manifest's ledger a measure ledger (the one these writers write)? */ export const isMeasureLedger = (manifest) => isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure"; /** * A flag's text as the value of `key`: a number for a number key ("null" * clears), true/false for a boolean, a list split on "|" for `flags`, a * number for `value` when it reads as one. Declared fields are left as text * (validateFields types them). */ export function parseLedgerValue(key, text) { const t = String(text); if (t === "null") return null; const type = LEDGER_KEY_TYPES[key]; if (type === "bool?") { if (t === "true") return true; if (t === "false") return false; return t; } if (type === "seconds?" || type === "run?") return /^-?\d+(?:\.\d+)?$/.test(t) ? Number(t) : t; if (type === "value") return /^[-+]?\d+(?:\.\d+)?$/.test(t) ? Number(t) : t; if (type === "list") return t === "" ? [] : t.split("|").map((s) => s.trim()).filter(Boolean); return t; } /** * The row `patch` makes of `base` (null for a new row), checked and * normalised -- or a thrown sentence naming every problem. `unset` lists the * keys to remove. A new row gets the boring answer for three of the six * (`scopeConfidence` read, `valueKind` uttered, `flags` []) and its display * from its value; `scopeBasis` is never defaulted (a ruling with no basis is * an opinion). * * @param {object} manifest * @param {Record | null} base the row as it stands, or null * @param {Record} patch * @param {{ unset?: string[] }} [opts] * @returns {Record} */ export function ledgerRowOf(manifest, base, patch, { unset = [] } = {}) { if (!isMeasureLedger(manifest)) throw new Error('the manifest has no measure ledger (ledgerSchema.kind "measure")'); const schema = measureSchema(manifest.ledgerSchema); const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : []; const declared = new Map(schema.fields.map((f) => [f.key, f])); const errors = []; for (const k of [...Object.keys(patch ?? {}), ...unset]) { if (!LEDGER_BUILTIN_KEYS.has(k) && !declared.has(k)) { errors.push(`"${k}" is not a ledger key (the built-ins, or the schema's fields: ${[...declared.keys()].join(", ") || "none"})`); } } for (const k of unset) if (["id", "date", "scope", "population", "scopeBasis", "scopeConfidence", "valueKind", "flags"].includes(k)) errors.push(`"${k}" cannot be unset: every row has one`); if (errors.length) throw new Error(errors.join("; ")); const builtins = Object.fromEntries(Object.entries(patch ?? {}).filter(([k]) => LEDGER_BUILTIN_KEYS.has(k))); const fieldPatch = Object.fromEntries(Object.entries(patch ?? {}).filter(([k]) => declared.has(k))); const row = { ...(base ?? {}), ...builtins }; for (const k of unset) delete row[k]; if (!base) { row.scopeConfidence ??= "read"; row.valueKind ??= "uttered"; row.flags ??= []; } // ---- the built-ins, each against its type ---- if (!ID_RE.test(String(row.id ?? ""))) errors.push("id must be a letter, then letters, digits, dots, colons, dashes or underscores (at most 64)"); else if (!base && ledger.some((r) => r?.id === row.id)) errors.push(`the ledger already has a row ${row.id}`); if (!DATE_RE.test(String(row.date ?? ""))) errors.push("date must be YYYY-MM-DD (or YYYY-MM, YYYY)"); if (row.asOf !== undefined && row.asOf !== null && !DATE_RE.test(String(row.asOf))) errors.push("asOf must be a date, or null"); const track = schema.tracks.find((t) => t.key === row.scope) ?? null; if (!track) errors.push(`scope must be one of the ledger's tracks: ${schema.tracks.map((t) => t.key).join(", ")}`); if (!schema.forms.includes(row.population)) errors.push(`population must be one of ${schema.forms.join(", ")}`); const promiseForm = PROMISE_FORMS.includes(row.population); if (track?.role === "regime") { const allowed = track.regimes ?? schema.regimes.map((r) => r.key); if (!allowed.includes(String(row.value))) errors.push(`value on the ${track.key} track must be one of its regimes: ${allowed.join(", ")}`); if (!EVENTS.includes(row.event)) errors.push(`event must be one of ${EVENTS.join(", ")} on a regime track`); } else if (track) { if (NUMERIC_FORMS.has(row.population) && !Number.isFinite(row.value)) errors.push(`value must be a number (in ${schema.unit || "the ledger's unit"}) for a ${row.population} row`); if (promiseForm && row.value !== undefined && row.value !== null) errors.push(`a ${row.population} row has no value (its words are its display)`); if (row.event !== undefined && row.event !== null) errors.push("event is a regime track's"); } for (const [k, type] of Object.entries(LEDGER_KEY_TYPES)) { const v = row[k]; if (v === undefined || v === null) continue; if (type.startsWith("text") && typeof v !== "string") errors.push(`${k} must be text`); if (type === "speaker?" && !(typeof v === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(v))) errors.push(`${k} must be a speaker's key (lower case: "madamsavvy")`); if (type === "bool?" && typeof v !== "boolean") errors.push(`${k} must be true or false`); if (type === "seconds?" && !(Number.isFinite(v) && v >= 0)) errors.push(`${k} must be a source second, 0 or more`); if (type === "day?" && !DAY_RE.test(String(v))) errors.push(`${k} must be a day (YYYY-MM-DD)`); if (type === "list" && !(Array.isArray(v) && v.every((x) => typeof x === "string"))) errors.push(`${k} must be a list of sentences`); } if (row.scopeConfidence !== undefined && !SCOPE_CONFIDENCE.includes(row.scopeConfidence)) errors.push(`scopeConfidence must be one of ${SCOPE_CONFIDENCE.join(", ")}`); if (row.valueKind !== undefined && !VALUE_KINDS.includes(row.valueKind)) errors.push(`valueKind must be one of ${VALUE_KINDS.join(", ")}`); if (typeof row.scopeBasis !== "string" || !row.scopeBasis.trim()) errors.push("scopeBasis must quote the phrase that settles the scope (--scopeBasis)"); // ---- the measure instruments' own ---- const isDelta = row.population === "delta"; if (row.run !== undefined && row.run !== null) { if (!Number.isInteger(row.run) || row.run < 0) errors.push("run must be a whole number, 0 or more"); else if (!isDelta) errors.push("run is a loss claim's (a delta row)"); } if (row.retro !== undefined && row.retro !== null && !isDelta) errors.push("retro is a loss claim's (a delta row)"); if (row.kept !== undefined && row.kept !== null && !["promise", "promise_check"].includes(row.population)) errors.push("kept is a promise's (a promise or promise_check row)"); if (row.population === "promise_outcome") { if (!PROMISE_OUTCOMES.includes(row.outcome)) errors.push(`a promise_outcome says how it ended: outcome ${PROMISE_OUTCOMES.join(", ")}`); } else if (row.outcome !== undefined && row.outcome !== null) errors.push("outcome is a promise_outcome's"); // The words under the outcome's stamp on the promise clock (measure-extras.mjs STAMP_NOTE): one line of text. if (row.stampNote !== undefined && row.stampNote !== null) { if (row.population !== "promise_outcome") errors.push("stampNote is a promise_outcome's (the words under its stamp)"); else if (typeof row.stampNote !== "string" || !row.stampNote.trim() || /[\n\r]/.test(row.stampNote) || row.stampNote.trim().length > STAMP_NOTE.max) { errors.push(`stampNote is one line of 1–${STAMP_NOTE.max} characters (the stamp's second line; past ${STAMP_NOTE.fit} the lint warns it may not fit)`); } } if (["promise_check", "promise_claim", "promise_outcome"].includes(row.population)) { const p = ledger.find((r) => r?.id === row.promise); if (!row.promise) errors.push(`a ${row.population} names its promise (--promise )`); else if (!p || p.population !== "promise") errors.push(`promise must name a promise row (${row.promise} is ${p ? `a ${p.population} row` : "not in the ledger"})`); } else if (row.promise !== undefined && row.promise !== null) errors.push("promise is a promise_check's, promise_claim's or promise_outcome's"); if (row.paidOn !== undefined && row.paidOn !== null && row.population !== "promise_claim") errors.push("paidOn is a promise_claim's"); // A promise_check is HIS later word; another party's is a promise_claim. if (row.population === "promise_check" && row.speaker) errors.push(`a promise_check is the subject's own word: ${row.speaker}'s is a promise_claim`); if (row.entryId !== undefined && row.entryId !== null && !(manifest.timeline ?? []).some((e) => e?.id === row.entryId)) { errors.push(`entryId ${row.entryId} is not an entry of the timeline`); } if (errors.length) throw new Error(errors.join("; ")); // ---- the declared fields (validateFields types and scopes them) ---- try { const { set, clear } = validateFields(row, fieldPatch, schema, ledger); Object.assign(row, set); for (const k of clear) delete row[k]; } catch (err) { throw new Error(err instanceof Error ? err.message : String(err)); } for (const k of unset) if (declared.has(k)) delete row[k]; if (row.display === undefined || row.display === null || row.display === "") { row.display = measureDisplay({ ...row, display: null }, schema); } const gaps = measureGaps(row, schema); if (gaps.length) throw new Error(`the row is not adjudicated: ${gaps.join(", ")}`); return row; } /** * What still names a row -- the timeline entries that pin it (`claim: ""`) * and the rows that refer to it (`promise`, a declared rowRef field) -- for * `rm` to refuse with. * * @returns {string[]} */ export function ledgerRowReferences(manifest, id) { const out = []; for (const e of manifest.timeline ?? []) if (typeof e?.claim === "string" && e.claim.trim() === id) out.push(`timeline entry ${e.id} pins it (claim)`); // An analysis item draws the rows it names (analysis-plan.mjs): its series, marks, pace ends, status rows, its line. for (const e of manifest.timeline ?? []) if (e?.type === "analysis" && analysisRowRefs(e).includes(id)) out.push(`analysis item ${e.id} draws it (series, a mark, a pace end, a status row or its line)`); const refs = isMeasureLedger(manifest) ? measureSchema(manifest.ledgerSchema).fields.filter((f) => f.kind === "rowRef").map((f) => f.key) : []; for (const r of manifest.ledger ?? []) { if (!isObj(r) || r.id === id) continue; if (r.promise === id) out.push(`row ${r.id} names it (promise)`); for (const k of refs) if (r[k] === id) out.push(`row ${r.id} refers to it (${k})`); } return out; }