Archilyzer · Source

archilyzer

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

commit 74f2fd79620456e52e308073b4ad0b91d34a7167
parent 1b1290699e30d56a04ad8178906d316615a747f7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 23:56:30 -0400

umtool: piece ids, the lifecycle store, and the inbox's grouping (pure, tested)

lib/pieces/ids.mjs: a:<site>/<report>, p:<project>, c:<case> (reserved), never
ambiguous. lib/lifecycle.mjs: active | parked | done in
REPORTS_ROOT/.umtool/lifecycle.json, {at, by?} per piece, atomic and
serialised, an unreadable file never overwritten. lib/inbox/groups.mjs: each
decision's category, group, one action and hidden flag, the ranking, and the
per-group cards.

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

Diffstat:
Aumtool/lib/inbox/groups.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/groups.test.mjs | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/lifecycle.mjs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/lifecycle.test.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/lifecycle.ts | 35+++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces/ids.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces/ids.test.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 724 insertions(+), 0 deletions(-)

diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -0,0 +1,218 @@ +// THE INBOX'S ORDER: which group a decision is in, how the groups rank, and +// the one action each offers (plans/umtool-redesign.md, "Target information +// architecture", Inbox). Pure functions over decision rows -- no disk, no +// clock -- so the ranking is unit-tested and the API, the CLI and (P3) the page +// share one definition. +// +// GROUPS, in order: +// +// your-call research proposals, then failed runs: money is waiting +// on a yes or no ("spend") +// review a finished iteration that is not current (r28's drafts +// join here in P2b) +// blocking something downstream would lie, on an ACTIVE piece +// notes the operator's open notes +// open every other open decision (a variant with no verdict, a +// link only the operator can choose, …) +// ready-to-finish a piece that looks done: mark it done, or keep it going +// quiet true facts that are not decisions; collapsed +// +// A decision on a PARKED or DONE piece keeps its group and is `hidden`. The +// API never drops it (one row per decision, the MCP reads every row); the +// inbox shows a hidden count instead of the rows. + +export const GROUPS = [ + { id: "your-call", label: "Your call", collapsed: false }, + { id: "review", label: "Review", collapsed: false }, + { id: "blocking", label: "Blocking", collapsed: false }, + { id: "notes", label: "Notes", collapsed: false }, + { id: "open", label: "Open", collapsed: false }, + { id: "ready-to-finish", label: "Ready to finish", collapsed: false }, + { id: "quiet", label: "Quiet", collapsed: true }, +]; +export const GROUP_IDS = GROUPS.map((g) => g.id); + +/** + * A decision's CATEGORY: what kind of thing it is, independent of where it + * sits. `spend` is research proposals plus failed runs (there is no "waiting + * on a cap" state: the daily cap refuses at start, a per-job cap ends the run). + */ +export const CATEGORIES = ["spend", "review", "fix", "note", "choose", "finish", "info"]; + +const KIND_CATEGORY = { + "research-proposal": "spend", + "iteration-failed": "spend", + "iteration-ready": "review", + "open-note": "note", + "unreadable-notes": "fix", + "link-ambiguous": "choose", + "looks-done": "finish", +}; + +const CATEGORY_GROUP = { + spend: "your-call", + review: "review", + fix: "blocking", + note: "notes", + choose: "open", + finish: "ready-to-finish", + info: "quiet", +}; + +/** @param {{ kind: string, severity: string }} d */ +export function categoryOf(d) { + const named = KIND_CATEGORY[d.kind]; + if (named) return named; + return d.severity === "blocking" ? "fix" : d.severity === "open" ? "choose" : "info"; +} + +/** @param {{ kind: string, severity: string }} d */ +export function groupOf(d) { + // Information is quiet whatever its kind: a fact is not a decision. + if (d.severity === "info") return "quiet"; + return CATEGORY_GROUP[categoryOf(d)]; +} + +// Within a group: the brief's order first (proposals before failed runs), then +// everything else as equals. +const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "unreadable-notes": 0 }; +const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; + +// ONE primary action per decision, its button copy naming the result. +const ACTION_LABEL = { + "research-proposal": "Approve acquisition", + "iteration-failed": "Retry run", + "iteration-ready": (d) => `Make ${d.target} current`, + "open-note": "Answer note", + "unreadable-notes": "Repair notes.json", + "link-ambiguous": "Link the video", + "looks-done": "Mark done", + "claim-unadjudicated": "Adjudicate claim", + "claim-incoherent": "Rule on the flag", + "clip-no-cues": "Fix the cue source", + "clip-unfetchable": "Replace the source", + "clip-mid-sentence": "Trim to the sentence", + "clip-cue-gap": "Fix the window", + "clip-cut-outside": "Fix the cut", + "window-overlap": "Fix the windows", + "no-punctuation": "Check the windows", + "manifest-invalid": "Fix the manifest", + "stale-build": "Rebuild the video", + unbuilt: "Build the video", + "storage-unreachable": "Reconnect the media drive", + "storage-mismatch": "Settle the storage", + "unjudged-variant": "Judge variant", + "missing-cut": "Ship the cut", + "stale-recipe": "Record the recipe", + "no-recipe": "Record the recipe", + "spec-problem": "Fix the spec", + "no-plan": "Name the plan", + unattributed: "Attribute variant", + "thumb-unaccepted": "Accept a cover", + loudness: "Re-render at the target", + "shadowed-name": "Rename the project", + "unroutable-name": "Rename the project", + "ambiguous-project": "Fix the project's files", +}; + +const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" }; + +/** + * The decision's one action: `{ label, href }`. The href is the decision's + * own, untouched -- a note's still ends in `note=<id>` (the MCP relies on it). + * + * @param {{ kind: string, severity: string, target: string, href: string }} d + */ +export function actionOf(d) { + const named = ACTION_LABEL[d.kind]; + const label = typeof named === "function" ? named(d) : (named ?? CATEGORY_LABEL[categoryOf(d)]); + return { label, href: d.href }; +} + +/** + * Add the inbox's fields to each row: `piece`, `category`, `group`, `action`, + * `lifecycle`, `hidden`. Never drops or merges a row. + * + * @template {{ kind: string, severity: string, target: string, href: string, project: string }} D + * @param {D[]} items + * @param {{ pieceOf: (d: D) => string | null, lifecycleOf: (piece: string) => string }} how + */ +export function annotate(items, { pieceOf, lifecycleOf }) { + return items.map((d) => { + const piece = d.piece ?? pieceOf(d); + const lifecycle = piece ? lifecycleOf(piece) : "active"; + return { + ...d, + ...(piece ? { piece } : {}), + category: categoryOf(d), + group: groupOf(d), + action: actionOf(d), + lifecycle, + hidden: lifecycle === "parked" || lifecycle === "done", + }; + }); +} + +/** + * The inbox's order: visible before hidden, then by group, then the kind's + * rank in its group, then severity, then newest first. Stable for equals (by + * piece, kind, target), so two reads of the same disk give the same list. + */ +export function rankDecisions(items) { + const g = (d) => GROUP_IDS.indexOf(d.group ?? groupOf(d)); + return [...items].sort( + (a, b) => + Number(!!a.hidden) - Number(!!b.hidden) || + g(a) - g(b) || + (KIND_RANK[a.kind] ?? 9) - (KIND_RANK[b.kind] ?? 9) || + (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3) || + (b.at ?? 0) - (a.at ?? 0) || + String(a.piece ?? a.project).localeCompare(String(b.piece ?? b.project)) || + a.kind.localeCompare(b.kind) || + String(a.target).localeCompare(String(b.target)), + ); +} + +/** + * The grouped summary, for a page or a terminal: per group, its CARDS (one per + * piece and kind -- 483 unadjudicated claims on one video are one card), how + * many decisions they hold, and how many are hidden. Rows are counted, never + * dropped: `decisions + hidden` over every group is `items.length`. + * + * @param {Array<Record<string, any>>} items annotated rows + */ +export function summarizeGroups(items) { + const ranked = rankDecisions(items); + const out = GROUPS.map((g) => ({ ...g, decisions: 0, hidden: 0, cards: [] })); + const byId = new Map(out.map((g) => [g.id, g])); + const cardOf = new Map(); + for (const d of ranked) { + const group = byId.get(d.group ?? groupOf(d)); + if (d.hidden) { + group.hidden += 1; + continue; + } + group.decisions += 1; + const key = `${group.id}\u0000${d.piece ?? d.project}\u0000${d.kind}`; + let card = cardOf.get(key); + if (!card) { + card = { + piece: d.piece ?? null, + project: d.project, + title: d.projectTitle ?? d.project, + kind: d.kind, + severity: d.severity, + count: 0, + why: d.why, + action: d.action ?? actionOf(d), + at: d.at ?? 0, + }; + cardOf.set(key, card); + group.cards.push(card); + } + card.count += 1; + if ((SEVERITY_RANK[d.severity] ?? 3) < (SEVERITY_RANK[card.severity] ?? 3)) card.severity = d.severity; + card.at = Math.max(card.at, d.at ?? 0); + } + return out; +} diff --git a/umtool/lib/inbox/groups.test.mjs b/umtool/lib/inbox/groups.test.mjs @@ -0,0 +1,114 @@ +// The inbox's grouping and ranking: pure, over hand-made rows. +import assert from "node:assert/strict"; +import test from "node:test"; +import { GROUP_IDS, actionOf, annotate, categoryOf, groupOf, rankDecisions, summarizeGroups } from "./groups.mjs"; + +const row = (kind, severity, extra = {}) => ({ + kind, + severity, + project: extra.project ?? "proj", + target: extra.target ?? "t", + why: extra.why ?? `${kind} why`, + href: extra.href ?? "/browse/proj", + at: extra.at ?? 0, + ...extra, +}); + +test("each kind lands in its group, in the brief's order", () => { + const cases = [ + ["research-proposal", "open", "your-call", "spend"], + ["iteration-failed", "open", "your-call", "spend"], + ["iteration-ready", "open", "review", "review"], + ["claim-unadjudicated", "blocking", "blocking", "fix"], + ["unreadable-notes", "blocking", "blocking", "fix"], + ["open-note", "open", "notes", "note"], + ["link-ambiguous", "open", "open", "choose"], + ["unjudged-variant", "open", "open", "choose"], + ["looks-done", "open", "ready-to-finish", "finish"], + ["loudness", "info", "quiet", "info"], + ["unbuilt", "info", "quiet", "info"], + ]; + for (const [kind, severity, group, category] of cases) { + assert.equal(groupOf({ kind, severity }), group, kind); + assert.equal(categoryOf({ kind, severity }), category, kind); + } + assert.deepEqual(GROUP_IDS, ["your-call", "review", "blocking", "notes", "open", "ready-to-finish", "quiet"]); +}); + +test("ranking: group order, proposals before failed runs, newest first, hidden last", () => { + const items = annotate( + [ + row("loudness", "info", { at: 9 }), + row("looks-done", "open", { at: 8 }), + row("open-note", "open", { at: 7 }), + row("claim-unadjudicated", "blocking", { at: 1, project: "old" }), + row("claim-unadjudicated", "blocking", { at: 5, project: "new" }), + row("iteration-ready", "open", { at: 6 }), + row("iteration-failed", "open", { at: 10 }), + row("research-proposal", "open", { at: 2 }), + row("clip-no-cues", "blocking", { at: 99, project: "parked-one" }), + ], + { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:parked-one" ? "parked" : "active") }, + ); + const ranked = rankDecisions(items).map((d) => `${d.kind}:${d.project}`); + assert.deepEqual(ranked, [ + "research-proposal:proj", + "iteration-failed:proj", + "iteration-ready:proj", + "claim-unadjudicated:new", + "claim-unadjudicated:old", + "open-note:proj", + "looks-done:proj", + "loudness:proj", + "clip-no-cues:parked-one", + ]); +}); + +test("annotate adds the fields and never drops, merges or reorders a row", () => { + const input = [row("open-note", "open", { href: "/sites/priv/x?note=n1" }), row("clip-no-cues", "blocking", { project: "gone" })]; + const out = annotate(input, { pieceOf: (d) => (d.project === "gone" ? null : "a:priv/x"), lifecycleOf: () => "done" }); + assert.equal(out.length, 2); + assert.equal(out[0].piece, "a:priv/x"); + assert.equal(out[0].lifecycle, "done"); + assert.equal(out[0].hidden, true); + // A note's action keeps its href, `note=<id>` last. + assert.deepEqual(out[0].action, { label: "Answer note", href: "/sites/priv/x?note=n1" }); + assert.match(out[0].href, /note=n1$/); + // No piece: active, not hidden, no piece key. + assert.equal("piece" in out[1], false); + assert.equal(out[1].lifecycle, "active"); + assert.equal(out[1].hidden, false); + // A piece already on the row wins. + assert.equal(annotate([row("x", "open", { piece: "p:keep" })], { pieceOf: () => "p:other", lifecycleOf: () => "active" })[0].piece, "p:keep"); +}); + +test("an action names its result; an iteration's names the iteration", () => { + assert.equal(actionOf(row("iteration-ready", "open", { target: "i3" })).label, "Make i3 current"); + assert.equal(actionOf(row("looks-done", "open")).label, "Mark done"); + assert.equal(actionOf(row("never-heard-of-it", "blocking")).label, "Fix it"); + assert.equal(actionOf(row("never-heard-of-it", "info")).label, "Open"); +}); + +test("the summary: one card per piece and kind, counts that add up, hidden counted", () => { + const claims = Array.from({ length: 483 }, (_, i) => row("claim-unadjudicated", "blocking", { project: "quartering-diet", target: `c${i}`, at: i })); + const items = annotate( + [...claims, row("clip-no-cues", "blocking", { project: "other" }), row("open-note", "open", { project: "parked" }), row("loudness", "info")], + { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:parked" ? "parked" : "active") }, + ); + const groups = summarizeGroups(items); + const blocking = groups.find((g) => g.id === "blocking"); + assert.equal(blocking.decisions, 484); + assert.equal(blocking.cards.length, 2); + assert.equal(blocking.cards[0].piece, "p:quartering-diet"); + assert.equal(blocking.cards[0].count, 483); + assert.equal(blocking.cards[0].at, 482); + const notes = groups.find((g) => g.id === "notes"); + assert.equal(notes.decisions, 0); + assert.equal(notes.hidden, 1); + assert.equal(groups.find((g) => g.id === "quiet").collapsed, true); + assert.equal(groups.reduce((n, g) => n + g.decisions + g.hidden, 0), items.length); + // Parking the video hides all 483 and leaves one card. + const parked = summarizeGroups(annotate(items, { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:quartering-diet" ? "done" : "active") })); + assert.equal(parked.find((g) => g.id === "blocking").decisions, 1); + assert.equal(parked.find((g) => g.id === "blocking").hidden, 483); +}); diff --git a/umtool/lib/lifecycle.mjs b/umtool/lib/lifecycle.mjs @@ -0,0 +1,122 @@ +// A PIECE's lifecycle: active, parked or done (plans/umtool-redesign.md, +// "Lifecycle"). +// +// REPORTS_ROOT/.umtool/lifecycle.json +// { format: "umtool-lifecycle", version: 1, +// pieces: { "<piece id>": { state, at, by? } } } +// +// STATE, NOT CACHE: it is the operator's word on a piece, so it lives beside +// the projects (the walk skips dot-dirs, so it is never a project) and not in +// CACHE_DIR. A piece with no entry is `active`. +// +// "Looks done" signals (a song's every cut shipped, a final mp4 plus a +// `share-*` batch, a published article with its video) only ever SUGGEST: they +// become a `looks-done` decision (lib/inbox.ts) and never write here. Only +// the operator's POST /api/pieces/lifecycle does. +// +// One writer, serialised in-process, and every write is a whole file to a temp +// name and a rename. A file that does not parse is never overwritten: a write +// refuses (LifecycleUnreadable) until somebody fixes it; a read treats it as +// "nothing set" and says so in `error`. +// +// Plain ESM, so a CLI and a unit test read it the way the app does. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { isPieceId } from "./pieces/ids.mjs"; + +export const LIFECYCLE_STATES = ["active", "parked", "done"]; +export const LIFECYCLE_FORMAT = "umtool-lifecycle"; +export const LIFECYCLE_VERSION = 1; + +export class LifecycleError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "LifecycleError"; + this.status = status; + } +} + +/** The file under a reports root. */ +export function lifecycleFile(reportsRoot) { + return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "lifecycle.json"); +} + +const isState = (s) => LIFECYCLE_STATES.includes(s); + +/** + * Every entry: `{ pieces: { [id]: { state, at, by? } }, error? }`. A missing + * file is empty; an unreadable one is empty with `error`. Entries that are not + * a piece id or a state are skipped, never fatal. + * + * @param {string} reportsRoot + */ +export async function readLifecycle(reportsRoot) { + let text; + try { + text = await readFile(/* turbopackIgnore: true */ lifecycleFile(reportsRoot), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return { pieces: {} }; + return { pieces: {}, error: `lifecycle.json cannot be read: ${err?.message ?? err}` }; + } + let raw; + try { + raw = JSON.parse(text); + } catch (err) { + return { pieces: {}, error: `lifecycle.json is not JSON: ${err.message}` }; + } + if (!raw || typeof raw !== "object" || raw.format !== LIFECYCLE_FORMAT || typeof raw.pieces !== "object" || !raw.pieces) { + return { pieces: {}, error: "lifecycle.json is not a umtool-lifecycle file" }; + } + const pieces = {}; + for (const [id, e] of Object.entries(raw.pieces)) { + if (!isPieceId(id) || !e || typeof e !== "object" || !isState(e.state)) continue; + pieces[id] = { state: e.state, at: typeof e.at === "string" ? e.at : "", ...(typeof e.by === "string" ? { by: e.by } : {}) }; + } + return { pieces }; +} + +/** A piece's state in a read: its entry's, else `active`. */ +export function lifecycleOf(read, id) { + return read?.pieces?.[id]?.state ?? "active"; +} + +let chain = Promise.resolve(); + +/** + * Set one piece's state. Answers the entry written. + * + * @param {string} reportsRoot + * @param {string} id a piece id (lib/pieces/ids.mjs) + * @param {string} state active | parked | done + * @param {{ by?: string, now?: Date }} [opts] + */ +export function setLifecycle(reportsRoot, id, state, { by, now } = {}) { + if (!isPieceId(id)) return Promise.reject(new LifecycleError(`not a piece id: ${JSON.stringify(id)}`)); + if (!isState(state)) return Promise.reject(new LifecycleError(`state is ${LIFECYCLE_STATES.join(" | ")}, not ${JSON.stringify(state)}`)); + const run = chain.then(() => write(reportsRoot, id, state, by, now ?? new Date())); + // The next write waits for this one, whether it failed or not. + chain = run.catch(() => {}); + return run; +} + +async function write(reportsRoot, id, state, by, now) { + const file = lifecycleFile(reportsRoot); + const read = await readLifecycle(reportsRoot); + if (read.error) throw new LifecycleError(`${read.error}; fix or remove ${file} first`, 409); + const entry = { state, at: now.toISOString(), ...(by ? { by } : {}) }; + const doc = { + format: LIFECYCLE_FORMAT, + version: LIFECYCLE_VERSION, + pieces: Object.fromEntries(Object.entries({ ...read.pieces, [id]: entry }).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), + }; + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw err; + } + return { id, ...entry }; +} diff --git a/umtool/lib/lifecycle.test.mjs b/umtool/lib/lifecycle.test.mjs @@ -0,0 +1,74 @@ +// A piece's lifecycle, read and written in a temp reports root. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { LIFECYCLE_STATES, lifecycleFile, lifecycleOf, readLifecycle, setLifecycle } from "./lifecycle.mjs"; + +const root = () => mkdtemp(path.join(tmpdir(), "umtool-lifecycle-")); + +test("absent is active, and a read never creates the file", async () => { + const r = await root(); + const read = await readLifecycle(r); + assert.deepEqual(read, { pieces: {} }); + assert.equal(lifecycleOf(read, "a:articles/zeta"), "active"); + assert.deepEqual(await readdir(r), []); +}); + +test("a write round-trips, with when and by whom", async () => { + const r = await root(); + const now = new Date("2026-10-13T12:00:00.000Z"); + const e = await setLifecycle(r, "p:quartering-diet", "done", { by: "operator", now }); + assert.deepEqual(e, { id: "p:quartering-diet", state: "done", at: "2026-10-13T12:00:00.000Z", by: "operator" }); + await setLifecycle(r, "a:articles/zeta", "parked", { now }); + const read = await readLifecycle(r); + assert.equal(lifecycleOf(read, "p:quartering-diet"), "done"); + assert.equal(lifecycleOf(read, "a:articles/zeta"), "parked"); + assert.equal(read.pieces["a:articles/zeta"].by, undefined); + const doc = JSON.parse(await readFile(lifecycleFile(r), "utf8")); + assert.equal(doc.format, "umtool-lifecycle"); + assert.deepEqual(Object.keys(doc.pieces), ["a:articles/zeta", "p:quartering-diet"]); + // Back to active is a write like any other. + await setLifecycle(r, "p:quartering-diet", "active", { now }); + assert.equal(lifecycleOf(await readLifecycle(r), "p:quartering-diet"), "active"); + // No temp file is left beside it. + assert.deepEqual(await readdir(path.dirname(lifecycleFile(r))), ["lifecycle.json"]); +}); + +test("concurrent writes all land", async () => { + const r = await root(); + const ids = Array.from({ length: 12 }, (_, i) => `p:project-${i}`); + await Promise.all(ids.map((id, i) => setLifecycle(r, id, LIFECYCLE_STATES[i % 3]))); + const read = await readLifecycle(r); + for (const [i, id] of ids.entries()) assert.equal(lifecycleOf(read, id), LIFECYCLE_STATES[i % 3]); +}); + +test("junk ids and states are refused, and nothing is written", async () => { + const r = await root(); + await assert.rejects(setLifecycle(r, "articles/zeta", "done"), /not a piece id/); + await assert.rejects(setLifecycle(r, "p:../x", "done"), /not a piece id/); + await assert.rejects(setLifecycle(r, "p:x", "shipped"), /state is active \| parked \| done/); + assert.deepEqual(await readdir(r), []); +}); + +test("an unreadable file is reported, and never overwritten", async () => { + const r = await root(); + await mkdir(path.dirname(lifecycleFile(r)), { recursive: true }); + await writeFile(lifecycleFile(r), "{ not json"); + const read = await readLifecycle(r); + assert.deepEqual(read.pieces, {}); + assert.match(read.error, /not JSON/); + await assert.rejects(setLifecycle(r, "p:x", "done"), (err) => err.status === 409); + assert.equal(await readFile(lifecycleFile(r), "utf8"), "{ not json"); +}); + +test("entries that are not a piece or a state are skipped on read", async () => { + const r = await root(); + await mkdir(path.dirname(lifecycleFile(r)), { recursive: true }); + await writeFile( + lifecycleFile(r), + JSON.stringify({ format: "umtool-lifecycle", version: 1, pieces: { "p:ok": { state: "parked", at: "x" }, junk: { state: "done" }, "p:bad": { state: "gone" } } }), + ); + assert.deepEqual(Object.keys((await readLifecycle(r)).pieces), ["p:ok"]); +}); diff --git a/umtool/lib/lifecycle.ts b/umtool/lib/lifecycle.ts @@ -0,0 +1,35 @@ +import { REPORTS_ROOT } from "./paths"; +import { + LIFECYCLE_STATES as STATES, + LifecycleError, + lifecycleOf as lifecycleOfRead, + readLifecycle as readAt, + setLifecycle as setAt, +} from "./lifecycle.mjs"; + +// The app's view of lib/lifecycle.mjs, typed and bound to REPORTS_ROOT. The +// logic, the file format and the rules are there (plain ESM, unit-tested). + +export type LifecycleState = "active" | "parked" | "done"; +export type LifecycleEntry = { state: LifecycleState; at: string; by?: string }; +export type LifecycleRead = { pieces: Record<string, LifecycleEntry>; error?: string }; + +export const LIFECYCLE_STATES = STATES as LifecycleState[]; +export { LifecycleError }; + +export const isLifecycleState = (s: unknown): s is LifecycleState => (LIFECYCLE_STATES as unknown[]).includes(s); + +export async function readLifecycle(): Promise<LifecycleRead> { + return (await readAt(REPORTS_ROOT)) as LifecycleRead; +} + +export function lifecycleOf(read: LifecycleRead, id: string): LifecycleState { + return lifecycleOfRead(read, id) as LifecycleState; +} + +export async function setLifecycle(id: string, state: LifecycleState, by?: string): Promise<LifecycleEntry & { id: string }> { + return (await setAt(REPORTS_ROOT, id, state, { by })) as LifecycleEntry & { id: string }; +} + +/** Parked and done pieces are out of the way: their decisions are `hidden`. */ +export const isQuiet = (state: LifecycleState): boolean => state !== "active"; diff --git a/umtool/lib/pieces/ids.mjs b/umtool/lib/pieces/ids.mjs @@ -0,0 +1,94 @@ +// A PIECE's id (plans/umtool-redesign.md, "Data and engine rules"). +// +// A piece is the unit the operator works on: an article plus the video +// project(s) made from it, or a project that belongs to no article. Its id is +// NAMESPACED, because the bare spellings collide: `resolveTarget` +// (lib/annotations/targets.mjs) reads a two-segment `x/y` as an article when +// such a report exists and as a project otherwise -- and a project id is a +// path, so `articles/zeta` can be either. +// +// a:<site>/<report> an article; `site` may be `articles` (the store's) +// p:<projectId> a project under REPORTS_ROOT, by its path id +// c:<case> a research case (reserved: research boards, R2) +// +// Pure, no imports with side effects: a client component may parse an id. + +/** A site or report id: lib/paths.mjs SEGMENT_RE (a test holds them equal). */ +export const PIECE_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; + +/** One segment of a project id: lib/projects/walk.mjs isSegment (a test holds them equal). */ +const PROJECT_SEGMENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const projectSegment = (v) => PROJECT_SEGMENT_RE.test(v) && !v.includes(".."); + +export const PIECE_KINDS = ["article", "project", "case"]; +const PREFIX = { article: "a", project: "p", case: "c" }; + +/** + * Parse a piece id, or null when it is not one. Never guesses: a bare + * `site/report` or project id is null. + * + * @param {unknown} id + * @returns {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string } | null} + */ +export function parsePieceId(id) { + if (typeof id !== "string" || id.length > 512) return null; + const m = /^([apc]):(.+)$/.exec(id); + if (!m) return null; + const [, ns, rest] = m; + if (ns === "a") { + const parts = rest.split("/"); + if (parts.length !== 2 || !parts.every((s) => PIECE_SEGMENT_RE.test(s))) return null; + return { kind: "article", site: parts[0], report: parts[1] }; + } + if (ns === "p") { + const parts = rest.split("/"); + if (!parts.length || !parts.every(projectSegment)) return null; + return { kind: "project", project: rest }; + } + if (!PIECE_SEGMENT_RE.test(rest)) return null; + return { kind: "case", case: rest }; +} + +/** True when `id` is a piece id. */ +export const isPieceId = (id) => parsePieceId(id) !== null; + +/** + * The id for a parsed piece. Throws on parts that would not parse back: an id + * that cannot round-trip is a bug at the caller, not a value to pass along. + * + * @param {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string }} p + */ +export function formatPieceId(p) { + const id = + p?.kind === "article" + ? `${PREFIX.article}:${p.site}/${p.report}` + : p?.kind === "project" + ? `${PREFIX.project}:${p.project}` + : p?.kind === "case" + ? `${PREFIX.case}:${p.case}` + : null; + if (id === null || !isPieceId(id)) throw new Error(`not a piece: ${JSON.stringify(p)}`); + return id; +} + +/** `a:<site>/<report>`. */ +export const articlePieceId = (site, report) => formatPieceId({ kind: "article", site, report }); + +/** `p:<projectId>`. */ +export const projectPieceId = (project) => formatPieceId({ kind: "project", project }); + +/** `c:<case>`. */ +export const casePieceId = (slug) => formatPieceId({ kind: "case", case: slug }); + +/** + * An article decision's `project` (`sites/<site>/<report>`, lib/decisions.ts + * noteDecisions) back to its article, or null. Only meaningful for a row whose + * `projectKind` is "article": a project may itself live under a `sites/` folder. + * + * @param {string} project + */ +export function articleOfDecisionProject(project) { + const m = /^sites\/([^/]+)\/([^/]+)$/.exec(String(project ?? "")); + if (!m || !PIECE_SEGMENT_RE.test(m[1]) || !PIECE_SEGMENT_RE.test(m[2])) return null; + return { site: m[1], report: m[2] }; +} diff --git a/umtool/lib/pieces/ids.test.mjs b/umtool/lib/pieces/ids.test.mjs @@ -0,0 +1,67 @@ +// Piece ids: namespaced, round-tripping, never ambiguous. +import assert from "node:assert/strict"; +import test from "node:test"; +import { SEGMENT_RE } from "../paths.mjs"; +import { isSegment } from "../projects/walk.mjs"; +import { + PIECE_SEGMENT_RE, + articleOfDecisionProject, + articlePieceId, + casePieceId, + formatPieceId, + isPieceId, + parsePieceId, + projectPieceId, +} from "./ids.mjs"; + +test("each namespace parses and formats back", () => { + for (const id of ["a:articles/zeta", "a:priv/polemic-alpha", "p:ferret-rescue", "p:quartering-uh-song/videos/yoshi", "p:gen-projects/zeta/i1", "c:vote-rigging"]) { + const parsed = parsePieceId(id); + assert.ok(parsed, id); + assert.equal(formatPieceId(parsed), id); + } + assert.deepEqual(parsePieceId("a:articles/zeta"), { kind: "article", site: "articles", report: "zeta" }); + assert.deepEqual(parsePieceId("p:quartering-uh-song/videos/yoshi"), { kind: "project", project: "quartering-uh-song/videos/yoshi" }); + assert.deepEqual(parsePieceId("c:vote"), { kind: "case", case: "vote" }); + assert.equal(articlePieceId("articles", "zeta"), "a:articles/zeta"); + assert.equal(projectPieceId("articles/zeta"), "p:articles/zeta"); + assert.equal(casePieceId("vote"), "c:vote"); +}); + +test("a two-segment id is never ambiguous: the namespace says which", () => { + // resolveTarget reads `articles/zeta` as an article when the report exists + // and as a project otherwise. A piece id carries the answer. + assert.equal(parsePieceId("articles/zeta"), null); + assert.equal(parsePieceId("a:articles/zeta").kind, "article"); + assert.equal(parsePieceId("p:articles/zeta").kind, "project"); + assert.notEqual(articlePieceId("articles", "zeta"), projectPieceId("articles/zeta")); +}); + +test("junk is refused", () => { + for (const bad of [ + "", "a:", "p:", "c:", "x:y", "A:articles/zeta", "a:articles", "a:articles/zeta/extra", "a:Articles/zeta", + "a:articles/../x", "p:../x", "p:a//b", "p:/abs", "p:.hidden", "p:a/..b", "p:a b", "c:Up", "c:a/b", + "a:articles/zeta\n", " p:x", null, undefined, 42, {}, `p:${"a/".repeat(300)}a`, + ]) { + assert.equal(parsePieceId(bad), null, JSON.stringify(bad)); + assert.equal(isPieceId(bad), false); + } + assert.throws(() => formatPieceId({ kind: "article", site: "x", report: "a/b" })); + assert.throws(() => projectPieceId("../etc")); + assert.throws(() => formatPieceId({ kind: "nope" })); +}); + +test("the segment rules are the ones the rest of umtool uses", () => { + assert.equal(PIECE_SEGMENT_RE.source, SEGMENT_RE.source); + for (const seg of ["ferret-rescue", "i1", "Mixed_Case.v2", ".hidden", "a..b", "a b", "-x", "x-"]) { + assert.equal(isPieceId(`p:${seg}`), isSegment(seg), seg); + } +}); + +test("an article decision's project names its article", () => { + assert.deepEqual(articleOfDecisionProject("sites/articles/zeta"), { site: "articles", report: "zeta" }); + assert.deepEqual(articleOfDecisionProject("sites/priv/polemic-alpha"), { site: "priv", report: "polemic-alpha" }); + assert.equal(articleOfDecisionProject("ferret-rescue"), null); + assert.equal(articleOfDecisionProject("sites/priv"), null); + assert.equal(articleOfDecisionProject("sites/priv/a/b"), null); +});