Archilyzer · Source

archilyzer

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

commit dd42bcadb399d0bd8979c7581fb5370728edb95c
parent ed8b67ed00cf8c652a9bd5ed95230fe6d0dd44c5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 12:20:53 -0400

umtool: recurring reports — Create's recurring form, the series page, Work's recurring facet, the Inbox's tick and edition cards, the cadence chip (R5)

- /create gains "A recurring report" (Article group): shape (Living report /
  Series), topic, question, scope (channels or a board's), cadence, the
  series' window check or the living report's make-current switch; plan,
  then confirm through the editor's report-schedule (dryRun first).
- /series/<id> (the piece s:<id>): the cadence chip, Pause/Resume, Tick now,
  Edit cadence, Delete (plan, then confirm); the tick in flight on P4b's
  JobProgress; editions newest first (a quiet one dimmed, with its window);
  the tick log. POST /api/schedules forwards to the editor; GET reads the
  store.
- pieces: s:<series> pieces; an edition's article names its series and is
  not a Work row; a living report's article carries its schedule's chip in
  the piece head (PieceFrame, additive) with Pause/Resume and Tick now, Edit
  and Delete in the ⋯ menu; an article in the making waiting for its first
  tick is a page and is named by its topic.
- Work: the Recurring facet (recurring=1), the Series kind, the chip on a
  row. Inbox: tick-failed (Tick now) and tick-held (Raise cap) in Your call,
  edition-ready in Review; an edition raises no iteration cards of its own.
- The Running list: a report-tick is a generation row, its spend from its
  log, linking its schedule. umtool schedule list | show <id>.
- The e2e editor stub runs the real report-schedule action over the fixture
  store with stubbed tick steps (common/testing/schedule/opsStub.ts);
  recurring.spec; create.spec counts nine lines. Editor ops-api.spec: a
  report-schedule row (create, list, tick now, pause, the lane's gate,
  delete). The tick logs its sweep's spend so far.

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

Diffstat:
Mcommon/controller/reportTick.ts | 20++++++++++++++++++++
Mcommon/lib/report/schedule/cadence.ts | 4++--
Acommon/testing/schedule/opsStub.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/ops-api.spec.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/schedules/route.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/series/[id]/page.tsx | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/work/page.tsx | 19++++++++++++++++---
Aumtool/bin/schedule.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 15++++++++++++---
Mumtool/components/articles/ArticlePage.tsx | 17++++++++++++++++-
Mumtool/components/articles/NewArticleForm.tsx | 3++-
Mumtool/components/create/CreateView.tsx | 5+++++
Aumtool/components/create/RecurringForm.tsx | 267+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/piece/PieceFrame.tsx | 29+++++++++++++++++++++++++++++
Aumtool/components/series/CadenceFields.tsx | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/series/ScheduleControls.tsx | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/series/TickProgress.tsx | 12++++++++++++
Mumtool/components/shell/JumpPalette.tsx | 1+
Mumtool/e2e/create.spec.ts | 5+++--
Mumtool/e2e/fixtures/editor-stub.mjs | 36++++++++++++++++++++++++++++++++++++
Aumtool/e2e/recurring.spec.ts | 249+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/activity.ts | 15++++++++++++++-
Mumtool/lib/create.ts | 4++++
Mumtool/lib/hrefs.ts | 9++++++++-
Mumtool/lib/inbox.ts | 47++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/inbox/groups.mjs | 11++++++++++-
Aumtool/lib/inbox/schedules.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/schedules.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/what.mjs | 3+++
Mumtool/lib/pieces.ts | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/pieces/ids.mjs | 21++++++++++++++-------
Mumtool/lib/pieces/ids.test.mjs | 7+++++--
Mumtool/lib/rail.ts | 3++-
Mumtool/lib/running.mjs | 18++++++++++++++++--
Mumtool/lib/running.test.mjs | 10++++++++++
Aumtool/lib/schedule-types.ts | 35+++++++++++++++++++++++++++++++++++
Aumtool/lib/schedules.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/work.ts | 15++++++++++++---
Mumtool/lib/work/facets.mjs | 5++++-
Mumtool/lib/work/facets.test.mjs | 7+++++++
40 files changed, 1919 insertions(+), 41 deletions(-)

diff --git a/common/controller/reportTick.ts b/common/controller/reportTick.ts @@ -67,6 +67,8 @@ import path from "node:path"; export const REPORT_TICK_JOB_KIND = "report-tick"; export const REPORT_TICK_RESULT_MARKER = "@@report-tick "; +// How often a tick re-reads the spend of the sweep it waits on. +const SPEND_POLL_MS = 5_000; // ─── the seam ─── @@ -193,13 +195,31 @@ export function editionGenerator(deps: EditionDeps): TickSteps["generateEdition" // A tick cancelled cancels its sweep. const stop = () => getRegistry().cancel(result.jobId); ctx.signal.addEventListener("abort", stop, { once: true }); + // The sweep's spend so far, in the tick's own log (`~$x`: the Running + // list's spend for the tick). + let said = -1; + const spent = setInterval(() => { + void readIteration(input.article, n, paths).then( + (it) => { + const usd = it ? iterationUsd(it) : 0; + if (usd !== said && usd > 0) { + said = usd; + ctx.log(`sweep ${input.article} i${n}: ~$${usd.toFixed(2)} so far`); + } + }, + () => {}, + ); + }, SPEND_POLL_MS); + spent.unref?.(); try { await result.done; } finally { + clearInterval(spent); ctx.signal.removeEventListener("abort", stop); } const it = await readIteration(input.article, n, paths); const usd = it ? iterationUsd(it) : 0; + ctx.log(`sweep ${input.article} i${n} ended ${it?.status ?? "unread"}: ~$${usd.toFixed(2)}`); const status: StepStatus = it?.status === "done" ? "done" : it?.status === "cancelled" ? "cancelled" : "failed"; if (status === "done" && input.title) { // An edition's title is the series' ("<topic> · week of <date>"), not the model's. diff --git a/common/lib/report/schedule/cadence.ts b/common/lib/report/schedule/cadence.ts @@ -279,12 +279,12 @@ export function cadenceWords(c: Cadence): string { return `every ${c.days} days ${c.at}`; } -/** "Mon 06:00" — a tick's local day and time; with the date when it is not in the next week. */ +/** "Mon 06:00" — a tick's local day and time; with the date when it is a week or more away (or past). */ export function tickWords(t: number, tz: string, now?: number): string { const w = wallOf(t, tz); const time = `${String(w.hh).padStart(2, "0")}:${String(w.mm).padStart(2, "0")}`; const day = DOW_NAMES[dowOf(w)]; - if (now !== undefined && (t - now > 6 * DAY_MS || t < now - DAY_MS)) return `${ymdOf(w)} ${time}`; + if (now !== undefined && (t - now >= 7 * DAY_MS || t < now - DAY_MS)) return `${ymdOf(w)} ${time}`; return `${day} ${time}`; } diff --git a/common/testing/schedule/opsStub.ts b/common/testing/schedule/opsStub.ts @@ -0,0 +1,116 @@ +// `report-schedule` for umtool's e2e editor stub (umtool R5): the REAL ops +// action and store over the fixture's article store, with a tick's steps +// stubbed -- what umtool/e2e/fixtures/editor-stub.mjs runs for each +// `POST /api/ops/report-schedule`. Test-only; synthetic. +// +// tsx common/testing/schedule/opsStub.ts --articles <ARTICLES_DIR> \ +// --channels a,b --generation '<json>' --job <id> (the body on stdin) +// +// Prints the action's answer as one JSON line; `tick-now` runs the tick to +// its end in this process (its claim, its record) and answers {jobId, tick}. +// The stubbed steps, by what the schedule asks: +// fetchAndBuild ok ("fetched (stub)") +// refresh no change, $0 +// generateEdition terms or question with "held" → held by the daily cap; +// "fail" → failed; a window that starts where it ends (a +// second tick the same day), or "quiet" → quiet; else a +// done iteration with a two-section report, $0.37 + +import { mkdir } from "node:fs/promises"; +import path from "node:path"; +import type { Paths } from "../../lib/paths"; +import { sanitizeGeneration } from "../../lib/generationSettings"; +import { createIteration, updateIteration, writeIterationFile } from "../../lib/report/iterations"; +import { claimTick } from "../../controller/reportSchedule"; +import { runTick, type TickDeps, type TickSteps } from "../../controller/reportTick"; +import { reportScheduleAction } from "../../controller/reportScheduleOps"; + +const argv = process.argv.slice(2); +const flag = (name: string) => { + const i = argv.indexOf(`--${name}`); + return i < 0 ? undefined : argv[i + 1]; +}; +const articlesDir = flag("articles") ?? ""; +if (!articlesDir) { + console.error("usage: opsStub.ts --articles <dir> [--channels a,b] [--generation json] [--job id]"); + process.exit(2); +} +const channels = (flag("channels") ?? "").split(",").filter(Boolean); +const generation = sanitizeGeneration(JSON.parse(flag("generation") ?? "{}")); +const jobId = flag("job") ?? `stub-tick-${Date.now()}`; +const root = path.dirname(articlesDir); +const paths = { + articlesDir, + exportIndexDir: path.join(root, ".export-index-schedule"), + generationUsageFile: path.join(root, ".generation-usage.jsonl"), + jobsDir: path.join(root, ".jobs-schedule"), +} as unknown as Paths; +await mkdir(articlesDir, { recursive: true }); + +const words = (s: { question: string; scope: { terms?: string } }) => `${s.question} ${s.scope.terms ?? ""}`.toLowerCase(); + +const steps: TickSteps = { + fetchAndBuild: async (_scope, ctx) => { + ctx.log("fetched (stub)"); + return { ok: true }; + }, + refresh: async () => ({ status: "no-change", usd: 0, reason: "nothing new matches (stub)" }), + generateEdition: async (input, ctx) => { + const w = words(input.schedule); + if (/held/.test(w)) return { status: "held-by-cap", usd: 0, estimateUsd: generation.caps.sweep, reason: `the day's Claude API spend is $${generation.caps.daily.toFixed(2)} (stub), at or past the $${generation.caps.daily.toFixed(2)} daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC` }; + if (/fail/.test(w)) return { status: "failed", usd: 0, reason: "the corpus build is gone (stub)" }; + if (input.quietCheck && (input.window.from === input.window.to || /quiet/.test(w))) { + return { status: "quiet", usd: 0, matched: 0, reason: `nothing in ${input.window.from} … ${input.window.to} matches (stub)` }; + } + const model = input.schedule.model ?? generation.models.api; + const it = await createIteration(input.article, { kind: "sweep", model, question: input.schedule.question, scope: { channels: input.schedule.scope.channels, from: input.window.from, to: input.window.to } }, paths); + await writeIterationFile( + input.article, + it.n, + "report.json", + { + format: "archilyzer-report", + version: 1, + id: input.article, + kind: "sweep", + title: input.title ?? input.schedule.topic, + sections: [ + { id: "s1", title: "What was said", body: `Two recordings in ${input.window.from} … ${input.window.to} mention it (stub).` }, + { id: "s2", title: "What changed", body: "Nothing contradicts the last edition (stub)." }, + ], + }, + paths, + ); + await updateIteration(input.article, it.n, { status: "done", usage: { [model]: { usd: 0.37, inputTokens: 1200, outputTokens: 300, calls: 4 } } }, paths); + ctx.log(`sweep ${input.article} i${it.n}: ~$0.37 so far`); + return { status: "done", iteration: it.n, usd: 0.37, matched: 2, jobId: `${jobId}-sweep` }; + }, +}; + +const deps: TickDeps = { + paths, + settings: () => ({ generation }), + knownChannels: async () => channels, + steps, +}; + +let raw = ""; +for await (const chunk of process.stdin) raw += chunk; +const body = JSON.parse(raw || "{}") as Record<string, unknown>; +const log: string[] = []; + +if (body.action === "tick-now") { + const id = String(body.id ?? ""); + const claimed = await claimTick(id, { jobId, trigger: "now" }, deps).catch((e: Error) => ({ error: e.message })); + if (!claimed) { + console.log(JSON.stringify({ ok: false, status: 409, error: `a tick of "${id}" is already queued or running` })); + } else if ("error" in claimed) { + console.log(JSON.stringify({ ok: false, status: 404, error: (claimed as { error: string }).error })); + } else { + const tick = await runTick(id, { trigger: "now", jobId }, deps, { log: (l) => log.push(l), signal: new AbortController().signal }); + console.log(JSON.stringify({ ok: true, jobId, tick, log })); + } +} else { + const out = await reportScheduleAction(body, { ...deps, lane: () => ({ held: false, armed: true }) }); + console.log(JSON.stringify(out)); +} diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts @@ -923,3 +923,79 @@ test("publish: each verb enqueues its run of stages on the publish queue; a dupl expect(stale.ok).toBe(true); expect(stale.jobs?.find((j) => j.kind === "build-site")?.existing).toBe(true); }); + +// --- recurring reports (umtool R5) ------------------------------------------ +// +// `report-schedule` over HTTP: create (its plan first: the first tick, the +// model, the cap), list, Tick now — a `report-tick` job the server's registry +// runs — pause, and delete (the plan, then the confirm). Until R4's stage 1 +// (fetch + local build) is wired into the editor, a tick's fetch step refuses +// and the tick ends failed SAYING SO; that refusal is what the tick's line in +// the schedule's history records here, and the Your call it raises. +test("report-schedule: create (plan, then the schedule), list, tick now, pause, delete (plan, then confirm)", async ({ request }) => { + test.setTimeout(120_000); + await resetData("empty"); + await settings(); + await writeChannelConfig("r5-chan", { name: "R5 channel" }); + const SERIES = `${testPaths().transcriptsDir}/reports/.series/r5-ops/series.json`; + const body = { action: "create", shape: "series", topic: "R5 ops", id: "r5-ops", channels: ["r5-chan"], cadence: "weekly mon 06:00", tz: "UTC", terms: "co-host" }; + + const plan = await ops(request, "report-schedule", { ...body, dryRun: true }); + expect(plan.status, plan.body.error).toBe(200); + const p = (plan.body as { plan?: { id: string; firstTick: string; firstTickWords: string; capUsd: number | null; firstTitle: string } }).plan!; + expect(p.id).toBe("r5-ops"); + expect(p.firstTick).toMatch(/T06:00:00\.000Z$/); + expect(p.firstTickWords).toBe("Mon 06:00"); + expect(p.firstTitle).toMatch(/^R5 ops · week of \d{4}-\d{2}-\d{2}$/); + expect(await pathExists(SERIES)).toBe(false); + + const unknown = await ops(request, "report-schedule", { ...body, channels: ["no-such-channel"] }); + expect(unknown.status).toBe(400); + expect(unknown.body.error).toMatch(/no such channel in this editor: no-such-channel/); + + const made = await ops(request, "report-schedule", body); + expect(made.status, made.body.error).toBe(200); + expect(await readJson<{ shape: string; nextTick: string; paused: boolean }>(SERIES)).toMatchObject({ shape: "series", paused: false }); + + const list = await ops(request, "report-schedule", { action: "list" }); + const listed = (list.body as { schedules?: { id: string; chip: string }[]; lane?: { held: boolean } }).schedules ?? []; + expect(listed.map((s) => s.id)).toEqual(["r5-ops"]); + expect(listed[0].chip).toMatch(/^weekly · next /); + expect((list.body as { lane?: { held: boolean } }).lane?.held).toBe(false); + + const tick = await ops(request, "report-schedule", { action: "tick-now", id: "r5-ops" }); + expect(tick.status, tick.body.error).toBe(200); + expect(tick.body.jobId).toBeTruthy(); + // One tick of a schedule at a time. + const again = await ops(request, "report-schedule", { action: "tick-now", id: "r5-ops" }); + if (again.status !== 200) expect(again.body.error).toMatch(/already queued or running/); + await expect + .poll(async () => (await readJson<{ ticks: { status: string }[] }>(SERIES)).ticks.length, { timeout: 60_000 }) + .toBeGreaterThan(0); + const s = await readJson<{ running: unknown; ticks: { status: string; reason?: string; trigger: string; jobId: string }[] }>(SERIES); + expect(s.ticks[0]).toMatchObject({ trigger: "now", jobId: tick.body.jobId, status: "failed" }); + expect(s.ticks[0].reason).toMatch(/^not wired: R4's stage 1/); + await expect.poll(async () => (await readJson<{ running: unknown }>(SERIES)).running, { timeout: 30_000 }).toBeNull(); + const job = await request.get(`${baseUrl}/api/ops/job/${tick.body.jobId}?tail=20`, { headers: AUTH }); + const j = (await job.json()) as { job?: { kind: string; status: string }; tail?: string[] }; + expect(j.job).toMatchObject({ kind: "report-tick", status: "failed" }); + expect((j.tail ?? []).join("\n")).toContain("@@report-tick "); + + const paused = await ops(request, "report-schedule", { action: "pause", id: "r5-ops" }); + expect((paused.body as { schedule?: { paused: boolean; chip: string } }).schedule).toMatchObject({ paused: true, chip: "weekly · paused" }); + + // The lane's gate: report-schedule takes "held" and nothing else. + const hold = await ops(request, "lane", { lane: "report-schedule", held: true }); + expect(hold.body).toEqual({ ok: true, lane: "report-schedule" }); + expect((await readJson<{ reportSchedule?: { held?: boolean } }>(testPaths().settingsFile)).reportSchedule?.held).toBe(true); + const start = await ops(request, "lane", { lane: "report-schedule", action: "start" }); + expect(start.status).toBe(400); + await ops(request, "lane", { lane: "report-schedule", held: false }); + + const del = await ops(request, "report-schedule", { action: "delete", id: "r5-ops" }); + expect((del.body as { confirmed?: boolean; plan?: { removes: string } })).toMatchObject({ confirmed: false, plan: { removes: expect.stringContaining("the series r5-ops") } }); + expect(await pathExists(SERIES)).toBe(true); + const gone = await ops(request, "report-schedule", { action: "delete", id: "r5-ops", confirm: true }); + expect((gone.body as { confirmed?: boolean }).confirmed).toBe(true); + expect(await pathExists(SERIES)).toBe(false); +}); diff --git a/umtool/app/api/schedules/route.ts b/umtool/app/api/schedules/route.ts @@ -0,0 +1,44 @@ +import { errorResponse } from "@/lib/articles/generation"; +import { clearPiecesCache } from "@/lib/pieces"; +import { clearRailCounts } from "@/lib/rail"; +import { readSchedules, scheduleAsk } from "@/lib/schedules"; + +export const dynamic = "force-dynamic"; + +const NO_STORE = { "cache-control": "no-store" }; +const ACTIONS = ["create", "update", "pause", "resume", "delete", "tick-now"]; + +// RECURRING REPORTS (plans/umtool-redesign.md, R5). +// +// GET every schedule, read from the article store (no editor call) +// POST { action: create | update | pause | resume | delete | tick-now, … } +// -- the editor's `report-schedule` ops action, forwarded as sent: the +// editor keeps the schedules and is their one writer (a create with +// `dryRun: true` is its plan; a delete without `confirm: true` is its +// plan). Answers the editor's JSON, or its refusal in its words. +export async function GET() { + try { + return Response.json(await readSchedules(), { headers: NO_STORE }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "send the schedule's action as an object" }, { status: 400, headers: NO_STORE }); + if (typeof body.action !== "string" || !ACTIONS.includes(body.action)) { + return Response.json({ error: `"action" is one of ${ACTIONS.join(", ")}` }, { status: 400, headers: NO_STORE }); + } + try { + const out = await scheduleAsk(body); + // A write changes what Work, the Inbox and the rail show. + if (!(body.action === "create" && body.dryRun === true) && !(body.action === "delete" && body.confirm !== true)) { + clearPiecesCache(); + clearRailCounts(); + } + return Response.json(out, { headers: NO_STORE }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/series/[id]/page.tsx b/umtool/app/series/[id]/page.tsx @@ -0,0 +1,224 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import LifecycleChip from "@/components/piece/LifecycleChip"; +import ScheduleControls from "@/components/series/ScheduleControls"; +import TickProgress from "@/components/series/TickProgress"; +import AppShell from "@/components/shell/AppShell"; +import { badgeVariants } from "@/components/ui/badge"; +import { EmptyState } from "@/components/ui/empty-state"; +import { Panel } from "@/components/ui/panel"; +import { Table, TD, TH } from "@/components/ui/table"; +import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; +import { articleHref, workHref } from "@/lib/hrefs"; +import { lifecycleOf, readLifecycle } from "@/lib/lifecycle"; +import { readScheduleView } from "@/lib/schedules"; +import type { Edition, ScheduleView, Tick } from "@/lib/schedule-types"; +import { cn } from "@/lib/utils"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// A SERIES (plans/umtool-redesign.md, R5): a recurring report's dated editions, +// the piece `s:<id>`. The head: its cadence chip ("weekly · next Mon 06:00"), +// Pause/Resume, Tick now, Edit cadence, Delete (plan, then confirm). Then the +// tick in flight, the editions newest first -- a quiet one dimmed, with its +// window, no article -- each linking its article, and the tick log: status, +// spend, reason. The editor keeps the schedule (its report-schedule lane); +// this page reads it from the article store and writes through the editor. +// +// A living report's schedule is its article's: /series/<article> goes there. +// A static segment (`series`), so nothing else's catch-all takes it. +// --------------------------------------------------------------------------- + +const usd = (n: number) => `$${n.toFixed(2)}`; +const when = (iso: string) => iso.replace("T", " ").slice(0, 16); + +const EDITION_TONE: Record<string, "on" | "info" | "open" | "blocking" | "neutral"> = { + done: "on", + quiet: "info", + running: "neutral", + failed: "blocking", + cancelled: "info", + "held-by-cap": "open", +}; +const TICK_TONE: Record<string, "on" | "info" | "open" | "blocking" | "neutral"> = { + done: "on", + "no-change": "info", + quiet: "info", + "held-by-cap": "open", + failed: "blocking", + interrupted: "blocking", + cancelled: "info", +}; + +export default async function SeriesPage({ params }: { params: Promise<{ id: string }> }) { + const { id: raw } = await params; + const id = decodeURIComponent(raw); + const read = await readScheduleView(id).catch((e: Error) => ({ problem: e.message })); + if (read && "view" in read && read.view.shape === "living") redirect(read.view.href); + const crumbs = [{ href: workHref({ recurring: "1" }), label: "Work" }]; + if (!read || "problem" in read) { + return ( + <div className="flex h-full flex-col"> + <AppShell active="work" crumbs={[...crumbs, { label: id }]} /> + <main className="px-7 pt-6"> + <EmptyState title={read ? "This series cannot be read" : `No series “${id}”`}> + {read && <span role="alert">{read.problem}</span>}{" "} + <Link href={workHref({ recurring: "1" })} className="ink-link"> + Recurring reports + </Link> + </EmptyState> + </main> + </div> + ); + } + const v = read.view; + const life = lifecycleOf(await readLifecycle(), v.piece); + const editions = [...(v.editions ?? [])].sort((a, b) => b.n - a.n); + const ticks = [...v.ticks].reverse(); + return ( + <div className="flex h-full flex-col"> + <AppShell + active="work" + crumbs={[...crumbs, { label: v.topic }]} + meta={ + <span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted" data-series-meta=""> + <span className={badgeVariants({ variant: "neutral", size: "sm" })}>series</span> + <span> + {editions.length} edition{editions.length === 1 ? "" : "s"} + </span> + <span className="font-mono text-meter" data-series-spent={v.spentUsd.toFixed(2)}> + {usd(v.spentUsd)} spent + </span> + <span className="font-mono text-[11px]">{v.piece}</span> + </span> + } + actions={<LifecycleChip piece={v.piece} title={v.topic} state={life} />} + below={ + <div className="flex flex-wrap items-center gap-x-4 gap-y-2" data-series={v.id} data-series-paused={v.paused ? "yes" : "no"}> + <span className={cn(badgeVariants({ variant: v.paused ? "open" : "meter", size: "md" }))} data-schedule-chip={v.chip}> + <i aria-hidden="true" className={cn("inline-block size-[7px] rounded-full", v.paused ? "bg-doubt-text" : "bg-meter")} /> + {v.chip} + </span> + <ScheduleControls schedule={{ id: v.id, shape: v.shape, paused: v.paused, cadence: v.cadence, running: !!v.running }} /> + </div> + } + /> + <main className="deck-main flex flex-1 flex-col gap-4 px-4 pb-6 pt-3"> + {v.running && !v.running.jobId.startsWith("pending-") && <TickProgress jobId={v.running.jobId} />} + <Panel title="Editions" aside={<span className="text-muted">newest first</span>} data-series-editions=""> + {editions.length === 0 ? ( + <p className="m-0 text-[12.5px] text-muted" data-series-empty=""> + No edition yet. The first tick is {v.nextWords ?? "not planned (paused)"}. + </p> + ) : ( + <ol className="m-0 flex list-none flex-col p-0" aria-label="editions"> + {editions.map((e) => ( + <EditionRow key={e.n} e={e} /> + ))} + </ol> + )} + </Panel> + <Panel title="Ticks" aside={<span className="text-muted">{ticks.length} recorded</span>} data-series-ticks=""> + {ticks.length === 0 ? ( + <p className="m-0 text-[12.5px] text-muted">Nothing has ticked yet.</p> + ) : ( + <Table aria-label="ticks"> + <thead> + <tr> + <TH>When</TH> + <TH>How</TH> + <TH>Status</TH> + <TH>Edition</TH> + <TH className="text-right">Spend</TH> + <TH>Why</TH> + </tr> + </thead> + <tbody> + {ticks.map((t, i) => ( + <TickRow key={`${t.at}-${i}`} t={t} /> + ))} + </tbody> + </Table> + )} + </Panel> + <Scope v={v} /> + </main> + </div> + ); +} + +function EditionRow({ e }: { e: Edition }) { + const quiet = e.status === "quiet"; + return ( + <li + data-edition={e.n} + data-edition-status={e.status} + className={cn("grid grid-cols-[40px_minmax(0,1fr)_190px_110px_70px] items-baseline gap-x-3 border-b border-seam py-2 last:border-b-0", quiet && "opacity-55")} + > + <span className="font-mono text-[11.5px] text-muted">#{e.n}</span> + <span className="min-w-0"> + {e.article && e.status !== "quiet" ? ( + <Link href={articleHref({ site: ARTICLES_KEY, id: e.article })} prefetch={false} className="block truncate font-medium text-inherit hover:underline" data-edition-link={e.article}> + {e.title} + </Link> + ) : ( + <span className="block truncate">{e.title}</span> + )} + {e.reason && <small className="block truncate text-[11.5px] text-muted-2">{e.reason}</small>} + </span> + <span className="font-mono text-[11.5px] text-text-2" data-edition-window={`${e.window.from}/${e.window.to}`}> + {e.window.from} … {e.window.to} + </span> + <span className={badgeVariants({ variant: EDITION_TONE[e.status] ?? "neutral", size: "sm" })}>{e.status}</span> + <span className="text-right font-mono text-[12px] text-meter">{e.usd ? usd(e.usd) : "$0"}</span> + </li> + ); +} + +function TickRow({ t }: { t: Tick }) { + return ( + <tr data-tick-status={t.status}> + <TD className="whitespace-nowrap font-mono text-[11.5px]">{when(t.at)}</TD> + <TD className="text-[12px]">{t.trigger === "now" ? "tick now" : t.missed ? `scheduled · stood in for ${t.missed}` : "scheduled"}</TD> + <TD> + <span className={badgeVariants({ variant: TICK_TONE[t.status] ?? "neutral", size: "sm" })}>{t.status}</span> + </TD> + <TD className="font-mono text-[11.5px]">{t.edition ? `#${t.edition}` : t.iteration ? `i${t.iteration}` : "—"}</TD> + <TD numeric className="text-meter"> + {usd(t.usd)} + {t.estimateUsd !== undefined && t.status === "held-by-cap" ? <small className="block text-muted">up to {usd(t.estimateUsd)}</small> : null} + </TD> + <TD className="text-[12px]">{t.reason ?? ""}</TD> + </tr> + ); +} + +function Scope({ v }: { v: ScheduleView }) { + return ( + <Panel title="What it asks" data-series-scope=""> + <dl className="m-0 grid grid-cols-[120px_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-[12.5px]"> + <dt className="text-muted">Question</dt> + <dd className="m-0">{v.question}</dd> + <dt className="text-muted">Channels</dt> + <dd className="m-0 font-mono text-[12px]">{v.scope.channels.join(", ")}</dd> + {v.scope.case && ( + <> + <dt className="text-muted">Board</dt> + <dd className="m-0 font-mono text-[12px]">{v.scope.case}</dd> + </> + )} + <dt className="text-muted">Window check</dt> + <dd className="m-0">{v.scope.terms ? <span className="font-mono text-[12px]">{v.scope.terms}</span> : "any recording in scope"}</dd> + <dt className="text-muted">Cadence</dt> + <dd className="m-0"> + {v.cadenceWords} <span className="text-muted">({v.tz})</span> + </dd> + <dt className="text-muted">Model · cap</dt> + <dd className="m-0 font-mono text-[12px]"> + {v.model ?? "the policy's"} · {v.caps?.maxUsd ? `${usd(v.caps.maxUsd)} a tick` : "the policy's sweep cap"} + </dd> + </dl> + </Panel> + ); +} diff --git a/umtool/app/work/page.tsx b/umtool/app/work/page.tsx @@ -21,7 +21,8 @@ export const dynamic = "force-dynamic"; // --------------------------------------------------------------------------- // WORK (plans/umtool-redesign.md, P3; canvas "Work"): every piece in one lit // list -- an article with its video projects, or a project no article claims. -// Facets: stage, kind, site, lifecycle (active by default), and a search. It +// Facets: stage, kind, site, lifecycle (active by default), recurring (R5: the +// series and the living reports, each with its cadence chip), and a search. It // replaced three lists, and reads their keys (lib/work/facets.mjs): /browse's // (kind, template, state, open, sort), /articles' (status, notes, audience) // and /sites' (site; `by=site` groups by site). A key with no chip of its own @@ -60,7 +61,7 @@ export default async function WorkPage({ searchParams }: { searchParams: Promise const href = (next: Partial<Search>) => workHref({ ...sp, deleted: undefined, freed: undefined, ...next }); const sites = [...new Set(all.map((r) => r.site).filter((s): s is string => !!s))].sort(); - const kinds = [{ id: "article", label: "Article" }, ...KINDS.map((k) => ({ id: k.id, label: k.label }))].filter( + const kinds = [{ id: "article", label: "Article" }, { id: "series", label: "Series" }, ...KINDS.map((k) => ({ id: k.id, label: k.label }))].filter( (k) => all.some((r) => r.kinds.includes(k.id)), ); const bySite = sp.by === "site"; @@ -144,6 +145,10 @@ export default async function WorkPage({ searchParams }: { searchParams: Promise </Link> )} </ToolbarGroup> + {/* The recurring reports (R5): the series and the living reports. */} + <ToolbarGroup label="Recurring" data-facet="recurring"> + <Chip href={href({ recurring: sp.recurring === "1" ? "" : "1" })} on={sp.recurring === "1"} label="Recurring" n={n({ recurring: "1" })} /> + </ToolbarGroup> <ToolbarGroup label="View"> <Chip href={href({ by: bySite ? "" : "site" })} on={bySite} label="By site" /> <Chip href={href({ sort: sp.sort === "name" ? "" : "name" })} on={sp.sort === "name"} label="By name" /> @@ -242,6 +247,7 @@ function Row({ r }: { r: WorkRow }) { data-status={r.status ?? undefined} data-audience={r.audience ?? undefined} data-open-notes={r.counts.notes} + data-recurring={r.recurring ? "" : undefined} className="grid grid-cols-[minmax(0,1fr)_190px_160px_130px_56px] items-center gap-x-3.5" > <div className="flex min-w-0 items-center gap-2"> @@ -249,7 +255,14 @@ function Row({ r }: { r: WorkRow }) { <Link href={r.href} prefetch={false} className="block truncate font-medium text-inherit hover:underline" data-piece-link=""> {r.title} </Link> - <small className="block truncate font-mono text-[11px] text-muted-2">{r.id}</small> + <small className="block truncate font-mono text-[11px] text-muted-2"> + {r.id} + {r.chip && ( + <span className="ml-2 font-sans text-meter" data-work-chip=""> + {r.chip} + </span> + )} + </small> </div> <LitActions className="shrink-0 gap-0"> {r.lifecycle === "active" ? ( diff --git a/umtool/bin/schedule.ts b/umtool/bin/schedule.ts @@ -0,0 +1,79 @@ +// `umtool schedule` -- the recurring reports, from a terminal (R5). +// +// TypeScript, because the schedules are common's (lib/report/schedule/) and +// umtool's reading of them is lib/schedules.ts: bin/umtool.mjs runs this file +// through tsx, from umtool/ (the `@/` paths). Read-only: a schedule is +// written through the editor (`pnpm ops report-schedule`), never here. +// +// umtool schedule list [--json] every schedule: its chip, its last tick, its spend +// umtool schedule show <id> [--json] one: its scope, its editions, its tick log +import { readScheduleView, readSchedules } from "../lib/schedules"; +import type { ScheduleView } from "../lib/schedule-types"; + +const args = process.argv.slice(2); +const json = args.includes("--json"); +const [sub, id] = args.filter((a) => !a.startsWith("--")); +const usd = (n: number) => `$${n.toFixed(2)}`; + +function line(v: ScheduleView): string { + const last = v.ticks.at(-1); + const call = v.call ? ` ← your call: ${v.call.status}${v.call.reason ? ` (${v.call.reason})` : ""}` : ""; + return `${v.shape.padEnd(7)} ${v.id.padEnd(32)} ${v.chip.padEnd(30)} ${(last ? `${last.status} ${last.at.slice(0, 16)}` : "never ticked").padEnd(28)} ${usd(v.spentUsd)}${v.running ? ` ticking (job ${v.running.jobId})` : ""}${call}`; +} + +if (sub === "list" || sub === undefined) { + const { schedules, problems } = await readSchedules(); + if (json) { + console.log(JSON.stringify({ schedules, problems }, null, 2)); + } else { + if (!schedules.length) console.log("no recurring reports (make one in Create, or `pnpm ops report-schedule`)"); + for (const v of schedules) console.log(line(v)); + for (const p of problems) console.log(`! ${p.id}: ${p.problem}`); + } + process.exit(problems.length ? 1 : 0); +} + +if (sub === "show") { + if (!id) { + console.error("which schedule? `umtool schedule show <id>`"); + process.exit(2); + } + const r = await readScheduleView(id); + if (!r) { + console.error(`no schedule "${id}"`); + process.exit(1); + } + if ("problem" in r) { + console.error(`the schedule "${id}" does not read: ${r.problem}`); + process.exit(1); + } + const v = r.view; + if (json) { + console.log(JSON.stringify(v, null, 2)); + process.exit(0); + } + console.log(`${v.topic} (${v.shape} ${v.id})`); + console.log(` ${v.chip} · ${v.cadenceWords} (${v.tz})${v.paused ? " · paused" : ""}`); + console.log(` question ${v.question}`); + console.log(` channels ${v.scope.channels.join(", ")}${v.scope.case ? ` (board ${v.scope.case})` : ""}`); + if (v.scope.terms) console.log(` terms ${v.scope.terms}`); + if (v.shape === "living") console.log(` article ${v.article ?? v.id}${v.autoMakeCurrent ? " (made current automatically)" : ""}`); + console.log(` spent ${usd(v.spentUsd)} over ${v.ticks.length} tick${v.ticks.length === 1 ? "" : "s"}`); + if (v.running) console.log(` ticking job ${v.running.jobId} (${v.running.trigger}, since ${v.running.at})`); + if (v.editions?.length) { + console.log("\n editions, newest first"); + for (const e of [...v.editions].reverse()) { + console.log(` #${String(e.n).padEnd(3)} ${e.status.padEnd(11)} ${e.window.from} … ${e.window.to} ${usd(e.usd).padStart(7)} ${e.article ?? "(quiet: no article)"} ${e.title}`); + } + } + if (v.ticks.length) { + console.log("\n ticks, newest first"); + for (const t of [...v.ticks].reverse().slice(0, 20)) { + console.log(` ${t.at.slice(0, 16)} ${t.trigger.padEnd(8)} ${t.status.padEnd(12)} ${usd(t.usd).padStart(7)} ${t.reason ?? ""}`); + } + } + process.exit(0); +} + +console.error(`unknown: umtool schedule ${sub} — list | show <id>`); +process.exit(2); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -16,6 +16,7 @@ // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool decisions [--json] // umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them +// umtool schedule list | show <id> [--json] the recurring reports (R5), read-only // umtool folders [--json] // umtool kinds [--json] // umtool window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] @@ -670,6 +671,8 @@ function usage() { " umtool decisions [--json]", " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them", " (--all: the hidden ones on parked/done pieces, and the quiet group)", + " umtool schedule list | show <id> [--json] the recurring reports: chip, editions, tick log (read-only;", + " a schedule is written through the editor: `pnpm ops report-schedule`)", " umtool folders [--json]", " umtool kinds [--json]", " umtool window <project> <clip> [--start S] [--end E] [--lock|--lock-end|…]", @@ -730,12 +733,18 @@ const COMMANDS = { "check-sources": cmdCheckSources, notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))), inbox: cmdInbox, + schedule: () => tsxScript("schedule"), help: usage, }; // `umtool inbox`: bin/inbox.ts, through tsx -- the inbox is the app's // TypeScript (lib/inbox.ts), run from umtool/ so its `@/` paths resolve. -async function cmdInbox() { +// `umtool schedule` (R5) is bin/schedule.ts, the same way. +function cmdInbox() { + return tsxScript("inbox"); +} + +async function tsxScript(name) { const { createRequire } = await import("node:module"); const { fileURLToPath } = await import("node:url"); const here = path.dirname(fileURLToPath(import.meta.url)); @@ -743,10 +752,10 @@ async function cmdInbox() { try { cli = createRequire(import.meta.url).resolve("tsx/cli"); } catch { - die("umtool inbox needs tsx (the workspace's devDependency): run `pnpm install` at the repo root"); + die(`umtool ${name} needs tsx (the workspace's devDependency): run \`pnpm install\` at the repo root`); } const code = await new Promise((resolve) => { - const child = spawn(process.execPath, [cli, path.join(here, "inbox.ts"), ...argv.slice(argv.indexOf("inbox") + 1)], { + const child = spawn(process.execPath, [cli, path.join(here, `${name}.ts`), ...argv.slice(argv.indexOf(name) + 1)], { cwd: path.dirname(here), stdio: "inherit", }); diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -13,6 +13,9 @@ import WorkspacePanel from "@/components/articles/WorkspacePanel"; import IterationsView from "@/components/articles/IterationsView"; import PieceFrame from "@/components/piece/PieceFrame"; import PolicyChip, { PolicyChipShell } from "@/components/piece/PolicyChip"; +import ScheduleControls from "@/components/series/ScheduleControls"; +import { livingScheduleOf } from "@/lib/schedules"; +import { seriesHref } from "@/lib/hrefs"; import DeleteProject from "@/components/projects/DeleteProject"; import ReportTabBody, { reportCounts } from "@/components/projects/report/ReportTabBody"; import { badgeVariants } from "@/components/ui/badge"; @@ -105,7 +108,10 @@ export default async function ArticlePage({ const iterations = await iterationCount(site, reportId); const hasIterations = iterations > 0; const missing = !read.report && read.problems[0]?.message === "no report.json"; - if (missing && !hasIterations) notFound(); + // A living report waiting for its first tick (R5) has no iteration yet, and + // is a page all the same: its schedule is. + const living = store ? await livingScheduleOf(reportId).catch(() => null) : null; + if (missing && !hasIterations && !living) notFound(); const r = read.report; const a = { site, id: reportId }; @@ -115,6 +121,12 @@ export default async function ArticlePage({ readArticlePieceFrame(site, reportId, { hasIterations, hasReport: !!r }), readPieceGraph(), ]); + // A living report's schedule (R5): its chip in the head. + const schedule = living ? { id: living.id, shape: living.shape, chip: living.chip, paused: living.paused, cadence: living.cadence, running: !!living.running } : null; + // An edition's series (R5). + const seriesId = frame.piece?.series ?? null; + const series = seriesId ? graph.byId.get(`s:${seriesId}`) : undefined; + const edition = seriesId ? { title: series?.title ?? seriesId, href: seriesHref(seriesId) } : null; const video = frame.piece ? await articleVideo(frame.piece, graph, sp.project ?? null) : null; const videoRef = video?.project ? await projectRef(video.project.id) : null; const detail = videoRef ? await readClipDetail(videoRef.dir) : null; @@ -177,10 +189,13 @@ export default async function ArticlePage({ <PolicyChip /> </Suspense> } + schedule={schedule} + edition={edition} more={ <> <span className="px-2 pb-1 pt-0.5 font-mono text-[11px] text-muted">{frame.pieceId}</span> {store && <DeleteArticle article={reportId} published={published} />} + {schedule && <ScheduleControls part="menu" schedule={schedule} />} {videoRef && ( <> <span className="px-2 pb-1 pt-1.5 font-mono text-[11px] text-muted" data-piece-more-project={videoRef.id}> diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -38,7 +38,8 @@ const AUTONOMY_SAYS: Record<Autonomy, string> = { auto: "everything runs through the editor until a cap; past it, it waits", }; -function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) { +// Exported for Create's recurring form (R5): the same picker, the same channels. +export function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) { const [all, setAll] = useState<EditorChannel[] | null>(null); const [error, setError] = useState(""); const [q, setQ] = useState(""); diff --git a/umtool/components/create/CreateView.tsx b/umtool/components/create/CreateView.tsx @@ -9,6 +9,7 @@ import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; import { createHref, type Make } from "@/lib/hrefs"; import type { CreateData } from "@/lib/create"; import { ArticleVideoForm, BoardForm, ResearchForm } from "./forms"; +import RecurringForm from "./RecurringForm"; // --------------------------------------------------------------------------- // CREATE (plans/umtool-redesign.md, P5; canvas "Create"): "What are you @@ -42,6 +43,8 @@ function lines(d: CreateData): { group: string; lines: Line[] }[][] { lines: [ { make: "article", title: "From a question", sub: "A sweep writes iteration 1 · estimate shown before it runs", action: "Start sweep" }, { make: "article-board", title: "From a board", sub: boardSub, action: "Draft article" }, + // R5: a living report or a dated series, on a schedule the editor keeps. + { make: "recurring", title: "A recurring report", sub: d.schedules ? `Living or a dated series · ${plural(d.schedules, "schedule")}` : "Living, or a dated series · the editor keeps the schedule", action: "Set a schedule" }, ], }, ], @@ -135,6 +138,8 @@ export default function CreateView({ return ( <NewArticleForm initialPolicy={data.policy} today={data.today} taken={data.taken} showPolicy={false} framed={false} history={data.history} onCancel={cancel} /> ); + case "recurring": + return <RecurringForm cases={data.cases} initialCase={initialCase} onCancel={cancel} />; case "article-board": return <BoardForm to="article" cases={data.cases} casesError={data.casesError} initialCase={initialCase} onCancel={cancel} />; case "video-board": diff --git a/umtool/components/create/RecurringForm.tsx b/umtool/components/create/RecurringForm.tsx @@ -0,0 +1,267 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { ChannelPicker } from "@/components/articles/NewArticleForm"; +import CadenceFields, { DEFAULT_CADENCE } from "@/components/series/CadenceFields"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { articleHref, seriesHref } from "@/lib/hrefs"; +import type { CaseSummary } from "@/lib/research/case-types"; +import type { Cadence } from "@/lib/schedule-types"; + +// --------------------------------------------------------------------------- +// CREATE → "A recurring report" (plans/umtool-redesign.md, R5): a topic, its +// scope (channels, or a board's), a cadence and a shape -- +// +// Living report one article kept current +// Series a new dated edition each tick +// +// -- then PLAN, THEN CONFIRM: "Plan the schedule" asks the editor what it +// would make (its `report-schedule` create with dryRun: the first tick's time, +// the model and its cap, a series' first window and title), and only "Start +// the schedule" makes it. Nothing schedules itself: the editor keeps what the +// operator started here. +// +// Labels are contracts (e2e/recurring.spec.ts): the form "a recurring +// report", the radios "Living report" / "Series", the fields "topic", +// "question", "window check", the scope radios "Channels" / "A board", the +// board select "board", the plan region "plan recurring report", the buttons +// "Plan the schedule", "Start the schedule", "Change it". +// --------------------------------------------------------------------------- + +type Plan = { + id: string; + shape: "living" | "series"; + article: string | null; + cadence: string; + tz: string; + firstTick: string; + firstTickWords: string; + firstWindow: { from: string; to: string } | null; + firstTitle: string | null; + model: string; + provider: "api" | "local"; + capUsd: number | null; + dailyCapUsd: number; + existingArticle: boolean; + warnings: string[]; +}; + +const SHAPES = [ + { id: "living", label: "Living report", sub: "One article kept current: each tick fetches what is new and updates it." }, + { id: "series", label: "Series", sub: "A new dated edition each tick, over only the window since the last one." }, +] as const; + +const usd = (n: number) => `$${n.toFixed(2)}`; +// A board's date is YYYYMMDD or YYYY-MM-DD; a schedule's is the latter. +const ymd = (d: string) => (/^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}` : d); + +async function post<T>(body: Record<string, unknown>): Promise<T> { + const r = await fetch("/api/schedules", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const b = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(b?.error ?? `HTTP ${r.status}`); + return b as T; +} + +export default function RecurringForm({ cases, initialCase, onCancel }: { cases: CaseSummary[]; initialCase: string | null; onCancel: () => void }) { + const router = useRouter(); + const hydrated = useHydrated(); + const boards = cases.filter((c) => (c.scope.channels ?? []).length > 0); + const [shape, setShape] = useState<"living" | "series">("series"); + const [topic, setTopic] = useState(""); + const [question, setQuestion] = useState(""); + const [scopeBy, setScopeBy] = useState<"channels" | "board">(initialCase && boards.some((c) => c.id === initialCase) ? "board" : "channels"); + const [board, setBoard] = useState(initialCase && boards.some((c) => c.id === initialCase) ? initialCase : (boards[0]?.id ?? "")); + const [channels, setChannels] = useState<string[]>([]); + const [terms, setTerms] = useState(""); + const [cadence, setCadence] = useState<Cadence>(DEFAULT_CADENCE); + const [autoCurrent, setAutoCurrent] = useState(false); + const [plan, setPlan] = useState<Plan | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const confirmRef = useRef<HTMLButtonElement>(null); + useEffect(() => { + if (plan) confirmRef.current?.focus(); + }, [plan]); + + const chosen = boards.find((c) => c.id === board) ?? null; + const scopeChannels = scopeBy === "board" ? (chosen?.scope.channels ?? []) : channels; + // A board's terms are its query, unless the operator typed their own. + const windowTerms = terms.trim() || (scopeBy === "board" ? (chosen?.scope.query ?? "") : ""); + + const body = () => ({ + action: "create", + shape, + topic: topic.trim(), + ...(question.trim() ? { question: question.trim() } : {}), + channels: scopeChannels, + ...(scopeBy === "board" && chosen ? { case: chosen.id, ...(chosen.scope.dateFrom ? { from: ymd(chosen.scope.dateFrom) } : {}), ...(chosen.scope.regex && !terms.trim() ? { regex: true } : {}) } : {}), + ...(shape === "series" && windowTerms ? { terms: windowTerms } : {}), + // On the editor's clock: it keeps the schedule (the plan names its zone). + cadence, + ...(shape === "living" && autoCurrent ? { autoMakeCurrent: true } : {}), + }); + + const ask = async () => { + if (!topic.trim()) return setError("name the topic"); + if (!scopeChannels.length) return setError(scopeBy === "board" ? "that board names no channel" : "pick at least one channel"); + setBusy(true); + setError(null); + try { + const r = await post<{ plan: Plan }>({ ...body(), dryRun: true }); + setPlan(r.plan); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + }; + + const start = async () => { + setBusy(true); + setError(null); + try { + const r = await post<{ schedule: { id: string; shape: string; article?: string } }>(body()); + const s = r.schedule; + router.push(s.shape === "living" ? articleHref({ site: "articles", id: s.article ?? s.id }) : seriesHref(s.id)); + } catch (e) { + setError((e as Error).message); + setBusy(false); + } + }; + + // Any change after a plan asks for the plan again. + const edit = <T,>(set: (v: T) => void) => (v: T) => { + set(v); + setPlan(null); + }; + + return ( + <form + aria-label="a recurring report" + className="flex flex-col gap-3" + onKeyDown={(e) => { + if (e.key === "Escape" && !e.defaultPrevented) { + e.preventDefault(); + if (plan) setPlan(null); + else onCancel(); + } + }} + onSubmit={(e) => { + e.preventDefault(); + if (plan) void start(); + else void ask(); + }} + > + <fieldset className="m-0 flex flex-wrap gap-x-5 gap-y-2 border-0 p-0" aria-label="shape"> + {SHAPES.map((s) => ( + <label key={s.id} className="flex max-w-[22rem] items-start gap-2 text-[13px]" data-shape={s.id}> + <input type="radio" name="shape" value={s.id} checked={shape === s.id} onChange={() => edit(setShape)(s.id)} aria-label={s.label} className="mt-1" /> + <span> + <b className="block font-semibold">{s.label}</b> + <small className="block text-[12px] text-muted">{s.sub}</small> + </span> + </label> + ))} + </fieldset> + <div className="flex flex-wrap items-end gap-x-3 gap-y-2.5"> + <Field label="Topic" hint={shape === "series" ? "Each edition is titled “<topic> · week of <date>”" : "The article's name"} className="min-w-[16rem] flex-1"> + <Input autoFocus data-autofocus="" required value={topic} onChange={(e) => edit(setTopic)(e.target.value)} aria-label="topic" placeholder="e.g. Co-host updates" /> + </Field> + <Field label="Question" hint="What each tick asks; the topic, unless asked" className="min-w-[16rem] flex-[2]"> + <Input value={question} onChange={(e) => edit(setQuestion)(e.target.value)} aria-label="question" placeholder="the topic, unless asked" /> + </Field> + </div> + <fieldset className="m-0 flex flex-col gap-2 border-0 p-0" aria-label="scope"> + <span className="flex gap-4 text-[12.5px]"> + <label className="flex items-center gap-1.5"> + <input type="radio" name="scope" checked={scopeBy === "channels"} onChange={() => edit(setScopeBy)("channels")} aria-label="Channels" /> + Channels + </label> + <label className={boards.length ? "flex items-center gap-1.5" : "flex items-center gap-1.5 text-muted-2"}> + <input type="radio" name="scope" disabled={!boards.length} checked={scopeBy === "board"} onChange={() => edit(setScopeBy)("board")} aria-label="A board" /> + A board{boards.length ? "" : " (none names channels)"} + </label> + </span> + {scopeBy === "channels" ? ( + <ChannelPicker value={channels} onChange={edit(setChannels)} /> + ) : ( + <Field label="Board" hint={chosen ? `${(chosen.scope.channels ?? []).join(", ")}${chosen.scope.dateFrom ? ` · from ${chosen.scope.dateFrom}` : ""}` : undefined}> + <Select aria-label="board" value={board} onChange={(e) => edit(setBoard)(e.target.value)}> + {boards.map((c) => ( + <option key={c.id} value={c.id}> + {c.title} + </option> + ))} + </Select> + </Field> + )} + </fieldset> + <div className="flex flex-wrap items-end gap-x-5 gap-y-2.5"> + <CadenceFields value={cadence} onChange={edit(setCadence)} disabled={busy} /> + {shape === "series" ? ( + <Field label="Window check" hint="What a window must match to be worth a sweep; empty: any recording" className="min-w-[14rem] flex-1"> + <Input value={terms} onChange={(e) => edit(setTerms)(e.target.value)} aria-label="window check" placeholder={chosen?.scope.query ?? "e.g. co-host|guest"} /> + </Field> + ) : ( + <label className="flex items-center gap-1.5 pb-1 text-[12.5px]"> + <input type="checkbox" checked={autoCurrent} onChange={(e) => edit(setAutoCurrent)(e.target.checked)} aria-label="make each update current" /> + Make each update current without review + </label> + )} + </div> + {plan && ( + <section role="region" aria-label="plan recurring report" data-plan-schedule={plan.id} className="rounded-[3px] border border-seam-2 bg-ink p-3 text-[12.5px]"> + <p className="m-0 font-medium" data-plan-first-tick={plan.firstTick}> + {plan.shape === "series" ? "Series" : "Living report"} <span className="font-mono">{plan.id}</span> · {plan.cadence} · first tick {plan.firstTickWords}{" "} + <span className="text-muted">({plan.tz})</span> + </p> + <ul className="m-0 mt-1 list-disc pl-5 text-text-2"> + <li data-plan-cap=""> + {plan.model} · {plan.provider === "local" ? "the local model: no API spend" : `up to ${usd(plan.capUsd ?? 0)} a tick`} · daily cap {usd(plan.dailyCapUsd)} + </li> + {plan.firstWindow && plan.firstTitle && ( + <li> + first edition: {plan.firstTitle} ({plan.firstWindow.from} … {plan.firstWindow.to}); a window nothing matches is quiet, $0 + </li> + )} + {plan.shape === "living" && <li>{plan.existingArticle ? `keeps ${plan.article} current` : `a new article, ${plan.article}: its first tick is its first sweep`}</li>} + </ul> + {plan.warnings.length > 0 && ( + <ul aria-label="worth knowing" className="m-0 mt-1 list-disc pl-5 text-doubt-text"> + {plan.warnings.map((w) => ( + <li key={w}>{w}</li> + ))} + </ul> + )} + </section> + )} + <div className="flex flex-wrap items-center gap-2"> + {plan ? ( + <> + <Button ref={confirmRef} type="submit" variant="go" disabled={!hydrated || busy} data-schedule-start=""> + {busy ? "Starting…" : "Start the schedule"} + </Button> + <Button type="button" variant="quiet" onClick={() => setPlan(null)}> + Change it + </Button> + </> + ) : ( + <Button type="submit" variant="go" disabled={!hydrated || busy || !topic.trim()} data-schedule-plan=""> + {busy ? "Planning…" : "Plan the schedule"} + </Button> + )} + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + {error && ( + <p role="alert" className="m-0 basis-full text-[12px] text-reject-text"> + {error} + </p> + )} + </div> + </form> + ); +} diff --git a/umtool/components/piece/PieceFrame.tsx b/umtool/components/piece/PieceFrame.tsx @@ -8,6 +8,10 @@ import type { Crumb } from "@/components/shell/AppHeader"; import { articleHref } from "@/lib/hrefs"; import { researchCaseHref } from "@/lib/research/hrefs"; import type { PieceFrame as Frame } from "@/lib/pieces/frame"; +import ScheduleControls from "@/components/series/ScheduleControls"; +import { badgeVariants as chipVariants } from "@/components/ui/badge"; +import type { Cadence } from "@/lib/schedule-types"; +import { cn } from "@/lib/utils"; import LifecycleChip from "./LifecycleChip"; import Menu from "./Menu"; import PieceKeys from "./PieceKeys"; @@ -22,6 +26,8 @@ import PieceKeys from "./PieceKeys"; // and the article piece (components/articles/ArticlePage.tsx, P4a-2) hand it // the trail, the tabs and their addresses, the counts and the body. `1`–`9` // open the tabs, in order, and `n` runs the Next card's action (PieceKeys). +// A living report's article carries its schedule's cadence chip in the head, +// with Pause/Resume and Tick now (`schedule`, R5); an edition says its series. // --------------------------------------------------------------------------- export type FrameTab = { id: string; label: string; href: string }; @@ -37,6 +43,8 @@ export default function PieceFrame({ meta, head, more, + schedule, + edition, children, }: { /** The rail's key (components/AppNav.tsx): a piece is under Work, never Work itself -- `projects` or `articles`. */ @@ -58,6 +66,10 @@ export default function PieceFrame({ note?: React.ReactNode; /** The ⋯ menu's items (Delete project …). */ more?: React.ReactNode; + /** A living report's schedule (R5): the cadence chip, Pause/Resume, Tick now. */ + schedule?: { id: string; shape: string; chip: string; paused: boolean; cadence: Cadence; running: boolean } | null; + /** The series this article is an edition of (R5). */ + edition?: { title: string; href: string } | null; children: React.ReactNode; }) { const hrefs = tabs.map((t) => t.href); @@ -111,6 +123,23 @@ export default function PieceFrame({ </span> )} {head} + {schedule && ( + <span className="inline-flex flex-wrap items-center gap-2" data-piece-schedule={schedule.id}> + <span className={cn(chipVariants({ variant: schedule.paused ? "open" : "meter", size: "md" }))} data-schedule-chip={schedule.chip}> + <i aria-hidden="true" className={cn("inline-block size-[7px] rounded-full", schedule.paused ? "bg-doubt-text" : "bg-meter")} /> + {schedule.chip} + </span> + <ScheduleControls part="head" schedule={schedule} /> + </span> + )} + {edition && ( + <span className="text-[12.5px] text-muted" data-piece-edition-of={edition.href}> + an edition of{" "} + <Link href={edition.href} prefetch={false} className="ink-link"> + {edition.title} + </Link> + </span> + )} </div> } /> diff --git a/umtool/components/series/CadenceFields.tsx b/umtool/components/series/CadenceFields.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { Field, Input, Select } from "@/components/ui/field"; +import type { Cadence } from "@/lib/schedule-types"; + +// A RECURRING REPORT'S CADENCE, as fields (R5): Create's recurring form and a +// schedule's "Edit cadence" share them. Daily · Weekly on a day · Every N days, +// at a time on the editor's clock. The value is the cadence common parses +// (lib/report/schedule/cadence.ts), so a field never says what the editor +// would not keep. + +const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + +export const DEFAULT_CADENCE: Cadence = { kind: "weekly", dow: 1, at: "06:00" }; + +export default function CadenceFields({ value, onChange, disabled }: { value: Cadence; onChange: (c: Cadence) => void; disabled?: boolean }) { + const at = value.at; + return ( + <div className="flex flex-wrap items-end gap-x-3 gap-y-2" data-cadence-fields={value.kind}> + <Field label="Cadence"> + <Select + aria-label="cadence" + value={value.kind} + disabled={disabled} + onChange={(e) => { + const k = e.target.value; + onChange(k === "daily" ? { kind: "daily", at } : k === "weekly" ? { kind: "weekly", dow: value.kind === "weekly" ? value.dow : 1, at } : { kind: "every", days: value.kind === "every" ? value.days : 3, at }); + }} + > + <option value="daily">Daily</option> + <option value="weekly">Weekly</option> + <option value="every">Every N days</option> + </Select> + </Field> + {value.kind === "weekly" && ( + <Field label="On"> + <Select aria-label="day of the week" value={value.dow} disabled={disabled} onChange={(e) => onChange({ kind: "weekly", dow: Number(e.target.value), at })}> + {DAYS.map((d, i) => ( + <option key={d} value={i}> + {d} + </option> + ))} + </Select> + </Field> + )} + {value.kind === "every" && ( + <Field label="Days"> + <Input + type="number" + min={2} + max={365} + aria-label="every how many days" + className="w-20" + value={value.days} + disabled={disabled} + onChange={(e) => onChange({ kind: "every", days: Math.max(2, Math.min(365, Math.round(Number(e.target.value) || 2))), at })} + /> + </Field> + )} + <Field label="At"> + <Input type="time" aria-label="at" className="w-28" value={at} disabled={disabled} onChange={(e) => onChange({ ...value, at: e.target.value || at })} /> + </Field> + </div> + ); +} diff --git a/umtool/components/series/ScheduleControls.tsx b/umtool/components/series/ScheduleControls.tsx @@ -0,0 +1,206 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { workHref } from "@/lib/hrefs"; +import type { Cadence } from "@/lib/schedule-types"; +import CadenceFields from "./CadenceFields"; + +// --------------------------------------------------------------------------- +// A RECURRING REPORT'S CONTROLS (plans/umtool-redesign.md, R5): Pause/Resume, +// Tick now, Edit cadence, Delete -- each the editor's `report-schedule` action +// through POST /api/schedules (umtool never writes a schedule itself). The +// page re-reads after each. +// +// compact the piece head's (a living report's article): Pause/Resume and +// Tick now beside the chip; Edit cadence and Delete are in the ⋯ +// menu (`part`) +// +// Delete is plan-then-confirm (the DeletePlan pattern): the trigger asks the +// editor for the plan (what goes, what stays, what refuses), the plan takes +// the focus, and only "Confirm delete" acts; "Keep it" (or Escape) closes it. +// Labels are contracts (e2e/recurring.spec.ts): the buttons "Pause schedule", +// "Resume schedule", "Tick now", "Edit cadence", "Save cadence", "Delete +// schedule", the region "delete schedule <id>", "Confirm delete", "Keep it". +// --------------------------------------------------------------------------- + +type Sched = { id: string; shape: string; paused: boolean; cadence: Cadence; running: boolean }; + +async function ask(body: Record<string, unknown>): Promise<Record<string, unknown>> { + const r = await fetch("/api/schedules", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const b = (await r.json().catch(() => ({}))) as Record<string, unknown> & { error?: string }; + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + return b; +} + +export default function ScheduleControls({ schedule, part = "all" }: { schedule: Sched; part?: "head" | "menu" | "all" }) { + const router = useRouter(); + const hydrated = useHydrated(); + const [busy, setBusy] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const [said, setSaid] = useState<string | null>(null); + const [editing, setEditing] = useState(false); + const [cadence, setCadence] = useState<Cadence>(schedule.cadence); + const [plan, setPlan] = useState<{ removes: string; keeps: string[]; refused: string | null } | null>(null); + const deleteRef = useRef<HTMLButtonElement>(null); + const confirmRef = useRef<HTMLButtonElement>(null); + const opened = useRef(false); + useEffect(() => { + if (plan) { + opened.current = true; + confirmRef.current?.focus(); + } else if (opened.current) { + opened.current = false; + deleteRef.current?.focus(); + } + }, [plan]); + + const act = async (what: string, body: Record<string, unknown>, done?: (b: Record<string, unknown>) => void) => { + setBusy(what); + setError(null); + setSaid(null); + try { + const b = await ask({ id: schedule.id, ...body }); + done?.(b); + router.refresh(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + }; + + const head = part === "head" || part === "all"; + const menu = part === "menu" || part === "all"; + return ( + <span className="inline-flex flex-wrap items-center gap-2" data-schedule-controls={schedule.id}> + {head && ( + <> + <Button + size="sm" + variant="outline" + disabled={!hydrated || busy !== null} + data-schedule-pause={schedule.paused ? "resume" : "pause"} + onClick={() => void act(schedule.paused ? "resume" : "pause", { action: schedule.paused ? "resume" : "pause" })} + > + {schedule.paused ? "Resume schedule" : "Pause schedule"} + </Button> + <Button + size="sm" + variant="outline" + disabled={!hydrated || busy !== null || schedule.running} + title={schedule.running ? "A tick is queued or running" : "One tick now (not held by the lane's gate)"} + data-schedule-tick="" + onClick={() => void act("tick", { action: "tick-now" }, (b) => setSaid(`Tick queued — job ${String(b.jobId ?? "")}`))} + > + {busy === "tick" ? "Ticking…" : "Tick now"} + </Button> + </> + )} + {menu && ( + <> + {!editing ? ( + <Button size="sm" variant={part === "menu" ? "quiet" : "outline"} disabled={!hydrated || busy !== null} data-schedule-edit="" onClick={() => setEditing(true)}> + Edit cadence + </Button> + ) : ( + <form + aria-label="edit cadence" + className="flex basis-full flex-wrap items-end gap-2 rounded-[3px] border border-seam-2 bg-ink p-3" + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + setEditing(false); + } + }} + onSubmit={(e) => { + e.preventDefault(); + void act("cadence", { action: "update", cadence }, () => setEditing(false)); + }} + > + <CadenceFields value={cadence} onChange={setCadence} disabled={busy !== null} /> + <Button type="submit" size="sm" variant="go" disabled={busy !== null}> + Save cadence + </Button> + <Button type="button" size="sm" variant="quiet" onClick={() => setEditing(false)}> + Cancel + </Button> + </form> + )} + {!plan ? ( + <Button + ref={deleteRef} + size="sm" + variant={part === "menu" ? "quiet" : "destructive"} + disabled={!hydrated || busy !== null} + data-schedule-delete="" + onClick={() => + void act("plan", { action: "delete" }, (b) => setPlan((b.plan as { removes: string; keeps: string[]; refused: string | null }) ?? null)) + } + > + Delete schedule + </Button> + ) : ( + <section + role="region" + aria-label={`delete schedule ${schedule.id}`} + data-delete-blocked={plan.refused ? "yes" : "no"} + className="basis-full rounded-[3px] border border-reject-text bg-ink p-3 text-[12px]" + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + setPlan(null); + } + }} + > + <p className="m-0 font-medium">Delete {plan.removes}. There is no undo.</p> + {plan.keeps.length > 0 && ( + <ul aria-label="what is kept" className="mt-1 list-disc pl-5 text-text-2"> + {plan.keeps.map((k) => ( + <li key={k}>{k}</li> + ))} + </ul> + )} + {plan.refused && ( + <p role="alert" className="mt-1 text-reject-text"> + {plan.refused} + </p> + )} + <div className="mt-2 flex gap-2"> + <Button + ref={confirmRef} + size="sm" + variant="destructive" + disabled={!!plan.refused || busy !== null} + onClick={() => + void act("delete", { action: "delete", confirm: true }, () => { + setPlan(null); + if (schedule.shape !== "living") router.push(workHref({ recurring: "1" })); + }) + } + > + {busy === "delete" ? "Deleting…" : "Confirm delete"} + </Button> + <Button size="sm" variant="quiet" onClick={() => setPlan(null)}> + Keep it + </Button> + </div> + </section> + )} + </> + )} + {said && ( + <span role="status" className="text-[12px] text-text-2" data-schedule-said=""> + {said} + </span> + )} + {error && ( + <span role="alert" className="basis-full text-[12px] text-reject-text" data-schedule-error=""> + {error} + </span> + )} + </span> + ); +} diff --git a/umtool/components/series/TickProgress.tsx b/umtool/components/series/TickProgress.tsx @@ -0,0 +1,12 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { EditorJobProgress } from "@/components/ui/job-progress"; + +// A tick in flight (R5): the editor's `report-tick` job, through P4b's one +// JobProgress, its last log line the step it is on. The page re-reads when it +// ends, so the edition and the tick log show what it did. +export default function TickProgress({ jobId }: { jobId: string }) { + const router = useRouter(); + return <EditorJobProgress jobId={jobId} label="Tick" cancelName="tick" onEnd={() => router.refresh()} data-tick-progress={jobId} />; +} diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -59,6 +59,7 @@ const FIXED: Item[] = [ { id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) }, { id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) }, { id: "new-article-board", section: "Create", label: "New article from a board", hint: "a seeded sweep, planned first", href: createHref({ make: "article-board" }) }, + { id: "new-recurring", section: "Create", label: "New recurring report", hint: "a living report or a dated series", href: createHref({ make: "recurring" }) }, { id: "new-video-article", section: "Create", label: "New video from an article", hint: "the chain over an iteration", href: createHref({ make: "video-article" }) }, { id: "new-video-board", section: "Create", label: "New video from a board", hint: "a timeline from the pinned cites", href: createHref({ make: "video-board" }) }, { id: "new-video-recording", section: "Create", label: "New video from a recording", hint: "a URL or channel/id", href: createHref({ make: "video-recording" }) }, diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts @@ -62,7 +62,8 @@ test("the lines, grouped Research · Article · Video · Song; the policy chip l await page.goto(urls.createHref()); await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("What are you making?"); await expect(page.locator("[data-make-group]")).toHaveText([/^Research/, /^Article/, /^Video/, /^Song/]); - await expect(page.locator("[data-make-line]")).toHaveCount(8); + // Nine: R5 added "A recurring report" under Article. + await expect(page.locator("[data-make-line]")).toHaveCount(9); // The boards and the reports on disk are counted on their lines. await expect(line(page, "article-board")).toContainText(/ · \d+ quotes?/); await expect(line(page, "video-report")).toContainText(/ · \d+ found/); @@ -97,7 +98,7 @@ test("keys: j/k light the lines, Enter opens the form on its first field, Escape await expect(page.locator('[data-make="article"]')).toBeFocused(); await expect(page).toHaveURL(/\/create$/); // Down the left column and into the right: the head follows the column. - for (let i = 0; i < 2; i++) await page.keyboard.press("j"); + for (let i = 0; i < 3; i++) await page.keyboard.press("j"); await expect(line(page, "video-article")).toHaveAttribute("data-lit", ""); const head = await page.locator(".lit-head").boundingBox(); const lit = await line(page, "video-article").boundingBox(); diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -720,6 +720,42 @@ function generationRoute(req, res, url, auth) { } }); } + // RECURRING REPORTS (R5): the REAL report-schedule action and store over + // the fixture's article store, a tick's steps stubbed + // (common/testing/schedule/opsStub.ts, under tsx). A tick-now runs to its + // end in that child; its job is answered here as done, with its log. + if (req.method === "POST" && url.pathname === "/api/ops/report-schedule") { + return readBody(req, (body) => { + requests.push({ route: "report-schedule", ...(body ?? {}), authorization: auth }); + record(); + const id = `stub-tick-${nextJob++}`; + const r = spawnSync( + path.join(REPO, "node_modules/.bin/tsx"), + [ + path.join(REPO, "common/testing/schedule/opsStub.ts"), + "--articles", ARTICLES, + "--channels", "sitechan,otherchan", + "--generation", JSON.stringify(generation), + "--job", id, + ], + { cwd: REPO, input: JSON.stringify(body ?? {}), encoding: "utf8", timeout: 60_000 }, + ); + const last = String(r.stdout ?? "").trim().split("\n").filter(Boolean).at(-1); + let out; + try { + out = JSON.parse(last ?? ""); + } catch { + return json(res, 500, { ok: false, error: `the schedule stub failed: ${String(r.stderr ?? "").slice(-400)}` }); + } + if (!out.ok) return json(res, out.status ?? 400, { ok: false, error: out.error }); + if (body?.action === "tick-now") { + const failed = out.tick?.status === "failed" || out.tick?.status === "interrupted"; + draftJobs.set(id, { id, kind: "report-tick", article: null, n: null, task: "tick", status: failed ? "failed" : "done", at: Date.now(), log: out.log ?? [], timers: [] }); + return json(res, 202, { ok: true, jobId: id }); + } + return json(res, 200, out); + }); + } if (req.method === "POST" && url.pathname === "/api/ops/research-approve") { return readBody(req, (body) => { requests.push({ route: "research-approve", ...(body ?? {}), authorization: auth }); diff --git a/umtool/e2e/recurring.spec.ts b/umtool/e2e/recurring.spec.ts @@ -0,0 +1,249 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// RECURRING REPORTS (plans/umtool-redesign.md, R5) over the editor stub, which +// runs the REAL report-schedule action and store over the fixture's article +// store with a tick's steps stubbed (common/testing/schedule/opsStub.ts): a +// tick makes a done edition, a second tick the same day is quiet, "held" in +// the terms is a daily-cap refusal, "fail" a failure. +// +// Create → "A recurring report": planned, then started (a series; a living +// report) · the series page: Tick now, a real and a quiet edition, the tick +// log, pause/resume, edit cadence, delete (plan, then confirm) · Work: one +// row per series, the recurring facet · the Inbox: a finished edition is +// Review, a held or failed tick is Your call · a living report's article: +// the cadence chip in its head. +// +// WRITES articles/.series/r5-*, articles/r5-* (through the stub; removed after) +// +// R5_SHOTS=<dir> also saves the screenshots (1366×768 and 1440×900, both themes). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ARTICLES = path.join(FIXTURE, "articles"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const SHOTS = process.env.R5_SHOTS ?? ""; +const stubAsked = (route: string) => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route); +const series = (id: string) => JSON.parse(readFileSync(path.join(ARTICLES, ".series", id, "series.json"), "utf8")); + +function clean() { + rmSync(path.join(ARTICLES, ".series"), { recursive: true, force: true }); + for (const a of readdirSync(ARTICLES).filter((n) => n.startsWith("r5-"))) rmSync(path.join(ARTICLES, a), { recursive: true, force: true }); +} + +async function shoot(page: Page, name: string) { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + const url = page.url(); + for (const theme of ["dark", "light"] as const) { + await page.context().addCookies([{ name: "umtool-theme", value: theme, url }]); + for (const [w, h] of [ + [1366, 768], + [1440, 900], + ] as const) { + await page.setViewportSize({ width: w, height: h }); + await page.goto(url); + await page.waitForLoadState("networkidle").catch(() => {}); + await page.screenshot({ path: path.join(SHOTS, `${name}-${w}x${h}-${theme}.png`) }); + } + } + await page.context().clearCookies({ name: "umtool-theme" }); + await page.setViewportSize({ width: 1280, height: 720 }); + await page.goto(url); +} + +async function api(page: Page, body: Record<string, unknown>) { + const r = await page.request.post("/api/schedules", { data: body }); + const b = (await r.json()) as Record<string, unknown>; + expect(r.ok(), JSON.stringify(b)).toBe(true); + return b; +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + clean(); + await warm(playwright, [urls.createHref({ make: "recurring" }), "/api/articles/channels", "/api/schedules", urls.seriesHref("r5-none"), urls.workHref({ recurring: "1" })]); +}); +test.afterAll(clean); + +test("Create → A recurring report: a series, planned (first tick, model, cap), then started; its page opens", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.createHref({ make: "recurring" })); + const form = page.getByRole("form", { name: "a recurring report" }); + await expect(form.getByRole("textbox", { name: "topic" })).toBeFocused(); + await expect(form.getByRole("radio", { name: "Series" })).toBeChecked(); + await form.getByRole("textbox", { name: "topic" }).fill("R5 cohost"); + await form.getByRole("textbox", { name: "question" }).fill("What did the co-hosts say this week?"); + await form.getByRole("textbox", { name: "find a channel" }).fill("site"); + await form.getByRole("button", { name: /Site Channel/ }).click(); + await expect(form.getByRole("combobox", { name: "cadence" })).toHaveValue("weekly"); + await expect(form.getByRole("combobox", { name: "day of the week" })).toHaveValue("1"); + await shoot(page, "create-recurring"); + await form.getByRole("button", { name: "Plan the schedule" }).click(); + const plan = form.getByRole("region", { name: "plan recurring report" }); + await expect(plan).toContainText("Series r5-cohost · weekly · Mon 06:00 · first tick Mon 06:00"); + await expect(plan.locator("[data-plan-first-tick]")).toHaveAttribute("data-plan-first-tick", /T\d\d:00:00\.000Z$/); + await expect(plan).toContainText(/up to \$\d+\.\d\d a tick · daily cap \$\d+\.\d\d/); + await expect(plan).toContainText("first edition: R5 cohost · week of"); + // Nothing written by the plan. + expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost"))).toBe(false); + expect(stubAsked("report-schedule").at(-1)).toMatchObject({ action: "create", dryRun: true, shape: "series", topic: "R5 cohost", channels: ["sitechan"], cadence: { kind: "weekly", dow: 1, at: "06:00" } }); + await shoot(page, "create-recurring-plan"); + // The confirm has the focus: Enter starts it. + await expect(form.getByRole("button", { name: "Start the schedule" })).toBeFocused(); + await page.keyboard.press("Enter"); + await page.waitForURL(/\/series\/r5-cohost$/, { timeout: 20_000 }); + await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/); + await expect(page.locator("[data-series-empty]")).toContainText("No edition yet"); + expect(series("r5-cohost")).toMatchObject({ shape: "series", topic: "R5 cohost", scope: { channels: ["sitechan"] }, paused: false, editions: [] }); +}); + +test("the series page: Tick now makes an edition, a second the same day is quiet; the tick log; pause, resume, edit cadence", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.seriesHref("r5-cohost")); + await page.getByRole("button", { name: "Tick now" }).click(); + await expect(page.locator("[data-schedule-said]")).toContainText(/Tick queued — job stub-tick-\d+/); + const done = page.locator("[data-edition='1']"); + await expect(done).toHaveAttribute("data-edition-status", "done"); + const article = series("r5-cohost").editions[0].article as string; + expect(article).toMatch(/^r5-cohost-\d{4}-\d{2}-\d{2}$/); + await expect(done.locator(`[data-edition-link='${article}']`)).toHaveText(/^R5 cohost · week of \d{4}-\d{2}-\d{2}$/); + await page.getByRole("button", { name: "Tick now" }).click(); + const quiet = page.locator("[data-edition='2']"); + await expect(quiet).toHaveAttribute("data-edition-status", "quiet"); + await expect(quiet).toHaveClass(/opacity-55/); + await expect(quiet.locator("[data-edition-link]")).toHaveCount(0); + // Newest first, each with its window; the quiet one's starts where the first ended. + await expect(page.locator("[data-edition]")).toHaveCount(2); + await expect(page.locator("[data-edition]").first()).toHaveAttribute("data-edition", "2"); + const w1 = (await done.getAttribute("data-edition-window"))!.split("/"); + await expect(quiet).toHaveAttribute("data-edition-window", `${w1[1]}/${w1[1]}`); + const ticks = page.getByRole("table", { name: "ticks" }); + await expect(ticks.locator("tbody tr")).toHaveCount(2); + await expect(ticks.locator("tbody tr").first()).toHaveAttribute("data-tick-status", "quiet"); + await expect(ticks.locator("tbody tr").nth(1)).toContainText("$0.37"); + await expect(page.locator("[data-series-spent]")).toHaveAttribute("data-series-spent", "0.37"); + await shoot(page, "series-page"); + + await page.getByRole("button", { name: "Pause schedule" }).click(); + await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · paused/); + await page.getByRole("button", { name: "Resume schedule" }).click(); + await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/); + await page.getByRole("button", { name: "Edit cadence" }).click(); + const edit = page.getByRole("form", { name: "edit cadence" }); + await edit.getByRole("combobox", { name: "cadence" }).selectOption("daily"); + await edit.locator('input[aria-label="at"]').fill("07:30"); + await edit.getByRole("button", { name: "Save cadence" }).click(); + await expect(page.locator("[data-schedule-chip]")).toHaveText(/daily · next \w{3} 07:30/); + expect(series("r5-cohost").cadence).toEqual({ kind: "daily", at: "07:30" }); + expect(stubAsked("report-schedule").map((r) => r.action)).toEqual(expect.arrayContaining(["tick-now", "pause", "resume", "update"])); +}); + +test("Work: one row per series, with its chip, under the recurring facet; its editions are not rows", async ({ page }) => { + await page.goto(urls.workHref({ recurring: "1" })); + const row = page.locator("[data-lit-line][data-piece='s:r5-cohost']"); + await expect(row).toBeVisible(); + await expect(row).toHaveAttribute("data-recurring", ""); + await expect(row.locator("[data-work-chip]")).toHaveText(/daily · next/); + await expect(page.locator("[data-lit-line][data-piece^='a:articles/r5-cohost-']")).toHaveCount(0); + // Every row the facet keeps is recurring. + const rows = page.locator("[data-lit-line][data-piece]"); + expect(await rows.count()).toBe(await page.locator("[data-lit-line][data-recurring]").count()); + await page.goto(urls.workHref({ kind: "series" })); + await expect(page.locator("[data-lit-line][data-piece='s:r5-cohost']")).toBeVisible(); + await page.goto(urls.workHref()); + await expect(page.locator("[data-lit-line][data-piece^='a:articles/r5-cohost-']")).toHaveCount(0); +}); + +test("the Inbox: a finished edition is Review on its series; a held tick (Raise cap) and a failed one (Tick now) are Your call", async ({ page }) => { + test.setTimeout(90_000); + await page.goto("/"); + for (const [topic, terms] of [ + ["R5 held", "held"], + ["R5 fail", "fail"], + ]) { + const made = (await api(page, { action: "create", shape: "series", topic, channels: ["sitechan"], cadence: "weekly mon 06:00", terms })) as { schedule: { id: string } }; + await api(page, { action: "tick-now", id: made.schedule.id }); + } + await page.goto("/"); + const review = page.locator("[data-group=review] [data-lit-line][data-piece='s:r5-cohost'][data-card='edition-ready']"); + await expect(review).toBeVisible(); + await expect(review.locator("[data-action-link]")).toHaveText("Review edition"); + const held = page.locator("[data-group=your-call] [data-lit-line][data-piece='s:r5-held'][data-card='tick-held']"); + await expect(held).toBeVisible(); + await expect(held).toContainText(/held by a cap: .*daily cap/); + await expect(held.locator("[data-action-link]")).toHaveText("Raise cap"); + await expect(held.locator("[data-action-link]")).toHaveAttribute("href", urls.generationPolicyHref()); + const failed = page.locator("[data-group=your-call] [data-lit-line][data-piece='s:r5-fail'][data-card='tick-failed']"); + await expect(failed).toBeVisible(); + await expect(failed.locator("[data-action-link]")).toHaveText("Tick now"); + await expect(failed.locator("[data-action-link]")).toHaveAttribute("href", urls.seriesHref("r5-fail")); + // The edition's article raises no iteration card of its own. + await expect(page.locator("[data-lit-line][data-piece^='a:articles/r5-cohost-']")).toHaveCount(0); + await shoot(page, "inbox-recurring"); + // A held series has no edition: the next tick covers its window. + expect(series("r5-held").editions).toEqual([]); +}); + +test("a living report: Create makes it; its article carries the cadence chip with Pause and Tick now; delete is plan, then confirm", async ({ page }) => { + test.setTimeout(120_000); + await page.goto(urls.createHref({ make: "recurring" })); + const form = page.getByRole("form", { name: "a recurring report" }); + await form.getByRole("radio", { name: "Living report" }).check(); + await form.getByRole("textbox", { name: "topic" }).fill("R5 living"); + await form.getByRole("textbox", { name: "find a channel" }).fill("site"); + await form.getByRole("button", { name: /Site Channel/ }).click(); + await form.getByRole("button", { name: "Plan the schedule" }).click(); + await expect(form.getByRole("region", { name: "plan recurring report" })).toContainText("a new article, r5-living: its first tick is its first sweep"); + await form.getByRole("button", { name: "Start the schedule" }).click(); + await page.waitForURL(/\/articles\/r5-living$/, { timeout: 20_000 }); + const head = page.locator("[data-piece-schedule='r5-living']"); + await expect(head.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/); + await head.getByRole("button", { name: "Tick now" }).click(); + await expect(head.locator("[data-schedule-said]")).toContainText(/Tick queued/); + // The first tick is the article's first sweep: an iteration, ready for review. + await expect(page.locator("[data-testid='piece-tab-iterations']")).toContainText("1"); + await shoot(page, "living-chip"); + await page.goto(urls.workHref({ recurring: "1" })); + await expect(page.locator("[data-lit-line][data-piece='a:articles/r5-living'] [data-work-chip]")).toHaveText(/weekly · next/); + + await page.goto("/articles/r5-living"); + await page.getByRole("button", { name: "More" }).click(); + await page.getByRole("button", { name: "Delete schedule" }).click(); + const plan = page.getByRole("region", { name: "delete schedule r5-living" }); + await expect(plan).toContainText("the schedule of r5-living"); + await expect(plan.getByRole("list", { name: "what is kept" })).toContainText("the article r5-living and its iterations"); + await expect(plan.getByRole("button", { name: "Confirm delete" })).toBeFocused(); + await plan.getByRole("button", { name: "Confirm delete" }).click(); + await expect(page.locator("[data-piece-schedule]")).toHaveCount(0); + expect(existsSync(path.join(ARTICLES, "r5-living", "schedule.json"))).toBe(false); + expect(existsSync(path.join(ARTICLES, "r5-living", "iterations", "1", "iteration.json"))).toBe(true); +}); + +test("delete a series: the plan says the editions stay as articles; Keep it writes nothing; Confirm delete goes to the recurring list", async ({ page }) => { + await page.goto(urls.seriesHref("r5-cohost")); + await page.getByRole("button", { name: "Delete schedule" }).click(); + const plan = page.getByRole("region", { name: "delete schedule r5-cohost" }); + await expect(plan).toContainText("the series r5-cohost"); + await expect(plan.getByRole("list", { name: "what is kept" })).toContainText("1 edition article, as articles: r5-cohost-"); + await page.keyboard.press("Escape"); + await expect(plan).toHaveCount(0); + await expect(page.getByRole("button", { name: "Delete schedule" })).toBeFocused(); + expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost", "series.json"))).toBe(true); + await page.getByRole("button", { name: "Delete schedule" }).click(); + await page.getByRole("region", { name: "delete schedule r5-cohost" }).getByRole("button", { name: "Confirm delete" }).click(); + await page.waitForURL(/\/work\?recurring=1$/, { timeout: 20_000 }); + expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost"))).toBe(false); + // The edition is an article in its own right now. + const edition = readdirSync(ARTICLES).find((n) => n.startsWith("r5-cohost-")); + expect(edition).toBeTruthy(); +}); diff --git a/umtool/lib/activity.ts b/umtool/lib/activity.ts @@ -8,7 +8,7 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { askEditor, EditorError, editorUrl, type EditorErrorReason } from "./articles/generation"; import { ARTICLES_KEY } from "./articles/key.mjs"; import { sitesPaths } from "./articles/sites"; -import { articleHref, mixHref, projectHref } from "./hrefs"; +import { articleHref, mixHref, projectHref, seriesHref } from "./hrefs"; import { hasRunPage, runHref } from "./research/runs-hrefs"; import { recentJobs as recentChainJobs, runningJob, type Job } from "./jobs"; import { recentJobs as recentRenders, type RenderJob } from "./mix"; @@ -24,6 +24,7 @@ import { queueText, rankOf, spendFromLog, + tickTargetFromLog, } from "./running.mjs"; // --------------------------------------------------------------------------- @@ -378,6 +379,18 @@ export async function readRunning({ fresh = false }: { fresh?: boolean } = {}): if (t) place = { article: t.article, n: t.n, task: t.task }; } } + // A recurring report's tick (R5): its spend so far (the log's `~$x`, the + // sweep it waits on) and the schedule it ticks. + if (j.kind === "report-tick" && j.status === "running") { + const tail = await askEditor<{ tail?: string[] }>(`/api/ops/job/${encodeURIComponent(j.id)}?tail=200`, { fresh }).catch(() => null); + const lines = Array.isArray(tail?.tail) ? tail.tail.map(String) : []; + spend = spendFromLog(lines) ?? spend; + const t = tickTargetFromLog(lines); + if (t) { + const { external: _x, ...item } = editorItem({ ...j, detail: `${t.shape} ${t.id}` }, null, rank, spend, jobsHref); + return { ...item, href: t.shape === "living" ? articleHref({ site: ARTICLES_KEY, id: t.id }) : seriesHref(t.id) }; + } + } return editorItem(j, place, rank, spend, jobsHref); }), ); diff --git a/umtool/lib/create.ts b/umtool/lib/create.ts @@ -6,6 +6,7 @@ import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { sitesPaths } from "@/lib/articles/sites"; import { spendHistory } from "@/lib/create/estimate.mjs"; import { readPieceGraph } from "@/lib/pieces"; +import { readSchedules } from "@/lib/schedules"; import { projectRefs } from "@/lib/projects"; import { makeKinds, sweepReports } from "@/lib/projects/create.mjs"; import { listCases } from "@/lib/research/boards"; @@ -42,6 +43,8 @@ export type CreateData = { reports: SweepReport[]; sources: SourceOption[]; kinds: { recording: ScaffoldKind | null; report: ScaffoldKind | null; song: ScaffoldKind | null }; + /** How many recurring reports are scheduled (R5), for the line's words. */ + schedules: number; }; const msg = (e: unknown) => (e instanceof Error ? e.message : String(e)); @@ -83,5 +86,6 @@ export async function readCreate(): Promise<CreateData> { reports: await sweepReports(refs).catch(() => []), sources, kinds: makeKinds() as CreateData["kinds"], + schedules: (await readSchedules().catch(() => ({ schedules: [] }))).schedules.length, }; } diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -107,6 +107,8 @@ export type WorkQuery = { notes?: string; audience?: string; sort?: string; + /** `1`: the recurring reports only -- the series and the living reports (R5). */ + recurring?: string; deleted?: string; freed?: string; }; @@ -156,7 +158,7 @@ export function articlesHref(q: ArticlesQuery = {}): string { * video-report a video from a sweep report on disk * song a song */ -export const MAKES = ["research", "article", "article-board", "video-article", "video-board", "video-recording", "video-report", "song"] as const; +export const MAKES = ["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-report", "song"] as const; export type Make = (typeof MAKES)[number]; export const isMake = (v: unknown): v is Make => typeof v === "string" && (MAKES as readonly string[]).includes(v); @@ -224,6 +226,11 @@ export function articleHref(a: ArticleRef, q: ArticleQuery = {}): string { return withQuery(articleBase(a), { ...(tab && tab !== "overview" ? { tab } : {}), ...rest }, note); } +/** A recurring report's series (R5): its editions, ticks and schedule. A static segment. */ +export function seriesHref(id: string): string { + return `/series/${encodeURIComponent(id)}`; +} + /** The evidence walk of one article. */ export function articleEvidenceHref(a: ArticleRef, q: { c?: string } = {}): string { return withQuery(`${articleBase(a)}/evidence`, q); diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -8,13 +8,17 @@ import { decisionsForSong, type Decision } from "./decisions"; import { openDecisions, projectRefs, summariseProject, type ProjectRef } from "./projects"; import { readManifest, reportSignature } from "./projects/report.mjs"; import { draftsView } from "./report/drafts.mjs"; -import { reviewHref } from "./hrefs"; +import { articleHref, generationPolicyHref, reviewHref } from "./hrefs"; import { awaitingReview, draftsDecisions } from "./inbox/drafts.mjs"; import { readFieldProvenance } from "./report/draft-provenance.mjs"; import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces"; import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle"; import { isMuted, readMutes } from "./mutes"; import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs"; +import { currentIteration } from "yt-dlp-transcript-common/lib/report/iterations"; +import { scheduleDecisions } from "./inbox/schedules.mjs"; +import { readSchedules } from "./schedules"; +import type { ScheduleView } from "./schedule-types"; // --------------------------------------------------------------------------- // THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the @@ -31,6 +35,11 @@ import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups // link-ambiguous an article whose video only a slug suggests // looks-done a piece every signal says is finished (a suggestion: // it never sets the lifecycle) +// tick-failed, a recurring report's tick that failed or was held by a +// tick-held, cap (Your call), and a series' finished edition with +// edition-ready nothing current yet (Review) -- lib/inbox/schedules.mjs; +// an edition's article raises no iteration cards of its +// own (they are its series') // drafts-unreviewed a report cut's field a model drafted that nobody has // reviewed (r28's draftsView; lib/inbox/drafts.mjs), one // row per field, kept per project against @@ -269,11 +278,39 @@ export async function draftsDecisionsAll(): Promise<Decision[]> { return per.flat(); } -/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done, drafts. */ +/** The recurring reports' decisions (R5): failed and held ticks, finished editions not yet current. */ +async function recurringDecisions(views: ScheduleView[]): Promise<Decision[]> { + const editions = views.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.status === "done" && e.article ? [e.article] : []))); + const current = new Map<string, number | null>(); + await Promise.all( + editions.map(async (a) => { + const cur = await currentIteration(a, sitesPaths()).catch(() => null); + current.set(a, cur?.report ?? null); + }), + ); + return scheduleDecisions(views, { + current: (a: string) => current.get(a) ?? null, + articleHref: (a: string) => articleHref({ site: ARTICLES_KEY, id: a }, { tab: "iterations" }), + settingsHref: generationPolicyHref(), + }) as Decision[]; +} + +/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done, drafts, recurring reports. */ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> { - const [spend, drafts] = await Promise.all([spendByJob(), draftsDecisionsAll().catch(() => [] as Decision[])]); - const perArticle = await Promise.all(storeArticles(graph).map((p) => iterationDecisions(p, spend))); - return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts]; + const [spend, drafts, schedules] = await Promise.all([ + spendByJob(), + draftsDecisionsAll().catch(() => [] as Decision[]), + readSchedules().catch(() => ({ schedules: [] as ScheduleView[] })), + ]); + // An edition's article is its series' piece's business (one Review card there). + const editionArticles = new Set(schedules.schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [e.article] : [])))); + const perArticle = await Promise.all( + storeArticles(graph) + .filter((p) => !editionArticles.has(p.report as string)) + .map((p) => iterationDecisions(p, spend)), + ); + const recurring = await recurringDecisions(schedules.schedules).catch(() => [] as Decision[]); + return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...recurring]; } /** diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -48,6 +48,12 @@ const KIND_CATEGORY = { "unreadable-notes": "fix", "link-ambiguous": "choose", "looks-done": "finish", + // Recurring reports (R5, lib/inbox/schedules.mjs): a tick that failed or was + // held by a cap is money or work waiting on a yes; a finished edition is a + // review gate, like a finished iteration. + "tick-failed": "spend", + "tick-held": "spend", + "edition-ready": "review", }; const CATEGORY_GROUP = { @@ -76,7 +82,7 @@ export function groupOf(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, "drafts-unreviewed": 1, "unreadable-notes": 0 }; +const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0 }; const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; // ONE primary action per decision, its button copy naming the result. @@ -89,6 +95,9 @@ const ACTION_LABEL = { "unreadable-notes": "Repair notes.json", "link-ambiguous": "Link the video", "looks-done": "Mark done", + "tick-failed": "Tick now", + "tick-held": "Raise cap", + "edition-ready": "Review edition", "claim-unadjudicated": "Adjudicate claim", "claim-incoherent": "Rule on the flag", "clip-no-cues": "Fix the cue source", diff --git a/umtool/lib/inbox/schedules.mjs b/umtool/lib/inbox/schedules.mjs @@ -0,0 +1,67 @@ +// THE INBOX'S RECURRING-REPORT DECISIONS (plans/umtool-redesign.md, R5). Pure, +// over schedule views (lib/schedules.ts) and what the article store says is +// current, so the rule is unit-tested and lib/inbox.ts only reads the disk. +// +// tick-failed the newest tick failed, or the editor stopped during it, +// and nothing has ticked since -- Your call: Tick now +// tick-held the newest tick was held by a cap (the day's, or the +// job's over the policy's max) -- Your call: Raise cap +// edition-ready a series' edition is done and its article has nothing +// current yet -- Review: read it, make it current +// +// A living report's refresh lands an `iteration-ready` card of its own (the +// article's iterations, lib/inbox.ts); only its failed or held ticks are here. +// An edition's article is the SERIES' piece's business: lib/inbox.ts does not +// raise iteration cards for it, so a finished edition is one Review card on +// the series, not two. + +const usd = (n) => `$${n.toFixed(2)}`; +const timeOf = (iso) => { + const t = iso ? Date.parse(iso) : NaN; + return Number.isFinite(t) ? t : 0; +}; + +/** + * @param {Array<{ id: string, shape: string, topic: string, article?: string, href: string, piece: string, call: null | { at: string, status: string, reason?: string, estimateUsd?: number, usd: number }, editions?: Array<{ n: number, title: string, status: string, article?: string, usd: number, at: string, window: { from: string, to: string } }> }>} views + * @param {{ current: (article: string) => number | null, articleHref: (article: string) => string, settingsHref: string }} how + */ +export function scheduleDecisions(views, how) { + const out = []; + for (const v of views) { + const living = v.shape === "living"; + const article = living ? (v.article ?? v.id) : null; + const base = living + ? { project: `sites/articles/${article}`, projectKind: "article", projectTitle: v.topic, piece: v.piece } + : { project: `series/${v.id}`, projectKind: "series", projectTitle: v.topic, piece: v.piece }; + const call = v.call; + if (call) { + const held = call.status === "held-by-cap"; + const est = call.estimateUsd !== undefined ? ` · up to ${usd(call.estimateUsd)} a tick` : ""; + out.push({ + ...base, + kind: held ? "tick-held" : "tick-failed", + target: call.at, + why: `${held ? "held by a cap" : call.status === "interrupted" ? "interrupted" : "failed"}${call.reason ? `: ${call.reason}` : ""}${held ? est : call.usd ? ` · ${usd(call.usd)} spent` : ""}`, + href: held ? how.settingsHref : v.href, + severity: "open", + at: timeOf(call.at), + }); + } + if (!living) { + for (const e of v.editions ?? []) { + if (e.status !== "done" || !e.article) continue; + if (how.current(e.article) !== null) continue; + out.push({ + ...base, + kind: "edition-ready", + target: e.title, + why: `${e.title} (${e.window.from} … ${e.window.to}) is done${e.usd ? ` · ${usd(e.usd)}` : ""}`, + href: how.articleHref(e.article), + severity: "open", + at: timeOf(e.at), + }); + } + } + } + return out; +} diff --git a/umtool/lib/inbox/schedules.test.mjs b/umtool/lib/inbox/schedules.test.mjs @@ -0,0 +1,59 @@ +// The recurring reports' Inbox decisions (R5): a failed or held tick is Your +// call, a finished edition is Review -- and each lands in its group. +import assert from "node:assert/strict"; +import test from "node:test"; +import { scheduleDecisions } from "./schedules.mjs"; +import { annotate, summarizeGroups } from "./groups.mjs"; +import { whatOf } from "./what.mjs"; + +const how = { current: (a) => (a === "cohost-2026-10-07" ? 1 : null), articleHref: (a) => `/articles/${a}?tab=iterations`, settingsHref: "/settings/generation" }; + +const series = (over = {}) => ({ + id: "cohost", + shape: "series", + topic: "Co-host updates", + href: "/series/cohost", + piece: "s:cohost", + call: null, + editions: [ + { n: 1, title: "Co-host updates · week of 2026-09-30", status: "done", article: "cohost-2026-10-07", usd: 1.2, at: "2026-10-07T10:00:00.000Z", window: { from: "2026-09-30", to: "2026-10-07" } }, + { n: 2, title: "Co-host updates · week of 2026-10-07", status: "quiet", usd: 0, at: "2026-10-14T10:00:00.000Z", window: { from: "2026-10-07", to: "2026-10-14" } }, + { n: 3, title: "Co-host updates · week of 2026-10-14", status: "done", article: "cohost-2026-10-21", usd: 2.5, at: "2026-10-21T10:00:00.000Z", window: { from: "2026-10-14", to: "2026-10-21" } }, + ], + ...over, +}); + +test("a finished edition nothing has made current is a Review card on the series; a quiet one and a current one are not", () => { + const d = scheduleDecisions([series()], how); + assert.equal(d.length, 1); + assert.deepEqual( + { kind: d[0].kind, piece: d[0].piece, target: d[0].target, href: d[0].href, project: d[0].project }, + { kind: "edition-ready", piece: "s:cohost", target: "Co-host updates · week of 2026-10-14", href: "/articles/cohost-2026-10-21?tab=iterations", project: "series/cohost" }, + ); + assert.match(d[0].why, /2026-10-14 … 2026-10-21\) is done · \$2\.50/); + const [row] = annotate(d, { pieceOf: () => null, lifecycleOf: () => "active" }); + assert.equal(row.group, "review"); + assert.equal(row.action.label, "Review edition"); + assert.equal(whatOf("edition-ready"), "edition ready"); +}); + +test("a failed tick is Your call (Tick now, on the schedule's page); a held one too (Raise cap, on the policy)", () => { + const failed = scheduleDecisions([series({ editions: [], call: { at: "2026-10-21T10:00:00.000Z", status: "failed", reason: "not wired: R4's stage 1", usd: 0 } })], how); + const held = scheduleDecisions( + [{ id: "shop", shape: "living", topic: "The shop", article: "shop", href: "/articles/shop", piece: "a:articles/shop", call: { at: "2026-10-21T10:00:00.000Z", status: "held-by-cap", reason: "the day's Claude API spend is $20.00", estimateUsd: 5, usd: 0 } }], + how, + ); + const rows = annotate([...failed, ...held], { pieceOf: () => null, lifecycleOf: () => "active" }); + assert.deepEqual( + rows.map((r) => [r.kind, r.group, r.action.label, r.action.href, r.project]), + [ + ["tick-failed", "your-call", "Tick now", "/series/cohost", "series/cohost"], + ["tick-held", "your-call", "Raise cap", "/settings/generation", "sites/articles/shop"], + ], + ); + assert.match(rows[1].why, /held by a cap: the day's Claude API spend is \$20\.00 · up to \$5\.00 a tick/); + const groups = summarizeGroups(rows); + assert.equal(groups.find((g) => g.id === "your-call").cards.length, 2); + assert.equal(whatOf("tick-failed"), "tick failed"); + assert.equal(whatOf("tick-held"), "tick held by a cap"); +}); diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -12,6 +12,9 @@ export const WHAT = { "unreadable-notes": "notes.json does not read", "link-ambiguous": "video not linked", "looks-done": "looks done", + "tick-failed": "tick failed", + "tick-held": "tick held by a cap", + "edition-ready": "edition ready", "claim-unadjudicated": "claims never ruled", "claim-incoherent": "claims that don't hold together", "clip-no-cues": "clips with no cues", diff --git a/umtool/lib/pieces.ts b/umtool/lib/pieces.ts @@ -15,8 +15,10 @@ import { readCases } from "./pieces/cases"; import { stageOfPiece } from "./pieces/tabs.mjs"; import { kindById } from "./projects/kinds.mjs"; import type { Decision } from "./decisions"; +import { chipOf, readSchedules } from "./schedules"; +import type { ScheduleChipData, ScheduleView } from "./schedule-types"; -export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId } from "./pieces/ids.mjs"; +export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId, seriesPieceId } from "./pieces/ids.mjs"; // --------------------------------------------------------------------------- // PIECES (plans/umtool-redesign.md): the unit the operator works on. @@ -28,6 +30,11 @@ export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, pr // manifest that names it, then a unique slug) // a PROJECT piece `p:<id>` -- a project under REPORTS_ROOT linked to no // article: a song, a hand-made report video, a sweep +// a SERIES piece `s:<id>` -- a recurring report's dated editions (R5, +// lib/schedules.ts); each edition is a store article that +// names its series (`series`), and Work lists the series, +// not its editions. A living report is its article's +// piece, with the schedule's chip (`schedule`). // // A project linked to two articles belongs to the first that claims it, by // strength (iteration, then manifest, then slug) and then in list order -- @@ -41,7 +48,7 @@ export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, pr // it is one small file, and a park has to show on the next read. // --------------------------------------------------------------------------- -export type PieceKind = "article" | "project"; +export type PieceKind = "article" | "project" | "series"; export type PieceProject = { id: string; @@ -91,6 +98,10 @@ export type Piece = { /** Why it looks done, when it does. A suggestion: it never sets the lifecycle. */ looksDone: string[]; newestMs: number; + /** A recurring report's schedule (R5): a series', or a living report's on its article; else null. */ + schedule: ScheduleChipData | null; + /** The series an edition's article belongs to (R5), else null. */ + series: string | null; }; /** The one stage rule's facts: the four stages, and a song's own three (lib/pieces/song-tabs.mjs). */ @@ -209,7 +220,7 @@ function fromRow(a: ArticleRow): ArticleIn { }; } -async function pendingArticles(): Promise<ArticleIn[]> { +async function pendingArticles(topics: Map<string, string> = new Map()): Promise<ArticleIn[]> { const ids = await listPendingArticles(sitesPaths()).catch(() => [] as string[]); const projects = await videoProjects(REPORTS_ROOT); return Promise.all( @@ -218,7 +229,8 @@ async function pendingArticles(): Promise<ArticleIn[]> { return { site: ARTICLES_KEY, id, - title: id, + // A living report waiting for its first tick is named by its topic (R5). + title: topics.get(id) ?? id, status: "in the making" as const, audience: null, hasVideo: false, @@ -247,10 +259,15 @@ async function projectLooksDone(p: ProjectSummary): Promise<string | null> { async function buildGraph(): Promise<PieceGraph> { // The article side must never take the decisions down with it: a site whose // site.json does not read is an article list without that site, not a 500. + // The recurring reports (R5) first: a living report's topic names its + // article while it is in the making. + const schedules = (await readSchedules().catch(() => ({ schedules: [] as ScheduleView[] }))).schedules; + const living = new Map(schedules.filter((v) => v.shape === "living").map((v) => [v.article ?? v.id, v])); + const editionOf = new Map(schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [[e.article, v.id] as const] : [])))); const [sites, store, pending, summaries, its, cases] = await Promise.all([ listSiteRows().catch(() => []), readStoreRow().catch(() => ({ articles: [] as ArticleRow[] })), - pendingArticles().catch(() => [] as ArticleIn[]), + pendingArticles(new Map([...living].map(([a, v]) => [a, v.topic]))).catch(() => [] as ArticleIn[]), listProjects(), iterationProjects().catch(() => new Map<string, { current: boolean }[]>()), readCases().catch(() => []), @@ -325,6 +342,37 @@ async function buildGraph(): Promise<PieceGraph> { unreachable: a.unreachable, looksDone, newestMs, + schedule: a.site === ARTICLES_KEY && living.has(a.id) ? chipOf(living.get(a.id)!) : null, + series: a.site === ARTICLES_KEY ? (editionOf.get(a.id) ?? null) : null, + }); + } + + // A series (R5): its editions are store articles; the series is the piece + // Work lists and the Inbox's edition and tick cards are on. + for (const v of schedules) { + if (v.shape === "living") continue; + const done = (v.editions ?? []).some((e) => e.status === "done"); + const reached = { research: (v.editions ?? []).length > 0 || v.ticks.length > 0, article: done, video: false, deliver: false }; + pieces.push({ + id: v.piece, + kind: "series", + flow: "article", + title: v.topic, + site: null, + report: null, + project: null, + href: v.href, + status: null, + audience: null, + stage: stageOfPiece({ kind: "article", reached }), + reached, + projects: [], + possible: [], + unreachable: [], + looksDone: [], + newestMs: Math.max(Date.parse(v.updatedAt) || 0, Date.parse(v.lastTick ?? "") || 0), + schedule: chipOf(v), + series: null, }); } @@ -353,6 +401,8 @@ async function buildGraph(): Promise<PieceGraph> { unreachable: [], looksDone: why ? [why] : [], newestMs: p.newestMtimeMs, + schedule: null, + series: null, }); pieceOfProject.set(p.id, projectPieceId(p.id)); } diff --git a/umtool/lib/pieces/ids.mjs b/umtool/lib/pieces/ids.mjs @@ -10,6 +10,8 @@ // 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) +// s:<series> a recurring report's series (R5): its editions are +// articles of the store, the series is their piece // // Pure, no imports with side effects: a client component may parse an id. @@ -20,19 +22,19 @@ export const PIECE_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; 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" }; +export const PIECE_KINDS = ["article", "project", "case", "series"]; +const PREFIX = { article: "a", project: "p", case: "c", series: "s" }; /** * 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} + * @returns {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string } | { kind: "series", series: string } | null} */ export function parsePieceId(id) { if (typeof id !== "string" || id.length > 512) return null; - const m = /^([apc]):(.+)$/.exec(id); + const m = /^([apcs]):(.+)$/.exec(id); if (!m) return null; const [, ns, rest] = m; if (ns === "a") { @@ -46,7 +48,7 @@ export function parsePieceId(id) { return { kind: "project", project: rest }; } if (!PIECE_SEGMENT_RE.test(rest)) return null; - return { kind: "case", case: rest }; + return ns === "s" ? { kind: "series", series: rest } : { kind: "case", case: rest }; } /** True when `id` is a piece id. */ @@ -56,7 +58,7 @@ 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 + * @param {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string } | { kind: "series", series: string }} p */ export function formatPieceId(p) { const id = @@ -66,7 +68,9 @@ export function formatPieceId(p) { ? `${PREFIX.project}:${p.project}` : p?.kind === "case" ? `${PREFIX.case}:${p.case}` - : null; + : p?.kind === "series" + ? `${PREFIX.series}:${p.series}` + : null; if (id === null || !isPieceId(id)) throw new Error(`not a piece: ${JSON.stringify(p)}`); return id; } @@ -80,6 +84,9 @@ export const projectPieceId = (project) => formatPieceId({ kind: "project", proj /** `c:<case>`. */ export const casePieceId = (slug) => formatPieceId({ kind: "case", case: slug }); +/** `s:<series>`. */ +export const seriesPieceId = (id) => formatPieceId({ kind: "series", series: id }); + /** * An article decision's `project` (`sites/<site>/<report>`, lib/decisions.ts * noteDecisions) back to its article, or null. Only meaningful for a row whose diff --git a/umtool/lib/pieces/ids.test.mjs b/umtool/lib/pieces/ids.test.mjs @@ -12,10 +12,11 @@ import { isPieceId, parsePieceId, projectPieceId, + seriesPieceId, } 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"]) { + 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", "s:co-host-updates"]) { const parsed = parsePieceId(id); assert.ok(parsed, id); assert.equal(formatPieceId(parsed), id); @@ -26,6 +27,8 @@ test("each namespace parses and formats back", () => { assert.equal(articlePieceId("articles", "zeta"), "a:articles/zeta"); assert.equal(projectPieceId("articles/zeta"), "p:articles/zeta"); assert.equal(casePieceId("vote"), "c:vote"); + assert.deepEqual(parsePieceId("s:co-host-updates"), { kind: "series", series: "co-host-updates" }); + assert.equal(seriesPieceId("co-host-updates"), "s:co-host-updates"); }); test("a two-segment id is never ambiguous: the namespace says which", () => { @@ -40,7 +43,7 @@ test("a two-segment id is never ambiguous: the namespace says which", () => { 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/../x", "p:../x", "p:a//b", "p:/abs", "p:.hidden", "p:a/..b", "p:a b", "c:Up", "c:a/b", "s:", "s:a/b", "s:Up", "a:articles/zeta\n", " p:x", null, undefined, 42, {}, `p:${"a/".repeat(300)}a`, ]) { assert.equal(parsePieceId(bad), null, JSON.stringify(bad)); diff --git a/umtool/lib/rail.ts b/umtool/lib/rail.ts @@ -28,7 +28,8 @@ export function railCounts(): Promise<RailCounts> { const [inbox, pieces, machine] = await Promise.all([readInbox(), listPieces(), machineCalls()]); return { inbox: inboxHeadline(inbox.groups).calls + machine.length, - work: pieces.filter((p) => p.lifecycle === "active").length, + // Work's rows: an edition's article is its series' row (R5). + work: pieces.filter((p) => p.lifecycle === "active" && !p.series).length, }; })(); const entry = { at: Date.now(), value }; diff --git a/umtool/lib/running.mjs b/umtool/lib/running.mjs @@ -23,8 +23,8 @@ /** The editor's lane runners: long-lived loops that enqueue the real work. */ export const LANE_KINDS = new Set(["auto-download", "auto-transcribe", "auto-digest", "auto-backfill", "auto-publish"]); -/** Generation: model calls, and the voices a narration is spoken with. */ -export const GENERATION_KINDS = new Set(["report-draft", "bench-verdicts", "tts-file"]); +/** Generation: model calls, the voices a narration is spoken with, and a recurring report's tick (R5). */ +export const GENERATION_KINDS = new Set(["report-draft", "bench-verdicts", "tts-file", "report-tick"]); /** Clip windows: umtool asks for them (`requestedBy: "umtool"`, the job's detail says so). */ const WINDOW_KINDS = new Set(["fetch-window", "fetch-windows"]); @@ -63,6 +63,20 @@ export function spendFromLog(lines) { } /** + * The schedule a report-tick job's FIRST log line names (`series <id>: …` or + * `living <id>: …`, controller/reportTick.ts), or null (R5). + * + * @param {string[]} lines + */ +export function tickTargetFromLog(lines) { + for (const line of lines ?? []) { + const m = /^(living|series) ([a-z0-9][a-z0-9-]*): /.exec(String(line)); + if (m) return { shape: m[1], id: m[2] }; + } + return null; +} + +/** * The article, iteration and task a report-draft job's FIRST log line names * (`sweep of <article> i3 on <model> (…)`), or null. The fallback when no * iteration on disk carries the job's id yet. diff --git a/umtool/lib/running.test.mjs b/umtool/lib/running.test.mjs @@ -89,3 +89,13 @@ test("the three ways the editor's jobs are missing are three sentences", () => { assert.equal(editorStateText("editor-token"), "Editor's WORKER_TOKEN not set"); assert.equal(editorStateText(null), null); }); + +test("a recurring report's tick (R5) is a generation row; its first log line names its schedule", async () => { + const { rankOf, tickTargetFromLog, spendFromLog } = await import("./running.mjs"); + assert.equal(rankOf({ id: "t1", kind: "report-tick" }), 0); + const log = ["series cohost: ticked now", "window 2026-10-07 … 2026-10-14: 3 recordings match", "sweep cohost-2026-10-14 i1: ~$0.42 so far"]; + assert.deepEqual(tickTargetFromLog(log), { shape: "series", id: "cohost" }); + assert.deepEqual(tickTargetFromLog(["living the-shop: the 2026-10-15T10:00:00.000Z window"]), { shape: "living", id: "the-shop" }); + assert.equal(tickTargetFromLog(["sweep of x i1 on m"]), null); + assert.equal(spendFromLog(log), 0.42); +}); diff --git a/umtool/lib/schedule-types.ts b/umtool/lib/schedule-types.ts @@ -0,0 +1,35 @@ +// A RECURRING REPORT, as umtool's pages read it (plans/umtool-redesign.md, +// R5): the schedule common stores (lib/report/schedule/types.ts) plus what a +// page shows of it -- the chip, the call, the spend, the addresses. Types +// only: safe for a client component. + +import type { Cadence } from "yt-dlp-transcript-common/lib/report/schedule/cadence"; +import type { Edition, Schedule, Tick } from "yt-dlp-transcript-common/lib/report/schedule/types"; + +export type { Cadence, Edition, Schedule, Tick }; + +export type ScheduleView = Schedule & { + /** "weekly · next Mon 06:00", "daily · paused". */ + chip: string; + /** "weekly · Mon 06:00". */ + cadenceWords: string; + /** The next tick's local day and time, or null (paused, none). */ + nextWords: string | null; + /** The newest tick when it is the operator's call (failed, held by a cap, interrupted). */ + call: Tick | null; + spentUsd: number; + /** The schedule's own page: a series' /series/<id>, a living report's article. */ + href: string; + /** The piece it is (`s:<id>`, or the living report's article's). */ + piece: string; +}; + +/** The chip's slice of a schedule (a piece head, a Work row). */ +export type ScheduleChipData = { + id: string; + shape: Schedule["shape"]; + chip: string; + paused: boolean; + href: string; + running: boolean; +}; diff --git a/umtool/lib/schedules.ts b/umtool/lib/schedules.ts @@ -0,0 +1,72 @@ +import { listScheduleReads, readLivingSchedule, readScheduleById } from "yt-dlp-transcript-common/lib/report/schedule/store"; +import { callOf, scheduleChip, spentOf, type Schedule } from "yt-dlp-transcript-common/lib/report/schedule/types"; +import { cadenceWords, tickWords } from "yt-dlp-transcript-common/lib/report/schedule/cadence"; +import { ARTICLES_KEY } from "./articles/key.mjs"; +import { sitesPaths } from "./articles/sites"; +import { askEditor } from "./articles/generation"; +import { articleHref, seriesHref } from "./hrefs"; +import { articlePieceId, seriesPieceId } from "./pieces/ids.mjs"; +import type { ScheduleChipData, ScheduleView } from "./schedule-types"; + +// --------------------------------------------------------------------------- +// RECURRING REPORTS, umtool's side (plans/umtool-redesign.md, R5). The editor +// keeps the schedules -- its report-schedule lane ticks them -- and they are +// stored in the article store (common lib/report/schedule/store.ts: a living +// report's beside its article, a series in reports/.series/<id>/). umtool +// READS them from disk (this file) and WRITES only through the editor's ops +// action, `report-schedule` (scheduleAsk): it never runs a timer itself. +// +// SERVER ONLY. +// --------------------------------------------------------------------------- + +export function viewOfSchedule(s: Schedule, now: number = Date.now()): ScheduleView { + const article = s.shape === "living" ? (s.article ?? s.id) : null; + const next = s.nextTick ? Date.parse(s.nextTick) : NaN; + return { + ...s, + chip: scheduleChip(s, now), + cadenceWords: cadenceWords(s.cadence), + nextWords: !s.paused && Number.isFinite(next) ? tickWords(next, s.tz, now) : null, + call: callOf(s), + spentUsd: spentOf(s), + href: article ? articleHref({ site: ARTICLES_KEY, id: article }) : seriesHref(s.id), + piece: article ? articlePieceId(ARTICLES_KEY, article) : seriesPieceId(s.id), + }; +} + +export const chipOf = (v: ScheduleView): ScheduleChipData => ({ + id: v.id, + shape: v.shape, + chip: v.chip, + paused: v.paused, + href: v.href, + running: !!v.running, +}); + +/** Every schedule that reads, and the files that do not. */ +export async function readSchedules(): Promise<{ schedules: ScheduleView[]; problems: { id: string; problem: string }[] }> { + const reads = await listScheduleReads(sitesPaths()); + const now = Date.now(); + return { + schedules: reads.flatMap((r) => (r.ok ? [viewOfSchedule(r.schedule, now)] : [])), + problems: reads.flatMap((r) => (r.ok ? [] : [{ id: r.id, problem: r.problem }])), + }; +} + +/** One schedule by id (a series', or a living report's article): the view, its problem, or null. */ +export async function readScheduleView(id: string): Promise<{ view: ScheduleView } | { problem: string } | null> { + const r = await readScheduleById(id, sitesPaths()); + if (!r) return null; + return r.ok ? { view: viewOfSchedule(r.schedule) } : { problem: r.problem }; +} + +/** A store article's living schedule, or null. */ +export async function livingScheduleOf(article: string): Promise<ScheduleView | null> { + const s = await readLivingSchedule(article, sitesPaths()).catch(() => null); + return s ? viewOfSchedule(s) : null; +} + +/** Ask the editor's `report-schedule` action (list, create, update, pause, resume, delete, tick-now). */ +export function scheduleAsk<T = Record<string, unknown>>(body: Record<string, unknown>): Promise<T> { + return askEditor<T>("/api/ops/report-schedule", { method: "POST", body }); +} diff --git a/umtool/lib/work.ts b/umtool/lib/work.ts @@ -45,6 +45,10 @@ export type WorkRow = PieceWithLifecycle & { projectState: string | null; haystack: string; counts: PieceCounts; + /** A recurring report (R5): a series, or a living report's article. */ + recurring: boolean; + /** Its cadence chip ("weekly · next Mon 06:00"), when recurring. */ + chip: string | null; }; const CALL_GROUPS = new Set(["your-call", "review", "blocking", "notes", "open"]); @@ -78,14 +82,17 @@ export async function readWork(): Promise<{ rows: WorkRow[]; lifecycleError?: st const byId = new Map(projects.map((p) => [p.id, p])); const label = new Map(KINDS.map((k) => [k.id, k.label])); - const rows = pieces.map((p): WorkRow => { + // One row per series: an edition's article is under its series (R5). + const rows = pieces.filter((p) => !p.series).map((p): WorkRow => { const own = p.project ? byId.get(p.project) : undefined; const linked = p.projects.map((x) => byId.get(x.id)).filter((x) => x !== undefined); const mine = own ? [own] : linked; const projectKinds = [...new Set(mine.map((x) => x.kind))]; - const kinds = p.kind === "article" ? ["article", ...projectKinds] : projectKinds; + const kinds = p.kind === "article" ? ["article", ...projectKinds] : p.kind === "series" ? ["series"] : projectKinds; const kindLabel = - p.kind === "article" + p.kind === "series" + ? "series" + : p.kind === "article" ? projectKinds.length ? `article + ${projectKinds.map((k) => label.get(k) ?? k).join(", ")}` : "article" @@ -107,6 +114,8 @@ export async function readWork(): Promise<{ rows: WorkRow[]; lifecycleError?: st projectState, haystack: [p.site, p.report, ...mine.map((x) => x.haystack)].filter(Boolean).join("\n"), counts: counts.get(p.id) ?? EMPTY, + recurring: !!p.schedule, + chip: p.schedule?.chip ?? null, }; }); return { rows, ...(life.error ? { lifecycleError: life.error } : {}) }; diff --git a/umtool/lib/work/facets.mjs b/umtool/lib/work/facets.mjs @@ -5,7 +5,8 @@ // Work reads its own keys AND the old lists' keys, so an old link lands on the // same set: // -// its own q, stage, kind, site, life, by, sort +// its own q, stage, kind, site, life, by, sort, recurring (R5: `1` keeps +// the series and the living reports) // /browse kind (a project kind id), template, state (a project state), // open (blocking | 1), q, sort (name), deleted // /articles kind=article (the redirect adds it), status, notes (open), @@ -80,6 +81,7 @@ export function lifeFilter(life) { * lifecycle: string, templates: string[], states: string[], status: string | null, * audience: string | null, haystack: string, * counts: { blocking: number, open: number, notes: number }, + * recurring?: boolean, * }} r * @param {Record<string, string | undefined>} q * @param {{ ignore?: string[] }} [opts] keys to leave out (a facet's own counts) @@ -97,6 +99,7 @@ export function keepRow(r, q, { ignore = [] } = {}) { if (on("state") && !r.states.includes(q.state)) return false; if (on("status") && r.status !== q.status) return false; if (on("audience") && r.audience !== q.audience) return false; + if (on("recurring") && q.recurring === "1" && !r.recurring) return false; if (on("notes") && q.notes === "open" && r.counts.notes <= 0) return false; if (on("open")) { if (q.open === "blocking" ? r.counts.blocking <= 0 : r.counts.blocking + r.counts.open <= 0) return false; diff --git a/umtool/lib/work/facets.test.mjs b/umtool/lib/work/facets.test.mjs @@ -74,3 +74,10 @@ test("sort: newest first, or by title", () => { assert.deepEqual(sortRows(rows, "name").map((r) => r.id), ["b", "a"]); assert.deepEqual(sortRows([row({ id: "x", title: "A" }), row({ id: "y", title: "B", newestMs: 9 })], "name").map((r) => r.id), ["x", "y"]); }); + +test("recurring (R5): `1` keeps the series and the living reports, nothing else", () => { + assert.equal(keepRow(row(), { recurring: "1" }), false); + assert.equal(keepRow(row({ recurring: true }), { recurring: "1" }), true); + assert.equal(keepRow(row({ id: "s:cohost", kinds: ["series"], recurring: true }), { recurring: "1", kind: "series" }), true); + assert.equal(keepRow(row(), {}), true); +});