Archilyzer · Source

archilyzer

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

commit 66c825681dabcbe3e6d78182c4c40f1cb25370ca
parent dcab2b796b9ea7eb555b6e9fa18b699a1fd07eb1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 23:26:32 -0500

umtool: `ledger` and `measure` -- a measure ledger's rows, and its slice

`umtool ledger <p> ls|add|set|rm [--json]` is the only writer of a measure
ledger's rows (manifest.mjs addLedgerRow / updateLedgerRow /
removeLedgerRow, under the manifest lock). ledgerRows.mjs checks the row a
write makes against the manifest's ledgerSchema and names every problem: a
track, a form the schema names, a number in its unit or a declared regime
with an event, the six adjudication fields (a new row defaults
scopeConfidence/valueKind/flags; scopeBasis is never defaulted), the
declared fields (validateFields), and the instruments' own keys -- `run`
(a loss claim's run, his words placing it), `retro` (a loss told in the past
with no asOf: off the odometer), `promise` (a promise_check's promise),
`kept`, `due`. Any other key is refused by name; rm refuses a row a
timeline entry pins or another row names.

The promise forms (`promise`, `promise_check`) are built into every measure
schema (measure-totals.mjs PROMISE_FORMS), and the five new keys are
built-ins (LEDGER_BUILTIN_KEYS).

`umtool measure <p> [--take <t>] [--scopes a,b] [--scale MIN-MAX]
[--as-of D] [--json]` prints the slice: each event at its cut second (the
take's built schedule.json, else an estimate; each figure timed by its
clip's words, read off disk), the hidden rows, and the totals. Docs:
umtool/docs/knobs.md ("The measure slice"), umtool/docs/cli.md, the usage.

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

Diffstat:
Mumtool/bin/umtool.mjs | 11+++++++++++
Mumtool/docs/cli.md | 2++
Mumtool/docs/knobs.md | 38++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/ledgerCli.mjs | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/ledgerCli.test.mjs | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/ledgerRows.mjs | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/measureCli.mjs | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/ledger-shared.mjs | 5+++++
Mumtool/report-to-video/ledger-totals.mjs | 2++
Mumtool/report-to-video/measure-slice.mjs | 5++---
Mumtool/report-to-video/measure-totals.mjs | 13++++++++++++-
Mumtool/report-to-video/measure-totals.test.mjs | 3++-
Mumtool/report-to-video/package.json | 2++
14 files changed, 756 insertions(+), 5 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -94,6 +94,10 @@ // promo/trailer-beats.json): running length against the limit, beats outside their clip // umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence, // each edge into its pause: before -> after for review; --apply writes the named rows +// umtool ledger <project> [ls | add <id> --<key> V … | set <id> --<key> V … [--unset k,k] | rm <id>] [--json] +// a measure ledger's rows, through its writers (weight video rev 9) +// umtool measure <project> [--take <t>] [--scopes a,b] [--as-of D] [--json] +// the measure slice the instruments draw from // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] // the clip deck's montage rulings (release 34) // umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of @@ -1015,6 +1019,10 @@ function usage() { " --reel <name>: that beat reel (promo/<name>-beats.json); every write is an undo point", " umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence (its", " cut's, else the whole ones in its window), each edge into its pause; before -> after; --apply writes", + " umtool ledger <project> [ls] [--scope S] [--json] | add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] | set <id> --<key> V … [--unset k,k] | rm <id>", + " a measure ledger's rows, checked against its ledgerSchema (incl. promise / promise_check, run, retro)", + " umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]", + " the measure slice the instruments draw from: events at their cut seconds, hidden rows, totals", " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>", " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]", @@ -1169,6 +1177,9 @@ const COMMANDS = { tighten: async () => process.exit(await (await import("../lib/report/tightCli.mjs")).tightenCommand(argv.slice(argv.indexOf("tighten") + 1))), // The trailer's beats, edited (UI notes item 11): lib/report/trailerBeatsCli.mjs. "trailer-beats": async () => process.exit(await (await import("../lib/report/trailerBeatsCli.mjs")).trailerBeatsCommand(argv.slice(argv.indexOf("trailer-beats") + 1))), + // A measure ledger's rows, and the slice its instruments draw from (weight video rev 9). + ledger: async () => process.exit(await (await import("../lib/report/ledgerCli.mjs")).ledgerCommand(argv.slice(argv.indexOf("ledger") + 1))), + measure: async () => process.exit(await (await import("../lib/report/measureCli.mjs")).measureCommand(argv.slice(argv.indexOf("measure") + 1))), // The clip deck's rulings (release 34): lib/report/rulingsCli.mjs. rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), // Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs. diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -69,6 +69,8 @@ Inbox cannot disagree about what is wrong with one. | `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | | `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | +| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) | +| `measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]` | the **measure slice** the instruments draw from (`render.chrome.deck.measure`; the flags override it): each row in scope the cut shows at the cut second its figure is said, the hidden rows, and the totals -- the odometer's runs, NET, the goals, the diets, the promises. The take's built `schedule.json` with `--take`, else an estimate; `--json` prints the slice. Reads only ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | | `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -446,6 +446,44 @@ umtool look <p> deck.claims='[{"kind":"count","at":"less-than-ten","t":903.6,"sa umtool set <p> costco-ok claim.eventDate=2026-09-22 ``` +## The measure slice (the weight instruments) + +A manifest whose `ledgerSchema.kind` is `"measure"` (one quantity over time and the regime he names; report-to-video +`measure-totals.mjs`) has its rows pinned to the cut by each row's `entryId` or an entry's ledger pin, `claim: +"<row id>"` (a string; a manifest that stamps fact-check verdicts keeps `claim` as `{id, verdict}`). With the deck on +and `render.chrome.deck.measure` set, the build writes the **measure slice** into `schedule.json` (`doc.measure`, +`measure-slice.mjs`): every row in scope the cut shows, at the cut second its figure is said (the clip's words, else +its cues spread by characters, else the entry's `quoteStart`, else the segment's start -- `tFrom` says which), the +rows no entry shows (`hidden`), the state after each event (current, remembered, goal, goals, lost, net, diet, +promises) and the totals. Every instrument module reads it whole (`slices.measure`). Absent the key, the schedule is +the one it always was. + +| Key | What it is | +|---|---| +| `scopes` | the ledger's tracks the instruments see (`["weight","regime"]`); a row of any other track is ignored entirely. Default: every track | +| `scale` | `{min, max}` in the ledger's unit: the dial's face. Default: the schema's `yMin`..`yMax` | +| `asOf` | the day the live countdowns and the promise clock count to (YYYY-MM-DD). Default: the day it is built | + +**The odometer** (ruled 5 Nov 2026, "go by his words"): only real-time loss claims count -- a `delta` below zero with +no `asOf` and not `retro`; a run's figure is its HIGHEST claim (his figure, over any app's he cites); a row's `run` +places it where his words say ("since I started"), else a gap over `bandGapDays` starts a new run; the total is the +sum of the runs. A **goal_loss** is a target weight against the start of the run open when he set it (a remembered +weight about a day within `bandGapDays` before the run's first claim), else against the last weight he stated. A +**diet** is the regime cell: an off closes only the regime it names. A **promise** (`promise`: what he says he will +do, `due` when he gave a day) is checked by later `promise_check` rows naming it (`promise`); `kept: true` on either +keeps it. + +Rows are written through `umtool ledger` only; `umtool measure` prints the slice: + +```sh +umtool look <p> deck.measure='{"scopes":["weight","regime"],"scale":{"min":220,"max":400}}' +umtool ledger <p> add p01 --date 2026-10-23 --scope weight --population promise --display "post a video of the scale" --scopeBasis "his own post" --citeUrl https://x.com/…/status/… +umtool ledger <p> add p02 --date 2026-11-03 --scope weight --population promise_check --promise p01 --display "pull up a video from three months ago" --scopeBasis "about the scale video" +umtool ledger <p> set w14 --retro true # a loss told in the past: off the odometer +umtool ledger <p> set w75 --run 6 # his words put it in the 2025 run +umtool measure <p> --take <t> --json +``` + ## Walk and preview (the clip editor) The clip editor (`/projects/<p>/clips`, a clip with **Edit**) is where a deck cut is walked: under the player, diff --git a/umtool/lib/report/ledgerCli.mjs b/umtool/lib/report/ledgerCli.mjs @@ -0,0 +1,148 @@ +// `umtool ledger` (weight video rev 9): a MEASURE ledger's rows from a +// terminal -- listed, added, patched, removed -- through the manifest's own +// writers (manifest.mjs addLedgerRow / updateLedgerRow / removeLedgerRow), so +// every row written is checked against the manifest's ledgerSchema +// (ledgerRows.mjs) exactly as the instruments will read it. +// +// umtool ledger <project> [ls] [--scope S] [--population P] [--json] +// umtool ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}'] [--json] +// umtool ledger <project> set <id> --<key> V … [--unset k,k] [--json] +// umtool ledger <project> rm <id> [--json] +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { addLedgerRow, removeLedgerRow, updateLedgerRow } from "./manifest.mjs"; +import { isMeasureLedger, parseLedgerValue } from "./ledgerRows.mjs"; + +export const LEDGER_USAGE = [ + "usage: umtool ledger <project> [ls] [--scope S] [--population P] [--json] the ledger's rows", + " umtool ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] [--row '{…}'] [--json]", + " umtool ledger <project> set <id> --<key> V … [--unset k,k] [--json]", + " umtool ledger <project> rm <id> [--json]", + "", + "A measure ledger's rows (ledgerSchema.kind \"measure\"), written only through these: each row is checked against", + "the schema -- a scope that is a track, a form it names (and the promise forms, promise / promise_check), a", + "number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults", + "scopeConfidence read, valueKind uttered, flags []; --scopeBasis is never defaulted) and the declared fields.", + "--<key> sets any built-in key (date asOf scope population value event display label quote deadline src channel", + "video cite citeFrom scopeBasis scopeConfidence valueKind flags (a|b) hedged unsourced entryId authorNote, and the", + "instruments' own: run (a loss claim's run, his words placing it), retro (a loss told in the past with no asOf:", + "off the odometer), promise (a promise_check's promise), kept, due (YYYY-MM-DD)) or a declared field; `null`", + "clears a value. rm refuses a row a timeline entry pins or another row names.", +].join("\n"); + +class CliError extends Error {} + +/** `--key value` pairs (the rest: words), `--json`/`--help` alone. */ +function parseArgs(args) { + const flags = new Map(); + const words = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--json" || a === "--help") { flags.set(a.slice(2), true); continue; } + if (a.startsWith("--")) { + const eq = a.indexOf("="); + if (eq > 0) { flags.set(a.slice(2, eq), a.slice(eq + 1)); continue; } + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags.set(a.slice(2), args[i + 1]); + i += 1; + continue; + } + words.push(a); + } + return { flags, words }; +} + +/** The row patch the flags spell: `--row` JSON first, then each `--<key>`. */ +function patchOf(flags, skip) { + let patch = {}; + if (flags.has("row")) { + try { + patch = JSON.parse(String(flags.get("row"))); + } catch (e) { + throw new CliError(`--row is not JSON: ${e instanceof Error ? e.message : e}`); + } + if (!patch || typeof patch !== "object" || Array.isArray(patch)) throw new CliError("--row must be a JSON object"); + } + for (const [k, v] of flags) { + if (skip.has(k)) continue; + patch[k] = parseLedgerValue(k, v); + } + return patch; +} + +const line = (r) => + [ + String(r.id).padEnd(6), + String(r.date ?? "").padEnd(10), + String(r.scope ?? "").padEnd(9), + String(r.population ?? "").padEnd(14), + String(r.display ?? r.value ?? "—").padEnd(22), + r.entryId ? `@${r.entryId}` : "", + Number.isInteger(r.run) ? `run ${r.run}` : "", + r.retro ? "retro" : "", + r.promise ? `-> ${r.promise}` : "", + r.kept ? "kept" : "", + String(r.label ?? "").slice(0, 70), + ].filter(Boolean).join(" "); + +/** + * @param {string[]} args the words after `ledger` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts] + * @returns {Promise<number>} the exit code + */ +export async function ledgerCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const { flags, words } = parseArgs(args); + const [projectArg, verb = "ls", id] = words; + if (!projectArg || flags.get("help")) { + err(LEDGER_USAGE); + return 2; + } + const json = flags.get("json") === true; + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + + if (verb === "ls") { + const rows = (manifest.ledger ?? []).filter((x) => + (!flags.has("scope") || x.scope === flags.get("scope")) && (!flags.has("population") || x.population === flags.get("population"))); + if (json) out(JSON.stringify({ project: project.id, kind: isMeasureLedger(manifest) ? "measure" : "headcount", rows }, null, 2)); + else { + for (const x of rows) out(line(x)); + out(`${rows.length} of ${(manifest.ledger ?? []).length} row(s)`); + } + return 0; + } + if (!isMeasureLedger(manifest)) throw new CliError(`${project.id} has no measure ledger (ledgerSchema.kind "measure"): these writers are a measure ledger's`); + if (!id) throw new CliError(`${verb} needs a row id`); + if (verb === "add") { + const patch = { ...patchOf(flags, new Set(["json", "help"])), id }; + const done = await addLedgerRow(project.dir, patch); + if (json) out(JSON.stringify({ project: project.id, added: done.row }, null, 2)); + else out(`added ${line(done.row)}`); + return 0; + } + if (verb === "set") { + const unset = flags.has("unset") ? String(flags.get("unset")).split(",").map((s) => s.trim()).filter(Boolean) : []; + const patch = patchOf(flags, new Set(["json", "help", "unset"])); + if (!Object.keys(patch).length && !unset.length) throw new CliError("set needs --<key> <value> or --unset <keys>"); + const done = await updateLedgerRow(project.dir, id, patch, { unset }); + if (json) out(JSON.stringify({ project: project.id, row: done.row }, null, 2)); + else out(`set ${line(done.row)}`); + return 0; + } + if (verb === "rm") { + const done = await removeLedgerRow(project.dir, id); + if (json) out(JSON.stringify({ project: project.id, removed: done.row.id }, null, 2)); + else out(`removed ${done.row.id}`); + return 0; + } + throw new CliError(`unknown: ledger ${verb} — ls, add, set or rm`); + } catch (e) { + err(`umtool ledger: ${e instanceof Error ? e.message : String(e)}`); + return 1; + } +} diff --git a/umtool/lib/report/ledgerCli.test.mjs b/umtool/lib/report/ledgerCli.test.mjs @@ -0,0 +1,146 @@ +// `umtool ledger` and `umtool measure` (weight video rev 9): a measure +// ledger's rows written only through its writers, checked against the +// schema, and the slice printed off a project made here. Run with: +// pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-ledger-cli-")); +process.env.REPORTS_DIR = path.join(ROOT, "reports"); +const { ledgerCommand } = await import("./ledgerCli.mjs"); +const { measureCommand } = await import("./measureCli.mjs"); +const { ledgerRowOf, ledgerRowReferences, parseLedgerValue } = await import("./ledgerRows.mjs"); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const SCHEMA = { + kind: "measure", + unit: "lb", + yMin: 210, + yMax: 400, + bandGapDays: 60, + tracks: [ + { key: "weight", role: "value", label: "Weight" }, + { key: "regime", role: "regime", label: "Diet", regimes: ["keto", "off"] }, + { key: "drinking", role: "regime", label: "Drinking", regimes: ["dry", "drinking"] }, + ], + forms: ["current", "past", "delta", "goal", "goal_loss", "overweight_by", "status"], + regimes: [{ key: "keto", label: "Keto" }, { key: "off", label: "No diet" }, { key: "dry", label: "Dry" }, { key: "drinking", label: "Drinking" }], + fields: [ + { key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], appliesTo: { scope: "weight" }, render: "cell" }, + { key: "citeUrl", label: "Source link", kind: "text", maxLength: 200 }, + ], +}; +const base = (o) => ({ scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o }); +const MANIFEST = { + schemaVersion: 1, + slug: "weigh", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan", channelsDir: "nowhere" }, + render: { fps: 30, transition: 0 }, + ledgerSchema: SCHEMA, + timeline: [ + { type: "clip", id: "c1", video: "v1", start: 10, end: 30, quoteStart: 12, claim: "w01" }, + { type: "clip", id: "c2", video: "v2", start: 0, end: 20, quoteStart: 5, claim: "w02" }, + ], + ledger: [ + base({ id: "w01", date: "2026-09-15", population: "delta", value: -5, display: "-5", entryId: "c1" }), + base({ id: "w02", date: "2026-10-26", population: "current", value: 291.5, display: "291.5 lb", entryId: "c2" }), + base({ id: "w03", date: "2026-10-31", population: "delta", value: -60, display: "-60", qualifier: "≈" }), + base({ id: "w04", date: "2023-03-02", population: "delta", value: -64, display: "-64" }), + base({ id: "w05", date: "2008-06-30", population: "past", asOf: "2008-06-30", value: 368, display: "368 lb" }), + base({ id: "d01", date: "2026-10-01", scope: "drinking", population: "status", value: "dry", event: "start", display: "dry" }), + ], +}; + +async function project() { + const dir = path.join(ROOT, "reports", "weigh"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2)); + return dir; +} +const lines = []; +const run = (cmd, ...args) => cmd(args, { root: path.join(ROOT, "reports"), out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }); +const manifestOf = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + +test("a row is checked against the schema, and every problem is named", () => { + assert.throws(() => ledgerRowOf({ ...MANIFEST, ledgerSchema: undefined }, null, {}), /no measure ledger/); + assert.throws( + () => ledgerRowOf(MANIFEST, null, { id: "w01", date: "soon", scope: "gym", population: "guess", nonsense: 1 }), + /"nonsense" is not a ledger key/, + ); + let e; + try { ledgerRowOf(MANIFEST, null, { id: "w01", date: "soon", scope: "gym", population: "guess" }); } catch (err) { e = String(err.message); } + for (const want of ["already has a row w01", "date must be", "scope must be one of the ledger's tracks: weight, regime, drinking", "population must be one of", "scopeBasis must quote"]) { + assert.ok(e.includes(want), `${want} in: ${e}`); + } + assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "r9", date: "2026-01-01", scope: "regime", population: "status", value: "dry" })), /value on the regime track must be one of its regimes: keto, off; event must be/); + assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "current", value: "heavy" })), /value must be a number/); + assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "current", value: 300, run: 2 })), /run is a loss claim's/); + assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "delta", value: -3, run: 1.5 })), /run must be a whole number/); + assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "p9", date: "2026-01-01", population: "promise_check", promise: "w01" })), /promise must name a promise row \(w01 is a delta row\)/); + assert.throws(() => ledgerRowOf(MANIFEST, null, base({ id: "w9", date: "2026-01-01", population: "current", value: 300, qualifier: "?" })), /qualifier/); + // A sound one: the defaults for three of the six, its display from its value. + const ok = ledgerRowOf(MANIFEST, null, { id: "w9", date: "2026-11-03", scope: "weight", population: "delta", value: -58.2, scopeBasis: "his words" }); + assert.deepEqual([ok.scopeConfidence, ok.valueKind, ok.flags, ok.display], ["read", "uttered", [], "-58.2 lb"]); + assert.equal(parseLedgerValue("value", "-58.2"), -58.2); + assert.equal(parseLedgerValue("retro", "true"), true); + assert.deepEqual(parseLedgerValue("flags", "a|b"), ["a", "b"]); + assert.deepEqual(ledgerRowReferences(MANIFEST, "w01"), ["timeline entry c1 pins it (claim)"]); +}); + +test("umtool ledger: add, set, unset, rm -- through the writers, on the file", async () => { + const dir = await project(); + lines.length = 0; + assert.equal(await run(ledgerCommand, "weigh", "ls", "--scope", "weight"), 0); + assert.match(lines.at(-1), /5 of 6 row\(s\)/); + // The promise, and a later word about it. + assert.equal(await run(ledgerCommand, "weigh", "add", "p01", "--date", "2026-10-23", "--scope", "weight", "--population", "promise", + "--display", "post a video of the scale", "--scopeBasis", "his own post", "--citeUrl", "https://x.com/a/status/1", "--json"), 0, lines.join("\n")); + assert.equal(JSON.parse(lines.at(-1)).added.citeUrl, "https://x.com/a/status/1"); + assert.equal(await run(ledgerCommand, "weigh", "add", "p02", "--date", "2026-11-03", "--scope", "weight", "--population", "promise_check", + "--promise", "p01", "--display", "pull up a video from three months ago", "--scopeBasis", "the scale video"), 0, lines.join("\n")); + // A loss told in the past: off the odometer; then put back on it. + assert.equal(await run(ledgerCommand, "weigh", "set", "w04", "--retro", "true"), 0, lines.join("\n")); + let m = await manifestOf(dir); + assert.equal(m.ledger.find((r) => r.id === "w04").retro, true); + assert.equal(await run(ledgerCommand, "weigh", "set", "w04", "--unset", "retro"), 0); + m = await manifestOf(dir); + assert.equal("retro" in m.ledger.find((r) => r.id === "w04"), false); + // Refused, by name, and nothing written. + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + assert.equal(await run(ledgerCommand, "weigh", "set", "w02", "--run", "3"), 1); + assert.match(lines.at(-1), /ERR umtool ledger: run is a loss claim's/); + assert.equal(await run(ledgerCommand, "weigh", "rm", "p01"), 1); + assert.match(lines.at(-1), /p01 is still named: row p02 checks it/); + assert.equal(await run(ledgerCommand, "weigh", "rm", "w01"), 1); + assert.match(lines.at(-1), /timeline entry c1 pins it/); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before); + assert.equal(await run(ledgerCommand, "weigh", "rm", "p02"), 0); + m = await manifestOf(dir); + assert.equal(m.ledger.some((r) => r.id === "p02"), false); +}); + +test("umtool measure: the slice, scoped, with the odometer by his words", async () => { + await project(); + assert.equal(await run(ledgerCommand, "weigh", "set", "w04", "--retro", "true"), 0); + assert.equal(await run(ledgerCommand, "weigh", "add", "w06", "--date", "2026-11-03", "--scope", "weight", "--population", "delta", "--value", "-58.2", "--scopeBasis", "his words"), 0); + lines.length = 0; + assert.equal(await run(measureCommand, "weigh", "--scopes", "weight,regime", "--as-of", "2026-11-05", "--json"), 0, lines.join("\n")); + const sl = JSON.parse(lines.join("\n")); + assert.deepEqual(sl.scopes, ["weight", "regime"]); + assert.equal(sl.asOfRender, "2026-11-05"); + assert.deepEqual(sl.events.map((e) => [e.row, e.tFrom]), [["w01", "quote"], ["w02", "quote"]]); + assert.ok(![...sl.events, ...sl.hidden].some((e) => e.row === "d01"), "drinking is out of scope"); + // One run: 5, then 60, then 58.2 -- its peak stays 60; the retro 64 is not counted. + assert.equal(sl.totals.runs, 1); + assert.equal(sl.totals.lost, 60); + assert.deepEqual(sl.totals.net, { from: 368, to: 291.5, value: -76.5, fromRow: "w05", toRow: "w02" }); + lines.length = 0; + assert.equal(await run(measureCommand, "weigh", "--scopes", "weight,regime"), 0); + assert.match(lines.join("\n"), /lost \(his words\): 60 lb across 1 run\(s\)/); + assert.equal(await run(measureCommand, "weigh", "--scopes", "gym"), 1); + assert.match(lines.at(-1), /"gym" is not a track/); +}); diff --git a/umtool/lib/report/ledgerRows.mjs b/umtool/lib/report/ledgerRows.mjs @@ -0,0 +1,182 @@ +// 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) and `promise_check` (a later word +// about it, naming the promise in `promise`); `kept: true` on either. +import { + EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, SCOPE_CONFIDENCE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields, +} from "umtool-report-to-video/ledger-totals"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const DATE_RE = /^\d{4}(?:-\d{2}(?:-\d{2})?)?$/; +const DAY_RE = /^\d{4}-\d{2}-\d{2}$/; +const ID_RE = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/; + +/** The forms whose value is a number in the schema's unit. */ +const NUMERIC_FORMS = new Set(["current", "past", "delta", "goal", "goal_loss", "overweight_by"]); + +/** Each built-in key's type: what a CLI flag's text is parsed as, and what is checked. */ +export const LEDGER_KEY_TYPES = Object.freeze({ + id: "id", date: "date", asOf: "date?", scope: "text", population: "text", value: "value", event: "text?", + display: "text?", label: "text?", quote: "text?", deadline: "text?", src: "text?", channel: "text?", video: "text?", + cite: "seconds?", citeFrom: "text?", scopeBasis: "text", scopeConfidence: "text", valueKind: "text", flags: "list", + hedged: "bool?", unsourced: "bool?", plotted: "bool?", hidden: "bool?", entryId: "text?", authorNote: "text?", + run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", +}); + +/** Is this manifest's ledger a measure ledger (the one these writers write)? */ +export const isMeasureLedger = (manifest) => isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure"; + +/** + * A flag's text as the value of `key`: a number for a number key ("null" + * clears), true/false for a boolean, a list split on "|" for `flags`, a + * number for `value` when it reads as one. Declared fields are left as text + * (validateFields types them). + */ +export function parseLedgerValue(key, text) { + const t = String(text); + if (t === "null") return null; + const type = LEDGER_KEY_TYPES[key]; + if (type === "bool?") { + if (t === "true") return true; + if (t === "false") return false; + return t; + } + if (type === "seconds?" || type === "run?") return /^-?\d+(?:\.\d+)?$/.test(t) ? Number(t) : t; + if (type === "value") return /^[-+]?\d+(?:\.\d+)?$/.test(t) ? Number(t) : t; + if (type === "list") return t === "" ? [] : t.split("|").map((s) => s.trim()).filter(Boolean); + return t; +} + +/** + * The row `patch` makes of `base` (null for a new row), checked and + * normalised -- or a thrown sentence naming every problem. `unset` lists the + * keys to remove. A new row gets the boring answer for three of the six + * (`scopeConfidence` read, `valueKind` uttered, `flags` []) and its display + * from its value; `scopeBasis` is never defaulted (a ruling with no basis is + * an opinion). + * + * @param {object} manifest + * @param {Record<string, unknown> | null} base the row as it stands, or null + * @param {Record<string, unknown>} patch + * @param {{ unset?: string[] }} [opts] + * @returns {Record<string, unknown>} + */ +export function ledgerRowOf(manifest, base, patch, { unset = [] } = {}) { + if (!isMeasureLedger(manifest)) throw new Error('the manifest has no measure ledger (ledgerSchema.kind "measure")'); + const schema = measureSchema(manifest.ledgerSchema); + const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : []; + const declared = new Map(schema.fields.map((f) => [f.key, f])); + const errors = []; + for (const k of [...Object.keys(patch ?? {}), ...unset]) { + if (!LEDGER_BUILTIN_KEYS.has(k) && !declared.has(k)) { + errors.push(`"${k}" is not a ledger key (the built-ins, or the schema's fields: ${[...declared.keys()].join(", ") || "none"})`); + } + } + for (const k of unset) if (["id", "date", "scope", "population", "scopeBasis", "scopeConfidence", "valueKind", "flags"].includes(k)) errors.push(`"${k}" cannot be unset: every row has one`); + if (errors.length) throw new Error(errors.join("; ")); + + const builtins = Object.fromEntries(Object.entries(patch ?? {}).filter(([k]) => LEDGER_BUILTIN_KEYS.has(k))); + const fieldPatch = Object.fromEntries(Object.entries(patch ?? {}).filter(([k]) => declared.has(k))); + const row = { ...(base ?? {}), ...builtins }; + for (const k of unset) delete row[k]; + if (!base) { + row.scopeConfidence ??= "read"; + row.valueKind ??= "uttered"; + row.flags ??= []; + } + + // ---- the built-ins, each against its type ---- + if (!ID_RE.test(String(row.id ?? ""))) errors.push("id must be a letter, then letters, digits, dots, colons, dashes or underscores (at most 64)"); + else if (!base && ledger.some((r) => r?.id === row.id)) errors.push(`the ledger already has a row ${row.id}`); + if (!DATE_RE.test(String(row.date ?? ""))) errors.push("date must be YYYY-MM-DD (or YYYY-MM, YYYY)"); + if (row.asOf !== undefined && row.asOf !== null && !DATE_RE.test(String(row.asOf))) errors.push("asOf must be a date, or null"); + const track = schema.tracks.find((t) => t.key === row.scope) ?? null; + if (!track) errors.push(`scope must be one of the ledger's tracks: ${schema.tracks.map((t) => t.key).join(", ")}`); + if (!schema.forms.includes(row.population)) errors.push(`population must be one of ${schema.forms.join(", ")}`); + const promiseForm = PROMISE_FORMS.includes(row.population); + if (track?.role === "regime") { + const allowed = track.regimes ?? schema.regimes.map((r) => r.key); + if (!allowed.includes(String(row.value))) errors.push(`value on the ${track.key} track must be one of its regimes: ${allowed.join(", ")}`); + if (!EVENTS.includes(row.event)) errors.push(`event must be one of ${EVENTS.join(", ")} on a regime track`); + } else if (track) { + if (NUMERIC_FORMS.has(row.population) && !Number.isFinite(row.value)) errors.push(`value must be a number (in ${schema.unit || "the ledger's unit"}) for a ${row.population} row`); + if (promiseForm && row.value !== undefined && row.value !== null) errors.push(`a ${row.population} row has no value (its words are its display)`); + if (row.event !== undefined && row.event !== null) errors.push("event is a regime track's"); + } + for (const [k, type] of Object.entries(LEDGER_KEY_TYPES)) { + const v = row[k]; + if (v === undefined || v === null) continue; + if (type.startsWith("text") && typeof v !== "string") errors.push(`${k} must be text`); + if (type === "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 && !promiseForm) errors.push("kept is a promise's (a promise or promise_check row)"); + if (row.population === "promise_check") { + const p = ledger.find((r) => r?.id === row.promise); + if (!row.promise) errors.push("a promise_check names its promise (--promise <row id>)"); + else if (!p || p.population !== "promise") errors.push(`promise must name a promise row (${row.promise} is ${p ? `a ${p.population} row` : "not in the ledger"})`); + } else if (row.promise !== undefined && row.promise !== null) errors.push("promise is a promise_check's"); + if (row.entryId !== undefined && row.entryId !== null && !(manifest.timeline ?? []).some((e) => e?.id === row.entryId)) { + errors.push(`entryId ${row.entryId} is not an entry of the timeline`); + } + if (errors.length) throw new Error(errors.join("; ")); + + // ---- the declared fields (validateFields types and scopes them) ---- + try { + const { set, clear } = validateFields(row, fieldPatch, schema, ledger); + Object.assign(row, set); + for (const k of clear) delete row[k]; + } catch (err) { + throw new Error(err instanceof Error ? err.message : String(err)); + } + for (const k of unset) if (declared.has(k)) delete row[k]; + + if (row.display === undefined || row.display === null || row.display === "") { + row.display = measureDisplay({ ...row, display: null }, schema); + } + const gaps = measureGaps(row, schema); + if (gaps.length) throw new Error(`the row is not adjudicated: ${gaps.join(", ")}`); + return row; +} + +/** + * What still names a row -- the timeline entries that pin it (`claim: "<id>"`) + * and the rows that refer to it (`promise`, a declared rowRef field) -- for + * `rm` to refuse with. + * + * @returns {string[]} + */ +export function ledgerRowReferences(manifest, id) { + const out = []; + for (const e of manifest.timeline ?? []) if (typeof e?.claim === "string" && e.claim.trim() === id) out.push(`timeline entry ${e.id} pins it (claim)`); + const refs = isMeasureLedger(manifest) ? measureSchema(manifest.ledgerSchema).fields.filter((f) => f.kind === "rowRef").map((f) => f.key) : []; + for (const r of manifest.ledger ?? []) { + if (!isObj(r) || r.id === id) continue; + if (r.promise === id) out.push(`row ${r.id} checks it (promise)`); + for (const k of refs) if (r[k] === id) out.push(`row ${r.id} refers to it (${k})`); + } + return out; +} diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -67,6 +67,7 @@ import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umto import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration"; import { termWords, validatePostsRender } from "umtool-report-to-video/post-redact"; import { parseMuteFrom } from "./playback.mjs"; +import { isMeasureLedger, ledgerRowOf, ledgerRowReferences } from "./ledgerRows.mjs"; import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs"; import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources"; import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs"; @@ -1270,6 +1271,79 @@ export async function updateClaim(dir, claimId, patch, { token = null } = {}) { // --------------------------------------------------------------------------- +// A MEASURE ledger's rows (weight video rev 9): added, patched and removed +// whole, through ledgerRows.mjs's checks -- the one way a row gets into the +// ledger the instruments draw from (`umtool ledger <p> add|set|rm`). +// --------------------------------------------------------------------------- + +/** + * Add one row to a measure ledger, checked (ledgerRows.mjs ledgerRowOf). + * + * @param {string} dir + * @param {Record<string, unknown>} row + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ row: Record<string, unknown>, token: string | null }>} + */ +export async function addLedgerRow(dir, row, { token = null } = {}) { + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const made = ledgerRowOf(manifest, null, row); + manifest.ledger = [...(Array.isArray(manifest.ledger) ? manifest.ledger : []), made]; + return { row: made, token: await writeManifestAtomic(dir, manifest) }; + }); +} + +/** + * Patch one row of a measure ledger: `patch` sets keys, `unset` removes them; + * the row that results is checked whole. + * + * @param {string} dir + * @param {string} id + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null, unset?: string[] }} [opts] + */ +export async function updateLedgerRow(dir, id, patch, { token = null, unset = [] } = {}) { + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : []; + const i = ledger.findIndex((r) => r?.id === id); + if (i < 0) throw new Error(`no ledger row ${id}`); + if (patch.id !== undefined && patch.id !== id) throw new Error("a row's id is not changed by set (add the new row, then rm the old)"); + const made = ledgerRowOf(manifest, ledger[i], patch, { unset }); + ledger[i] = made; + return { row: made, token: await writeManifestAtomic(dir, manifest) }; + }); +} + +/** + * Remove one row of a measure ledger. Refused while anything names it -- a + * timeline entry's pin, a check of a promise, a declared row reference. + * + * @param {string} dir + * @param {string} id + * @param {{ token?: string | null }} [opts] + */ +export async function removeLedgerRow(dir, id, { token = null } = {}) { + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + if (!isMeasureLedger(manifest)) throw new Error('the manifest has no measure ledger (ledgerSchema.kind "measure")'); + const ledger = Array.isArray(manifest.ledger) ? manifest.ledger : []; + const row = ledger.find((r) => r?.id === id); + if (!row) throw new Error(`no ledger row ${id}`); + const refs = ledgerRowReferences(manifest, id); + if (refs.length) throw new Error(`${id} is still named: ${refs.join("; ")}`); + manifest.ledger = ledger.filter((r) => r?.id !== id); + return { row, token: await writeManifestAtomic(dir, manifest) }; + }); +} + +// --------------------------------------------------------------------------- // The DECK: per-entry on-screen text, and the render.chrome block that turns // the deck on. // diff --git a/umtool/lib/report/measureCli.mjs b/umtool/lib/report/measureCli.mjs @@ -0,0 +1,130 @@ +// `umtool measure` (weight video rev 9): the measure slice a cut's +// instruments would draw from (report-to-video measure-slice.mjs), printed -- +// every event at its cut second, the hidden rows, and the totals. Reads only. +// +// umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json] +// +// The cut's seconds: the take's built schedule (takes/<t>/out/sourced/ +// schedule.json) when there is one, else an estimate from the manifest. Each +// figure is timed by its clip's words (measure-words.mjs: the project's +// channels tree, then the corpus) -- read off disk, never fetched. +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { CHANNELS_DIR } from "../paths.mjs"; +import { resolveTakeManifest, takePlayDir } from "./takeManifest.mjs"; +import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; +import { estimateSchedule, playWindow } from "umtool-report-to-video/deck"; +import { renderGaps } from "umtool-report-to-video/gaps"; +import { measureSlice, pinnedRows } from "umtool-report-to-video/measure-slice"; +import { measureClipWords } from "umtool-report-to-video/measure-words"; +import { SHADOW_CHANNELS, channelsDirFor } from "umtool-report-to-video/sources"; + +export const MEASURE_USAGE = [ + "usage: umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]", + "", + "The measure slice of the cut (render.chrome.deck.measure; --scopes / --scale / --as-of override it): every ledger row", + "in scope the cut shows, at the cut second its figure is said (its clip's words; else the quote's start),", + "the rows no entry shows, the state after each, and the totals -- the odometer's runs (the highest real-time", + "loss claim of each run, summed), NET, the goals, the diets, the promises. The cut's seconds are the take's", + "built schedule.json with --take, else an estimate. --json prints the slice itself.", +].join("\n"); + +class CliError extends Error {} + +const exists = (p) => stat(p).then(() => true, () => false); +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const clock = (t) => { + const s = Math.max(0, Math.round(t)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +}; + +/** + * @param {string[]} args the words after `measure` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, channelsDir?: string }} [opts] + * @returns {Promise<number>} the exit code + */ +export async function measureCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), channelsDir = CHANNELS_DIR } = {}) { + const valued = new Set(["--take", "--scopes", "--scale", "--as-of"]); + const flags = new Map(); + const words = []; + for (let i = 0; i < args.length; i += 1) { + if (valued.has(args[i])) { flags.set(args[i], args[i + 1] ?? ""); i += 1; } else if (!args[i].startsWith("--")) words.push(args[i]); + } + const json = args.includes("--json"); + try { + const [projectArg] = words; + if (!projectArg || args.includes("--help")) { + err(MEASURE_USAGE); + return 2; + } + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + const take = flags.get("--take") ?? null; + const base = take ? (await resolveTakeManifest(project.dir, take)).manifest : await readManifest(project.dir); + if (!base) throw new CliError(`${project.id} has no manifest`); + if (!isObj(base.ledgerSchema) || base.ledgerSchema.kind !== "measure") throw new CliError(`${project.id} has no measure ledger (ledgerSchema.kind "measure")`); + + // The settings the slice is made with: the manifest's, with the flags over them. + const m = JSON.parse(JSON.stringify(base)); + m.render = isObj(m.render) ? m.render : {}; + const chrome = isObj(m.render.chrome) ? m.render.chrome : { engine: "hyperframes", layout: "deck", deck: {} }; + const deck = isObj(chrome.deck) ? chrome.deck : {}; + const measure = { ...(isObj(deck.measure) ? deck.measure : {}) }; + if (flags.has("--scopes")) measure.scopes = String(flags.get("--scopes")).split(",").map((s) => s.trim()).filter(Boolean); + if (flags.has("--as-of")) measure.asOf = flags.get("--as-of"); + if (flags.has("--scale")) { + const m2 = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(flags.get("--scale"))); + if (!m2) throw new CliError("--scale is MIN-MAX, in the ledger's unit (220-400)"); + measure.scale = { min: Number(m2[1]), max: Number(m2[2]) }; + } + m.render.chrome = { ...chrome, layout: "deck", deck: { ...deck, measure } }; + const cut = selectVariant(m, DEFAULT_VARIANT); + const entries = cut.timeline ?? []; + + // The cut's seconds: the take's built schedule, else an estimate. + let schedule = null; + let from = "an estimate from the manifest"; + if (take) { + const p = path.join(takePlayDir(project.dir, take), "out", DEFAULT_VARIANT, "schedule.json"); + const doc = await readFile(p, "utf8").then((t) => JSON.parse(t), () => null); + if (Array.isArray(doc?.segments)) { schedule = doc; from = `take ${take}'s schedule.json`; } + } + if (!schedule) schedule = estimateSchedule(cut); + + const ledger = cut.measureLedger ?? base.ledger ?? []; + const ids = new Set(pinnedRows(entries, ledger).keys()); + const own = channelsDirFor(project.dir, base, { shadowExists: await exists(path.join(project.dir, SHADOW_CHANNELS)) }); + const wordsOf = await measureClipWords({ entries, ids, provenance: base.provenance ?? {}, channelsDirs: [own, channelsDir] }); + const clk = new Map(entries.filter((e) => e.type === "clip").map((e) => [e.id, playWindow(e, cut.render).from])); + const gaps = new Map(entries.filter((e) => e.type === "clip" && renderGaps(e, cut.render).length).map((e) => [e.id, renderGaps(e, cut.render)])); + const slice = measureSlice({ ...cut, ledger }, schedule, { words: wordsOf, clock: clk, gaps, asOf: measure.asOf ?? null }); + + if (json) { + out(JSON.stringify(slice, null, 2)); + return 0; + } + const by = slice.events.reduce((a, e) => ((a[e.tFrom] = (a[e.tFrom] ?? 0) + 1), a), {}); + out(`${project.id}${take ? ` · take ${take}` : ""} · the cut's seconds: ${from}`); + out(`scopes ${slice.scopes.join(", ")} · scale ${slice.scale.min}–${slice.scale.max} ${slice.unit} · as of ${slice.asOfRender}`); + out(`${slice.events.length} event(s) on camera (timed by: ${Object.entries(by).map(([k, n]) => `${k} ${n}`).join(", ")}) · ${slice.hidden.length} hidden`); + out(""); + for (const e of slice.events) { + out(` ${clock(e.t).padStart(6)} ${String(e.row).padEnd(6)} ${String(e.kind).padEnd(12)} ${String(e.display ?? "").padEnd(24)} ${e.run !== null ? `run ${e.run}`.padEnd(7) : "".padEnd(7)} ${String(e.tFrom).padEnd(7)} ${e.segment}`); + } + const t = slice.totals; + out(""); + out(`lost (his words): ${t.lost} ${slice.unit} across ${t.runs} run(s) — ${t.lostRuns.map((x) => `${x.start} ${x.peak} (${x.row})`).join(" · ")}`); + out(`net: ${t.net.from ?? "—"} → ${t.net.to ?? "—"} = ${t.net.value ?? "—"} ${slice.unit} (${t.net.fromRow ?? "—"} → ${t.net.toRow ?? "—"})`); + out(`goals: ${t.goals}${Object.keys(t.goalRepeats).length ? ` (${Object.entries(t.goalRepeats).map(([k, n]) => `"${k}" ×${n}`).join(", ")})` : ""} · diets: ${t.diets} · peak drift: ${t.peakDrift.join(" → ") || "—"} · under 300: ${t.under300.said}${t.under300.rows.length ? ` (${t.under300.rows.join(", ")})` : ""}`); + for (const p of t.promises) out(`promise ${p.row}, said ${p.said}: "${p.what}"${p.due ? ` · due ${p.due}` : ""} · ${p.kept ? "KEPT" : "not kept"}${p.checks.length ? ` · checked ${p.checks.join(", ")}` : ""}`); + out(`span: ${t.span.from ?? "—"} → ${t.span.to ?? "—"}`); + return 0; + } catch (e) { + err(`umtool measure: ${e instanceof Error ? e.message : String(e)}`); + return 1; + } +} diff --git a/umtool/report-to-video/ledger-shared.mjs b/umtool/report-to-video/ledger-shared.mjs @@ -94,4 +94,9 @@ export const LEDGER_BUILTIN_KEYS = new Set([ "scopeBasis", "scopeConfidence", "valueKind", "flags", "hedged", "unsourced", // the cut "entryId", "plotted", "hidden", "authorNote", + // the measure instruments (measure-slice.mjs): a loss claim's run (his + // words placing it), a loss told in the past with no asOf to give it + // (`retro`), a promise check's promise, whether it was kept, and a day a + // goal or a promise is due + "run", "retro", "promise", "kept", "due", ]); diff --git a/umtool/report-to-video/ledger-totals.mjs b/umtool/report-to-video/ledger-totals.mjs @@ -51,10 +51,12 @@ export { EVENTS, MEASURE_PREDICATES, MEASURE_THRESHOLDS, + PROMISE_FORMS, allRegimeGaps, freshestReading, goalAbsolute, measureDisplay, + measureGaps, measureQualifier, measureSchema, measureScoreboard, diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs @@ -21,14 +21,13 @@ // // The odometer rule (ruled 5 Nov 2026, "go by his words"): see lossRuns. import { chronological, dateKey, daysBetween } from "./ledger-shared.mjs"; -import { measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs"; +import { PROMISE_FORMS, measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs"; import { goalCell, nextRegime, offOf } from "./panel-model.mjs"; import { offsetIn } from "./gaps.mjs"; export const MEASURE_SLICE_VERSION = 1; -/** The populations a promise is written in: what he says he will do, and a later word about it. */ -export const PROMISE_FORMS = Object.freeze(["promise", "promise_check"]); +export { PROMISE_FORMS }; /** `render.chrome.deck.measure`'s keys. */ export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf"]); diff --git a/umtool/report-to-video/measure-totals.mjs b/umtool/report-to-video/measure-totals.mjs @@ -82,6 +82,14 @@ export function offCloses(openKey, named, offKey = null) { /** 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 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), + * and `promise_check`, a later statement about it (`promise` names the row; + * `kept: true` on either says it was kept). Built into every measure schema. + */ +export const PROMISE_FORMS = ["promise", "promise_check"]; + /** The two forms that are a reading of the quantity itself, so they plot. */ export const PLOTTING_FORMS = new Set(["current", "past"]); @@ -394,7 +402,10 @@ export function measureSchema(schema) { from: s.from ?? null, to: s.to ?? null, tracks, - forms: s.forms?.length ? s.forms.map(String) : DEFAULT_FORMS, + // 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. diff --git a/umtool/report-to-video/measure-totals.test.mjs b/umtool/report-to-video/measure-totals.test.mjs @@ -137,7 +137,8 @@ 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"]); + // The schema's forms, then the promise forms every measure ledger carries. + assert.deepEqual(v.populations, ["current", "past", "delta", "goal", "overweight_by", "status", "promise", "promise_check"]); assert.deepEqual(v.events, EVENTS); assert.deepEqual(v.regimes, ["keto", "carnivore", "off"]); assert.equal(v.unit, "lb"); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -48,6 +48,8 @@ "./gaps": "./gaps.mjs", "./ladder-chunks": "./ladder-chunks.mjs", "./ledger-totals": "./ledger-totals.mjs", + "./measure-slice": "./measure-slice.mjs", + "./measure-words": "./measure-words.mjs", "./montage": "./montage.mjs", "./montage-styles": "./montage-styles.mjs", "./montage-rulings": "./montage-rulings.mjs",