// "What needs you" (umtool redesign L4): the Inbox's new decision sources -- // versions to judge, clips not walked, stale quote checks, a live case's new // transcripts, X's jar -- as pure rows, then read from a temporary reports tree // and a stand-in editor; and the card's one-press settle (groups.mjs mergeSettle). // // Run with: pnpm --filter umtool exec tsx --test lib/inbox/needs-you.test.ts import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { mkdtempSync } from "node:fs"; import { mkdir, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // The environment BEFORE any module that reads lib/paths.mjs is loaded (checks.mjs reaches it through // quoteCheck.mjs): a static import would be hoisted above this and read the real ~/reports. const tmp = mkdtempSync(path.join(os.tmpdir(), "umtool-needs-you-")); process.env.CHANNELS_DIR = path.join(tmp, "channels"); process.env.SITES_DIR = path.join(tmp, "sites"); process.env.REPORTS_DIR = path.join(tmp, "reports"); process.env.UMTOOL_XJAR_MEMO_MS = "0"; const { VERSION_UNJUDGED, versionsDecisions, versionsToJudge } = await import("./versions.mjs"); const { CLIPS_UNWALKED, walkDecisions } = await import("./walk.mjs"); const { QUOTE_CHECK_STALE, quoteCheckDecisions, staleQuoteChecks } = await import("./checks.mjs"); const { X_JAR_STALE, xJarDecision } = await import("./xJar.mjs"); const { CASE_NEW_CUES, caseCuesDecision, lastScanOf, newSince } = await import("./caseCues.mjs"); const { annotate, groupOf, mergeSettle, summarizeGroups } = await import("./groups.mjs"); const { whatOf } = await import("./what.mjs"); const take = (id: string, o: Record = {}) => ({ id, label: id, previewSize: 100, previewMtimeMs: 0, builtAt: "2026-11-01T10:00:00Z", draft: false, quick: false, version: true, seconds: 95, ...o }); // eslint-disable-next-line @typescript-eslint/no-explicit-any type Row = { kind: string; severity: string; [k: string]: any }; // eslint-disable-next-line @typescript-eslint/no-explicit-any type Any = any; const annotated = (rows: Any[]): Row[] => annotate(rows as never[], { pieceOf: () => "p:x", lifecycleOf: () => "active" }) as Any[]; test("versions to judge: rendered (its preview there, whatever `draft` says), no verdict, not superseded, not a quick render or a skipped take -- newest first", () => { const takes = [ take("v1", { builtAt: "2026-11-01T10:00:00Z" }), take("v2", { builtAt: "2026-11-03T10:00:00Z" }), take("v3", { previewSize: null }), take("d1", { draft: true, previewSize: null }), take("d2", { draft: true, builtAt: "2026-10-25T10:00:00Z" }), take("q1", { quick: true }), take("liked"), take("gone"), take("clip"), ]; const verdicts = { liked: { verdict: "like" }, gone: { verdict: null, superseded: { by: "v2" } } }; assert.deepEqual(versionsToJudge(takes, verdicts, { skip: (t) => t.id === "clip" }).map((t) => t.id), ["v2", "v1", "d2"]); const rows = versionsDecisions({ project: "x", projectTitle: "X", takes, verdicts, playHref: (t) => `/projects/x/play?take=${t}`, skip: (t) => t.id === "clip", now: Date.parse("2026-11-04T00:00:00Z") }); assert.equal(rows.length, 3); assert.ok(rows.every((r) => r.kind === VERSION_UNJUDGED && r.href === "/projects/x/play?take=v2" && r.what === "3 versions to judge" && r.severity === "open")); assert.match(rows[0].why, /^3 versions to judge · newest version v2 · 1:35 · rendered 2026-11-03/); const [row] = annotated(rows); assert.equal(groupOf(row), "review"); assert.equal(row.action.label, "Play and judge"); // A render nobody judged for two weeks is no longer waiting: Quiet, folded. const later = versionsDecisions({ project: "x", projectTitle: "X", takes, verdicts, playHref: () => "/", skip: (t) => t.id === "clip", now: Date.parse("2026-11-16T12:00:00Z") }); assert.deepEqual(later.map((r) => [r.target, r.severity, r.what]), [["v2", "open", "1 version to judge"], ["v1", "info", "2 versions to judge"], ["d2", "info", "2 versions to judge"]]); assert.equal(later[1].href, "/"); assert.equal(groupOf(later[1]), "quiet"); assert.deepEqual(versionsDecisions({ project: "x", projectTitle: "X", takes: [], verdicts: {}, playHref: () => "/" }), []); // Shapes it does not know are left out, never thrown on. assert.deepEqual(versionsToJudge(null as never, null as never), []); }); test("clips not walked: only on a draft going somewhere -- a walk begun or a render made; the bench on the first in walk order", () => { const clips = [ { id: "c03", verdict: "unreviewed" }, { id: "c01", verdict: "confirmed" }, { id: "c02", verdict: "unreviewed" }, ]; const base = { project: "x", projectTitle: "X", at: 5, now: 10, benchHref: (c: string) => `/projects/x/clip/${c}` }; const rows = walkDecisions({ ...base, clips, rendered: false }); assert.deepEqual(rows.map((r) => r.target), ["c03", "c02"]); assert.ok(rows.every((r) => r.kind === CLIPS_UNWALKED && r.href === "/projects/x/clip/c03" && r.what === "2 clips not walked")); assert.match(rows[0].why, /2 clips not walked · 1 of 3 walked · next c03 — c03, c02/); // Never walked and never rendered: a cut in the making, not yet a call. assert.deepEqual(walkDecisions({ ...base, clips: clips.map((c) => ({ ...c, verdict: "unreviewed" })), rendered: false }), []); assert.equal(walkDecisions({ ...base, clips: clips.map((c) => ({ ...c, verdict: "unreviewed" })), rendered: true }).length, 3); assert.deepEqual(walkDecisions({ ...base, clips: clips.map((c) => ({ ...c, verdict: "confirmed" })), rendered: true }), []); const [row] = annotated(rows); assert.deepEqual([groupOf(row), row.action.label, whatOf(CLIPS_UNWALKED)], ["review", "Walk the clips", "clips not walked"]); // A draft untouched for two weeks: its walk is not waiting. assert.ok(walkDecisions({ ...base, clips, rendered: false, now: 5 + 15 * 864e5 }).every((r) => r.severity === "info")); }); test("stale quote checks: a clip whose cut or quote changed since its row, or never checked, on a project that uses the check", () => { const clip = (id: string, start: number, o: Record = {}) => ({ type: "clip", id, video: "v", start, end: start + 5, quote: `Line ${start}`, ...o }); const row = (start: number, status = "ok") => ({ status, cut: { from: start, to: start + 5 }, quote: `Line ${start}` }); const timeline = [clip("a", 10), clip("b", 20, { cutStart: 21 }), clip("c", 30), clip("d", 40, { quoteRuled: true }), clip("e", 50, { quote: "" }), { type: "card", id: "k1" }]; const doc: Any = { version: 1, clips: { a: row(10), b: row(20, "moved"), d: row(1) } }; assert.deepEqual(staleQuoteChecks(timeline, doc), [ { id: "b", why: "stale" }, { id: "c", why: "unchecked" }, ]); // No quote-check.json (or an empty one): the check is opt-in, nothing to say. assert.deepEqual(staleQuoteChecks(timeline, { clips: {} }), []); assert.deepEqual(staleQuoteChecks(timeline, null), []); const rows = quoteCheckDecisions({ project: "x", projectTitle: "X", timeline, doc, href: "/projects/x", at: 1 }); assert.deepEqual(rows.map((r) => [r.kind, r.target, r.settle]), [ [QUOTE_CHECK_STALE, "b", { kind: "quote-check", clips: ["b"], label: "Run quote-check" }], [QUOTE_CHECK_STALE, "c", { kind: "quote-check", clips: ["c"], label: "Run quote-check" }], ]); assert.equal(rows[0].fix, "umtool quote-check x --clips b,c"); assert.match(rows[0].why, /2 quote checks out of date · cut or quote changed since: b · never checked: c/); // One card, one press over every clip it lists. const [g] = (summarizeGroups(annotated(rows)) as Any[]).filter((x) => x.cards.length); assert.equal(g.id, "open"); assert.deepEqual(g.cards[0].settle, { kind: "quote-check", clips: ["b", "c"], label: "Run quote-check" }); assert.equal(g.cards[0].action.label, "Run quote-check"); }); test("a card's settle: one quote check over every clip; the same project-wide press kept; two patches, or a row without one, none", () => { const q = (c: string) => ({ kind: "quote-check", clips: [c], label: "Run quote-check" }); const links = { kind: "check-links", fix: true, label: "Use embed ids (2)" }; assert.deepEqual(mergeSettle(q("a"), q("b")), { kind: "quote-check", clips: ["a", "b"], label: "Run quote-check" }); assert.deepEqual(mergeSettle(links, { ...links }), links); assert.equal(mergeSettle({ kind: "patch", clip: "a", patch: {}, label: "x" }, { kind: "patch", clip: "b", patch: {}, label: "x" }), null); assert.equal(mergeSettle(links, null), null); assert.equal(mergeSettle(links, { kind: "check-links", label: "Check links" }), null); }); test("X's jar: a row only when an X alert is up (X work waits) -- the editor's three lines, Blocking", () => { const x = { source: "profile", ageMinutes: 190, maxAgeMinutes: 60, fresh: false, loggedIn: true, at: null, readAt: "", summary: "" }; const alert = { service: "x", label: "X", family: "x", state: "stale", kind: "jar-age", raisedAt: "2026-11-09T10:00:00Z", headline: "X cookies are 3 h old (limit 60 min)", fix: "Refresh cookies (or Connect X account) on /settings — then Recheck.", detail: "2 X jobs are queued." }; assert.equal(xJarDecision({ alerts: [], x }, { href: "/s" }), null); assert.equal(xJarDecision({ alerts: [{ ...alert, state: "ok-again" }], x }, { href: "/s" }), null); assert.equal(xJarDecision({ alerts: [{ ...alert, family: "ytdlp", service: "rumble" }], x }, { href: "/s" }), null); assert.equal(xJarDecision("not a payload", { href: "/s" }), null); const row = xJarDecision({ alerts: [alert], x }, { href: "http://editor/settings" }); assert.ok(row); assert.equal(row.kind, X_JAR_STALE); assert.equal(row.severity, "blocking"); assert.equal(row.why, "X cookies are 3 h old (limit 60 min) Refresh cookies (or Connect X account) on /settings — then Recheck. 2 X jobs are queued."); assert.equal(row.at, Date.parse("2026-11-09T10:00:00Z")); const [a] = annotate([row], { pieceOf: () => null, lifecycleOf: () => "active" }); assert.deepEqual([a.group, a.action.label, a.hidden], ["blocking", "Refresh X's cookies", false]); }); test("a live case's new transcripts: since its last done candidate scan; none before one ran", () => { assert.equal(lastScanOf({}), null); assert.equal(lastScanOf({ candidates: { state: "running", startedAt: "2026-11-01T00:00:00Z" } }), null); const since = lastScanOf({ candidates: { state: "done", startedAt: "2026-11-01T00:00:00Z", endedAt: "2026-11-01T00:05:00Z" } }); assert.equal(since, Date.parse("2026-11-01T00:05:00Z")); const rows = [ { channel: "a", id: "old", at: since! - 1 }, { channel: "a", id: "new1", at: since! + 10 }, { channel: "b", id: "new2", at: since! + 20 }, ]; const fresh = newSince(rows, since!); assert.deepEqual(fresh.map((r) => r.id), ["new2", "new1"]); const row = caseCuesDecision({ id: "lighthouse", title: "Lighthouse", since: since!, fresh, href: "/research/lighthouse/pipeline" }); assert.ok(row); assert.deepEqual([row.kind, row.target, row.what, row.at], [CASE_NEW_CUES, "lighthouse", "2 new transcripts since the last scan", since! + 20]); assert.match(row.why, /since the last scan · 2026-11-01 00:05 UTC · on b, a — scan the candidates again/); assert.equal(caseCuesDecision({ id: "x", title: "x", since: since!, fresh: [], href: "/" }), null); const [a] = annotate([row], { pieceOf: () => null, lifecycleOf: () => "active" }); assert.deepEqual([a.group, a.action.label], ["review", "Scan again"]); }); // ─── read from disk and from a stand-in editor ──────────────────────────────── let editor: Server; let services: unknown = { ok: true, alerts: [], pending: [] }; before(async () => { editor = createServer((req, res) => { res.setHeader("content-type", "application/json"); if (req.url?.startsWith("/api/ops/services")) return res.end(JSON.stringify(services)); res.statusCode = 404; res.end(JSON.stringify({ ok: false, error: "no route" })); }); await new Promise((r) => editor.listen(0, "127.0.0.1", r)); process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${(editor.address() as AddressInfo).port}`; process.env.WORKER_TOKEN = "t"; // A report video with two rendered versions (one judged), a walk begun, and a quote check gone stale. const p = path.join(tmp, "reports", "ny-cut"); const clip = (id: string, start: number, o: Record = {}) => ({ type: "clip", id, video: "vid", start, end: start + 4, cite: start, quote: `Line ${start}`, ...o }); await mkdir(p, { recursive: true }); await writeFile( path.join(p, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "ny-cut", title: "The NY Cut", provenance: { channelSlug: "nychan" }, render: { width: 1920, height: 1080, fps: 30 }, timeline: [clip("c01", 10, { verdict: "confirmed" }), clip("c02", 20), clip("c03", 30)] }), ); for (const [id, order] of [["v1", 1], ["v2", 2]] as const) { await mkdir(path.join(p, "takes", id), { recursive: true }); await writeFile(path.join(p, "takes", id, "take.json"), JSON.stringify({ id, group: "cut", order, label: `Version ${order}`, kind: "similar", preview: "preview.mp4", version: true, window: "full", builtAt: new Date(Date.now() - (3 - order) * 864e5).toISOString() })); await writeFile(path.join(p, "takes", id, "preview.mp4"), "mp4"); } await writeFile(path.join(p, "takes", "verdicts.json"), JSON.stringify({ v1: { verdict: "like", note: "", at: "2026-11-02T00:00:00Z" } })); await writeFile(path.join(p, "quote-check.json"), JSON.stringify({ version: 1, clips: { c02: { status: "ok", cut: { from: 19, to: 24 }, quote: "Line 20" } } })); // A live case scanned on 1 Nov, its channel transcribed once before and twice after. const c = path.join(tmp, "reports", ".umtool", "research", "ny-case"); await mkdir(c, { recursive: true }); const now = "2026-11-01T00:00:00Z"; await writeFile(path.join(c, "case.json"), JSON.stringify({ format: "umtool-research-case", version: 1, id: "ny-case", title: "The NY Case", scope: { source: "local" }, search: null, sessions: [], sections: [], quotes: [], notes: "", handoffs: [], counters: { quote: 0, section: 0 }, createdAt: now, updatedAt: now })); await writeFile(path.join(c, "pipeline.json"), JSON.stringify({ format: "archilyzer-case-pipeline", version: 1, case: "ny-case", subjects: [], scope: { channels: ["nychan"], groups: [], sites: [] }, eras: [], groups: [], privateNames: { sha256: [], note: "" }, readerPrompts: { common: "" }, status: "reading", createdAt: now, updatedAt: now })); await writeFile(path.join(c, "stages.json"), JSON.stringify({ candidates: { state: "done", startedAt: now, endedAt: "2026-11-01T00:05:00Z", by: "cli", pid: 1, log: [] } })); for (const [id, when] of [["old", "2026-10-20T00:00:00Z"], ["new1", "2026-11-03T00:00:00Z"], ["new2", "2026-11-04T00:00:00Z"]]) { const d = path.join(tmp, "channels", "nychan", "data", id); await mkdir(d, { recursive: true }); await writeFile(path.join(d, "transcript.cues.json"), "{}"); await utimes(path.join(d, "transcript.cues.json"), new Date(when), new Date(when)); } }); after(async () => { editor?.close(); await rm(tmp, { recursive: true, force: true }); }); test("from disk: the report video's version to judge, its clips not walked, its stale quote check -- each kind once per row", async () => { const { projectCallsAll } = await import("./projectCalls"); const rows = (await projectCallsAll()).filter((d) => d.project === "ny-cut"); const of = (k: string) => rows.filter((d) => d.kind === k).map((d) => d.target); assert.deepEqual(of(VERSION_UNJUDGED), ["v2"]); assert.equal(rows.find((d) => d.kind === VERSION_UNJUDGED)?.href, "/projects/ny-cut/play?take=v2"); assert.deepEqual(of(CLIPS_UNWALKED), ["c02", "c03"]); assert.equal(rows.find((d) => d.kind === CLIPS_UNWALKED)?.href, "/projects/ny-cut/clip/c02"); // c02's row is for a cut it no longer plays; c01 and c03 were never checked. assert.deepEqual(of(QUOTE_CHECK_STALE), ["c01", "c02", "c03"]); assert.ok(rows.every((d) => d.projectTitle === "The NY Cut")); // Read again with nothing changed: the same rows (the memo), and judging v2 drops it. assert.deepEqual((await projectCallsAll()).filter((d) => d.project === "ny-cut"), rows); await writeFile(path.join(tmp, "reports", "ny-cut", "takes", "verdicts.json"), JSON.stringify({ v1: { verdict: "like", note: "", at: "x" }, v2: { verdict: "maybe", note: "", at: "y" } })); assert.deepEqual((await projectCallsAll()).filter((d) => d.project === "ny-cut" && d.kind === VERSION_UNJUDGED), []); }); test("from disk: the live case's two new transcripts since its scan (the files, with no index)", async () => { const { caseCuesDecisions } = await import("./caseCues"); const [row] = await caseCuesDecisions(); assert.ok(row); assert.deepEqual([row.kind, row.project, row.projectTitle, row.href, row.piece], [CASE_NEW_CUES, "research/ny-case", "The NY Case", "/research/ny-case/pipeline", "c:ny-case"]); assert.equal(row.what, "2 new transcripts since the last scan"); }); test("from the editor: no row while no X work waits; the row once the jar's alert is up; none when the editor is gone", async () => { const { xJarDecisions } = await import("./xJar"); assert.deepEqual(await xJarDecisions(), []); services = { ok: true, alerts: [{ service: "x", label: "X", family: "x", state: "stale", kind: "jar-age", raisedAt: "2026-11-09T10:00:00Z", headline: "X cookies are 3 h old", fix: "Refresh cookies on /settings — then Recheck.", detail: "" }], pending: [] }; const [row] = await xJarDecisions(); assert.equal(row?.kind, X_JAR_STALE); assert.equal(row?.href, `${process.env.ARCHILYZER_EDITOR_URL}/settings`); await new Promise((r) => editor.close(() => r())); assert.deepEqual(await xJarDecisions(), []); }); test("the one-press routes refuse another site's write (sameOrigin.mjs) and still take this app's own", async () => { const routes = [ { mod: await import("../../app/api/report/links/route"), method: "POST" as const, body: { project: "ny-cut", fix: true } }, { mod: await import("../../app/api/report/takes/verdict/route"), method: "POST" as const, body: { project: "ny-cut", take: "v2", verdict: "like" } }, { mod: await import("../../app/api/report/window/route"), method: "PUT" as const, body: { project: "ny-cut", clip: "c02", lockCut: true } }, // Home's Quick clip render (it starts a job) and the timeline's writes (Add clip). { mod: await import("../../app/api/report/quick-clip/route"), method: "POST" as const, body: { spec: "nychan/nyfresh@1-2" } }, { mod: await import("../../app/api/report/timeline/route"), method: "POST" as const, body: { project: "ny-cut", op: "remove", id: "c03" } }, ]; for (const { mod, method, body } of routes) { const handler = (mod as unknown as Record Promise>)[method]; // A text/plain form post from evil.example to this app: no preflight, refused before the body is read. const cross = await handler( new Request("http://localhost:3050/api/x", { method, headers: { host: "localhost:3050", origin: "https://evil.example", "sec-fetch-site": "cross-site", "content-type": "text/plain" }, body: JSON.stringify(body) }), ); assert.equal(cross.status, 403, method); assert.match(((await cross.json()) as { error: string }).error, /refused/); // A rebinding page (Host: evil.example) is refused too. const rebound = await handler(new Request("http://evil.example/api/x", { method, headers: { host: "evil.example:3050" }, body: JSON.stringify(body) })); assert.equal(rebound.status, 403); } // This app's own page (same-origin) gets past the guard: the verdict is written. const verdict = (await import("../../app/api/report/takes/verdict/route")) as unknown as { POST: (r: Request) => Promise }; const own = await verdict.POST( new Request("http://localhost:3050/api/report/takes/verdict", { method: "POST", headers: { host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin", "content-type": "application/json" }, body: JSON.stringify({ project: "ny-cut", take: "v2", verdict: "no" }) }), ); assert.equal(own.status, 200, await own.clone().text()); });