Archilyzer · Source

archilyzer

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

commit 1a2097e4433f6c2cfcb412b18aff79285b7a032a
parent 590cf959073a64164f211475bbf624e9ae5759bd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 12:03:17 -0400

common, editor: recurring reports — the schedule store, its cadence, the tick and the report-schedule lane (umtool R5)

A schedule is a living report (one article kept current: each tick fetches
the scope and refreshes it) or a series (a dated edition each tick over the
window since the last; a window nothing matches is a quiet edition, $0).

- lib/report/schedule/: the cadence maths (daily, weekly on a day, every N
  days anchored to the first tick, on the schedule's local clock; DST-safe;
  a missed window is ONE catch-up tick), the schedule's schema and words,
  and the store's reads (living: <article>/schedule.json beside it, the new
  article in the making; series: reports/.series/<id>/series.json).
- controller/reportSchedule.ts: the one writer (create/plan, update,
  pause/resume, delete plan/confirm, the tick's claim and record), under
  the article store's lock.
- controller/reportTick.ts: one report-tick job per tick on its own queue,
  its steps through the TickSteps seam (fetchAndBuild, refresh,
  generateEdition, triage?). generateEdition is real (the window check,
  the daily cap, a report-draft sweep with from/to, the edition's title);
  R4's fetchAndBuild and refresh refuse "not wired" until R4 merges.
- controller/reportScheduleRunner.ts: the lane, armed by instrumentation
  below the idle gate, a scan every minute, held by its pause gate
  (settings.reportSchedule.held, lane report-schedule).
- pnpm ops report-schedule (list, create, update, pause, resume, delete,
  tick-now); the lane route takes report-schedule's held; COMMANDS.md and
  SETTINGS.md regenerated.

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

Diffstat:
MCOMMANDS.md | 3++-
MSETTINGS.md | 19+++++++++++++++++++
Acommon/controller/reportSchedule.test.ts | 375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/reportSchedule.ts | 605+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/reportScheduleOps.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/reportScheduleRunner.ts | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/reportTick.ts | 430+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 14++++++++++++++
Mcommon/lib/autoQueueTypes.ts | 2+-
Mcommon/lib/pauseGates.ts | 8++++++++
Mcommon/lib/queueKeys.ts | 7+++++++
Acommon/lib/report/schedule/cadence.test.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/schedule/cadence.ts | 301+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/schedule/store.ts | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/schedule/types.ts | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 20++++++++++++++++++++
Aeditor/app/api/ops/_reportSchedule.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/lane/route.ts | 12+++++++++---
Aeditor/app/api/ops/report-schedule/route.ts | 37+++++++++++++++++++++++++++++++++++++
Meditor/app/components/lanes/pauseControl.tsx | 14++++++++++++++
Meditor/app/operations/actions.ts | 11+++++++++--
Meditor/instrumentation.ts | 11+++++++++++
Mscripts/archilyzer-ops.mjs | 38+++++++++++++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.test.mjs | 10++++++++++
Msettings.json.example | 3+++
27 files changed, 2758 insertions(+), 9 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -124,7 +124,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `evict-clips` | evict-clips deletes cached clip windows (data/&lt;id&gt;/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. | | | `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "&lt;id&gt;"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` | | `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | -| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` | +| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` | | `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. | | @@ -148,6 +148,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | +| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'` | ### Usage, flags and environment diff --git a/SETTINGS.md b/SETTINGS.md @@ -48,6 +48,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`attribution`](#attribution) | object — see below | | [`archiveOrg`](#archiveorg) | object — see below | | [`publish`](#publish) | object — see below | +| [`reportSchedule`](#reportschedule) | object — see below | | [`seeder`](#seeder) | object — see below | | [`tts`](#tts) | object — see below | | [`generation`](#generation) | object — see below | @@ -860,6 +861,24 @@ Default: } ``` +## `reportSchedule` + +The recurring reports' lane (umtool R5): the editor ticks each schedule (`pnpm ops report-schedule`; a living report or a dated series, stored in the article store) when its cadence is due, one `report-tick` job at a time, never on an idle boot. Its one key is the lane's pause gate. See ReportScheduleSettings and common/controller/reportScheduleRunner.ts. + +#### `reportSchedule` + +| Key | Default | Description | +|---|---|---| +| `held` | `false` | The lane's pause gate (lib/pauseGates.ts, lane `report-schedule`; `pnpm ops lane {"lane":"report-schedule","held":true}`). A hold stops the runner STARTING ticks: a tick already queued or running finishes, a schedule's Tick now still runs, and the windows a hold spans are caught up by ONE tick per schedule when it lifts. Default false. | + +Default: + +```json +{ + "held": false +} +``` + ## `seeder` The home seeder of last resort (release 21): `archilyzer seed` seeds the sites' playable torrents (`archilyzer media playable`), each one only while no other seeder has it, and only behind a VPN (the docker profile `seeder`, docker-compose.seeder.yml). Not configured until `sites` names one. See SeederSettings and common/controller/seeder.ts. diff --git a/common/controller/reportSchedule.test.ts b/common/controller/reportSchedule.test.ts @@ -0,0 +1,375 @@ +// Recurring reports (umtool R5): the store and its one writer, the runner's +// due/lock logic, and the tick over stubbed steps. Temp stores only. +// +// Run with: node_modules/.bin/tsx --test controller/reportSchedule.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { sanitizeGeneration } from "../lib/generationSettings"; +import { listPendingArticles, listArticleDirs } from "../lib/report/registry"; +import { createIteration, readIterationFile, updateIteration, writeIterationFile } from "../lib/report/iterations"; +import { livingFile, listSchedules, readSchedule, seriesFile } from "../lib/report/schedule/store"; +import { parseCadence } from "../lib/report/schedule/cadence"; +import { + claimTick, + createSchedule, + deleteSchedule, + parseCreate, + planCreate, + planDelete, + setPaused, + updateSchedule, +} from "./reportSchedule"; +import { editionGenerator, nextWindow, notWiredFetch, notWiredRefresh, runTick, type StepOutcome, type TickDeps, type TickSteps } from "./reportTick"; +import { scanSchedules } from "./reportScheduleRunner"; +import { reportScheduleAction as action } from "./reportScheduleOps"; + +// The answers, read loosely (each test says which keys it expects). +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const reportScheduleAction = (b: Record<string, unknown>, d: Parameters<typeof action>[1]): Promise<any> => action(b, d); + +const ROOTS: string[] = []; +after(() => { + for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); +}); + +const TZ = "America/New_York"; +// Wed 2026-10-14 08:00 New York. +const NOW = new Date("2026-10-14T12:00:00.000Z"); + +function store() { + const root = mkdtempSync(path.join(tmpdir(), "report-schedule-")); + ROOTS.push(root); + const paths = { + articlesDir: path.join(root, "reports"), + exportIndexDir: path.join(root, ".export-index"), + generationUsageFile: path.join(root, "usage.jsonl"), + jobsDir: path.join(root, ".jobs"), + } as unknown as Paths; + mkdirSync(paths.articlesDir, { recursive: true }); + return paths; +} + +const gen = (over: Record<string, unknown> = {}) => sanitizeGeneration({ routes: { sweep: "api" }, ...over }); + +function depsOf(paths: Paths, steps: Partial<TickSteps> = {}, now: Date = NOW, extra: Partial<TickDeps> = {}): TickDeps { + return { + paths, + now: () => now, + settings: () => ({ generation: gen() }), + knownChannels: async () => ["chan-a", "chan-b"], + steps: { + fetchAndBuild: async () => ({ ok: true }), + refresh: async () => ({ status: "no-change", usd: 0 }), + generateEdition: async () => ({ status: "quiet", usd: 0, matched: 0 }), + ...steps, + }, + ...extra, + }; +} + +const ctx = () => ({ log: () => {}, signal: new AbortController().signal }); +const reportDoc = (id: string, title = `Article ${id}`) => ({ + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title, + sections: [{ id: "s1", title: "One", body: "Plain words." }], +}); + +async function doneIteration(paths: Paths, article: string, title?: string) { + const it = await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?", scope: { channels: ["chan-a"] } }, paths); + await writeIterationFile(article, it.n, "report.json", reportDoc(article, title), paths); + await updateIteration(article, it.n, { status: "done" }, paths); + return it.n; +} + +const weekly = { kind: "weekly", dow: 1, at: "06:00" }; + +// ─── the store and its writer ─── + +test("create: a series in .series/, a living report beside a NEW article that is in the making; dryRun writes nothing", async () => { + const paths = store(); + const deps = depsOf(paths); + const plan = await reportScheduleAction({ action: "create", dryRun: true, shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: weekly, tz: TZ }, deps); + assert.equal(plan.ok, true); + const p = (plan as { plan: { id: string; firstTick: string; firstTickWords: string; firstWindow: { from: string; to: string }; firstTitle: string; capUsd: number; provider: string } }).plan; + assert.equal(p.id, "co-host-updates"); + assert.equal(p.firstTick, "2026-10-19T10:00:00.000Z"); + assert.equal(p.firstTickWords, "Mon 06:00"); + assert.deepEqual(p.firstWindow, { from: "2026-10-12", to: "2026-10-19" }); + assert.equal(p.firstTitle, "Co-host updates · week of 2026-10-12"); + assert.equal(p.capUsd, 5); + assert.equal(p.provider, "api"); + assert.deepEqual(await listSchedules(paths), []); + + const made = await reportScheduleAction({ action: "create", shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: "weekly mon 06:00", tz: TZ, terms: "co-host" }, deps); + assert.equal(made.ok, true, JSON.stringify(made)); + assert.ok(existsSync(seriesFile(paths, "co-host-updates"))); + // A second one with the same topic takes the next id. + const again = await reportScheduleAction({ action: "create", shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: weekly, tz: TZ }, deps); + assert.equal((again as { schedule: { id: string } }).schedule.id, "co-host-updates-2"); + + const living = await reportScheduleAction({ action: "create", shape: "living", topic: "The shop story", question: "What does she say about the shop?", channels: ["chan-b"], cadence: { kind: "daily", at: "07:30" }, tz: TZ }, deps); + assert.equal(living.ok, true, JSON.stringify(living)); + const s = (living as { schedule: { id: string; article: string; nextTick: string; autoMakeCurrent: boolean; chip: string } }).schedule; + assert.equal(s.id, "the-shop-story"); + assert.equal(s.article, "the-shop-story"); + assert.equal(s.autoMakeCurrent, false); + assert.equal(s.nextTick, "2026-10-15T11:30:00.000Z"); + assert.equal(s.chip, "daily · next Thu 07:30"); + assert.ok(existsSync(livingFile(paths, "the-shop-story"))); + // An article in the making, never a broken article. + assert.deepEqual(await listPendingArticles(paths), ["the-shop-story"]); + assert.deepEqual(await listArticleDirs(paths), []); + + const list = await reportScheduleAction({ action: "list" }, { ...deps, lane: () => ({ held: false, armed: false }) }); + assert.deepEqual( + (list as { schedules: { id: string }[] }).schedules.map((x) => x.id), + ["co-host-updates", "co-host-updates-2", "the-shop-story"], + ); +}); + +test("create refuses: the reserved shape, no scope, an unknown channel, an edition flag on the wrong shape, a cap over max", async () => { + const paths = store(); + const deps = depsOf(paths); + const ask = (b: Record<string, unknown>) => reportScheduleAction({ action: "create", topic: "T", channels: ["chan-a"], cadence: weekly, tz: TZ, shape: "series", ...b }, deps); + assert.match(((await ask({ shape: "watch" })) as { error: string }).error, /reserved/); + assert.match(((await ask({ channels: [] })) as { error: string }).error, /scope/); + assert.match(((await ask({ channels: ["nope"] })) as { error: string }).error, /no such channel in this editor: nope/); + assert.match(((await ask({ autoMakeCurrent: true })) as { error: string }).error, /living report/); + assert.match(((await ask({ cadence: { kind: "every", days: 1 } })) as { error: string }).error, /2 to 365/); + assert.match(((await ask({ maxUsd: 50 })) as { error: string }).error, /over the settings' max/); + assert.match(((await ask({ tz: "Mars/Olympus" })) as { error: string }).error, /time zone/); + assert.deepEqual(await listSchedules(paths), []); +}); + +test("update re-plans on a new cadence; pause holds; resume re-plans from now (no catch-up of a pause)", async () => { + const paths = store(); + await createSchedule(parseCreate({ shape: "series", topic: "Weekly", channels: ["chan-a"], cadence: weekly, tz: TZ }), depsOf(paths)); + const later = new Date("2026-10-30T12:00:00.000Z"); + const u = await updateSchedule("weekly", { cadence: parseCadence("every 3 days 09:00") }, depsOf(paths, {}, later)); + assert.equal(u.nextTick, "2026-10-30T13:00:00.000Z"); + assert.equal(u.anchor, "2026-10-30"); + const p = await setPaused("weekly", true, depsOf(paths)); + assert.equal(p.paused, true); + const r = await setPaused("weekly", false, depsOf(paths, {}, new Date("2026-11-20T15:00:00.000Z"))); + assert.equal(r.paused, false); + // On the anchor's grid (Oct 30 + 3k), the first after Nov 20 15:00 local-ish: Nov 23 09:00 EST. + assert.equal(r.nextTick, "2026-11-23T14:00:00.000Z"); + await assert.rejects(updateSchedule("weekly", { autoMakeCurrent: true }, depsOf(paths)), /living report/); +}); + +test("delete: a plan first (what goes, what stays), refused while a tick runs, then gone", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "series", topic: "Gone", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); + const plan = await reportScheduleAction({ action: "delete", id: "gone" }, deps); + assert.equal((plan as { confirmed: boolean }).confirmed, false); + assert.match((plan as { plan: { removes: string } }).plan.removes, /the series gone/); + assert.ok(existsSync(seriesFile(paths, "gone"))); + await claimTick("gone", { jobId: "job-1", trigger: "now" }, deps); + assert.match((await planDelete("gone", deps)).refused ?? "", /job job-1/); + assert.match(((await reportScheduleAction({ action: "delete", id: "gone", confirm: true }, deps)) as { error: string }).error, /cancel it or let it end/); + await updateSchedule("gone", { topic: "Gone" }, deps); + // Released, it goes. + const { recordTick } = await import("./reportSchedule"); + await recordTick("gone", { at: NOW.toISOString(), trigger: "now", jobId: "job-1", status: "quiet", usd: 0 }, deps); + const done = await reportScheduleAction({ action: "delete", id: "gone", confirm: true }, deps); + assert.equal((done as { confirmed: boolean }).confirmed, true); + assert.equal(existsSync(seriesFile(paths, "gone")), false); + await assert.rejects(deleteSchedule("gone", deps), /no schedule/); +}); + +// ─── the runner ─── + +test("the runner: a due schedule gets ONE tick (missed windows counted); paused, ticking and not-due ones none; the gate holds all", async () => { + const paths = store(); + const base = depsOf(paths, {}, new Date("2026-10-01T12:00:00.000Z")); + await createSchedule(parseCreate({ shape: "series", topic: "Due", channels: ["chan-a"], cadence: { kind: "daily", at: "06:00" }, tz: TZ }), base); + await createSchedule(parseCreate({ shape: "series", topic: "Paused", channels: ["chan-a"], cadence: { kind: "daily", at: "06:00" }, tz: TZ }), base); + await createSchedule(parseCreate({ shape: "series", topic: "Later", channels: ["chan-a"], cadence: weekly, tz: TZ }), depsOf(paths, {}, NOW)); + await setPaused("paused", true, base); + // The editor was away from Oct 2 06:00 to Oct 5 08:00 (local): four daily windows. + const now = new Date("2026-10-05T12:00:00.000Z"); + const asked: { id: string; o: unknown }[] = []; + const enqueue = async (id: string, o: { next: string }) => { + asked.push({ id, o }); + await claimTick(id, { jobId: `job-${id}`, trigger: "schedule", next: o.next }, depsOf(paths, {}, now)); + return { ok: true as const, jobId: `job-${id}` }; + }; + const held = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => true, enqueue, isLive: () => true }); + assert.equal(held.held, true); + assert.equal(asked.length, 0); + const r = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => false, enqueue, isLive: () => true }); + assert.deepEqual(r.enqueued.map((e) => [e.id, e.scheduledFor, e.missed]), [["due", "2026-10-02T10:00:00.000Z", 3]]); + assert.deepEqual(asked[0].o, { trigger: "schedule", scheduledFor: "2026-10-02T10:00:00.000Z", next: "2026-10-06T10:00:00.000Z", missed: 3 }); + assert.equal((await readSchedule("due", paths))?.nextTick, "2026-10-06T10:00:00.000Z"); + // A second scan while the tick runs: nothing (never two ticks of one schedule). + const again = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => false, enqueue, isLive: () => true }); + assert.equal(again.enqueued.length, 0); + // The editor died mid-tick: the claim is released, the tick recorded interrupted. + const dead = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => true, enqueue, isLive: () => false }); + assert.deepEqual(dead.interrupted, ["due"]); + const s = await readSchedule("due", paths); + assert.equal(s?.running, null); + assert.equal(s?.ticks.at(-1)?.status, "interrupted"); +}); + +test("claims: a second claim of one schedule is refused", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "series", topic: "One", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); + assert.ok(await claimTick("one", { jobId: "a", trigger: "now" }, deps)); + assert.equal(await claimTick("one", { jobId: "b", trigger: "schedule" }, deps), null); + const r = await reportScheduleAction({ action: "tick-now", id: "one" }, deps); + assert.equal(r.ok, false); + assert.match((r as { error: string }).error, /already queued or running \(job a\)/); +}); + +// ─── the tick, over stubbed steps ─── + +test("living, no change: refresh says so, $0, nothing made current", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "living", topic: "Shop", channels: ["chan-a"], cadence: weekly, tz: TZ, autoMakeCurrent: true }), deps); + await doneIteration(paths, "shop"); + const asked: string[] = []; + const t = await runTick("shop", { trigger: "now", jobId: "j1" }, depsOf(paths, { refresh: async (a) => (asked.push(a), { status: "no-change", usd: 0, reason: "nothing new" }) }, NOW, { makeCurrent: async () => assert.fail("not made current") }), ctx()); + assert.deepEqual(asked, ["shop"]); + assert.equal(t.status, "no-change"); + assert.equal(t.usd, 0); + const s = await readSchedule("shop", paths); + assert.equal(s?.ticks.length, 1); + assert.equal(s?.lastTick, NOW.toISOString()); +}); + +test("living, updated: the new iteration is left ready — or made current when autoMakeCurrent", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "living", topic: "Kept", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); + await createSchedule(parseCreate({ shape: "living", topic: "Auto", channels: ["chan-a"], cadence: weekly, tz: TZ, autoMakeCurrent: true }), deps); + await doneIteration(paths, "kept"); + await doneIteration(paths, "auto"); + const made: string[] = []; + const steps = { refresh: async (): Promise<StepOutcome> => ({ status: "done", usd: 0.42, iteration: 2 }) }; + const extra = { makeCurrent: async (a: string, n: number) => made.push(`${a}/${n}`) }; + const kept = await runTick("kept", { trigger: "schedule", jobId: "j1", scheduledFor: NOW.toISOString() }, depsOf(paths, steps, NOW, extra), ctx()); + assert.equal(kept.status, "done"); + assert.equal(kept.iteration, 2); + assert.equal(kept.usd, 0.42); + assert.deepEqual(made, []); + const auto = await runTick("auto", { trigger: "now", jobId: "j2" }, depsOf(paths, steps, NOW, extra), ctx()); + assert.equal(auto.status, "done"); + assert.deepEqual(made, ["auto/2"]); +}); + +test("living with no report yet: its first tick is the article's first sweep, not a refresh", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "living", topic: "Fresh", channels: ["chan-a"], cadence: { kind: "daily", at: "06:00" }, tz: TZ, from: "2026-01-01" }), deps); + const asked: unknown[] = []; + const t = await runTick( + "fresh", + { trigger: "now", jobId: "j1" }, + depsOf(paths, { + refresh: async () => assert.fail("no report to refresh"), + generateEdition: async (i) => (asked.push({ article: i.article, window: i.window, quiet: i.quietCheck, title: i.title }), { status: "done", usd: 1.5, iteration: 1 }), + }), + ctx(), + ); + assert.equal(t.status, "done"); + assert.deepEqual(asked, [{ article: "fresh", window: { from: "2026-01-01", to: "2026-10-14" }, quiet: false, title: null }]); +}); + +test("series: an edition over the window since the last one's end, titled; then a quiet edition: recorded, no article, $0", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); + const asked: { article: string; window: unknown; title: string | null }[] = []; + const t1 = await runTick( + "co-host-updates", + { trigger: "now", jobId: "j1" }, + depsOf(paths, { generateEdition: async (i) => (asked.push({ article: i.article, window: i.window, title: i.title }), { status: "done", usd: 2.25, iteration: 1, matched: 4, jobId: "draft-1" }) }), + ctx(), + ); + assert.equal(t1.status, "done"); + assert.equal(t1.edition, 1); + assert.equal(t1.article, "co-host-updates-2026-10-14"); + assert.deepEqual(asked[0], { article: "co-host-updates-2026-10-14", window: { from: "2026-10-07", to: "2026-10-14" }, title: "Co-host updates · week of 2026-10-07" }); + let s = await readSchedule("co-host-updates", paths); + assert.deepEqual( + s?.editions?.map((e) => [e.n, e.status, e.article, e.usd, e.matched]), + [[1, "done", "co-host-updates-2026-10-14", 2.25, 4]], + ); + // A week on: the window starts where the last ended; nothing matches. + const week = new Date("2026-10-21T12:00:00.000Z"); + const t2 = await runTick("co-host-updates", { trigger: "schedule", jobId: "j2" }, depsOf(paths, { generateEdition: async (i) => (asked.push({ article: i.article, window: i.window, title: i.title }), { status: "quiet", usd: 0, matched: 0, reason: "nothing matches" }) }, week), ctx()); + assert.equal(t2.status, "quiet"); + assert.equal(t2.usd, 0); + assert.equal(t2.edition, 2); + assert.equal(t2.article, undefined); + assert.deepEqual(asked[1].window, { from: "2026-10-14", to: "2026-10-21" }); + s = await readSchedule("co-host-updates", paths); + assert.deepEqual(s?.editions?.[1], { n: 2, at: week.toISOString(), window: { from: "2026-10-14", to: "2026-10-21" }, title: "Co-host updates · week of 2026-10-14", status: "quiet", usd: 0, reason: "nothing matches", matched: 0 }); + // The next window continues from the quiet one's end. + assert.deepEqual(nextWindow(s!, "2026-10-28"), { from: "2026-10-21", to: "2026-10-28" }); +}); + +test("series held by a cap: no edition (the next tick covers the window), the tick held with its reason and estimate", async () => { + const paths = store(); + const deps = depsOf(paths); + await createSchedule(parseCreate({ shape: "series", topic: "Capped", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); + const t = await runTick( + "capped", + { trigger: "schedule", jobId: "j1" }, + depsOf(paths, { generateEdition: async () => ({ status: "held-by-cap", usd: 0, reason: "the day's Claude API spend is $20.00 … daily cap", estimateUsd: 5 }) }), + ctx(), + ); + assert.equal(t.status, "held-by-cap"); + assert.equal(t.estimateUsd, 5); + const s = await readSchedule("capped", paths); + assert.deepEqual(s?.editions, []); + assert.equal(s?.ticks.at(-1)?.status, "held-by-cap"); + assert.equal(s?.running, null); +}); + +test("until R4 is wired: the fetch step refuses, and the tick fails saying so", async () => { + const paths = store(); + await createSchedule(parseCreate({ shape: "series", topic: "Unwired", channels: ["chan-a"], cadence: weekly, tz: TZ }), depsOf(paths)); + const t = await runTick("unwired", { trigger: "now", jobId: "j1" }, depsOf(paths, { fetchAndBuild: notWiredFetch, refresh: notWiredRefresh }), ctx()); + assert.equal(t.status, "failed"); + assert.match(t.reason ?? "", /not wired: R4's stage 1/); +}); + +// ─── the real generateEdition, as far as it runs without a model ─── + +test("generateEdition: a window with nothing in it is quiet ($0, no job); past the daily cap it is held, before any job", async () => { + const paths = store(); + await createSchedule(parseCreate({ shape: "series", topic: "Real", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths)); + const s = (await readSchedule("real", paths))!; + const draft = { paths, corpusTools: async () => assert.fail("no corpus read"), settings: () => ({ generation: gen() }), now: () => NOW }; + const quiet = await editionGenerator({ draft, countWindow: async (q) => (assert.equal(q.terms, "co-host"), { recordings: 0 }) })( + { schedule: s, article: "real-2026-10-14", title: "Real · week of 2026-10-07", window: { from: "2026-10-07", to: "2026-10-14" }, quietCheck: true }, + ctx(), + ); + assert.deepEqual(quiet, { status: "quiet", usd: 0, matched: 0, reason: "nothing in 2026-10-07 … 2026-10-14 matches co-host" }); + writeFileSync(paths.generationUsageFile, JSON.stringify({ at: NOW.toISOString(), day: "2026-10-14", jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }) + "\n"); + const held = await editionGenerator({ draft, countWindow: async () => ({ recordings: 3 }) })( + { schedule: s, article: "real-2026-10-14", title: "t", window: { from: "2026-10-07", to: "2026-10-14" }, quietCheck: true }, + ctx(), + ); + assert.equal(held.status, "held-by-cap"); + assert.equal(held.estimateUsd, 5); + assert.equal(held.matched, 3); + assert.match(held.reason ?? "", /daily cap/); + // Nothing was made. + assert.equal(existsSync(path.join(paths.articlesDir, "real-2026-10-14")), false); + assert.equal(await readIterationFile("real-2026-10-14", 1, "report.json", paths).catch(() => null), null); + void readFileSync; +}); diff --git a/common/controller/reportSchedule.ts b/common/controller/reportSchedule.ts @@ -0,0 +1,605 @@ +// A RECURRING REPORT'S SCHEDULE — THE ONE WRITER (umtool R5; plans/umtool- +// redesign.md "R5 — Recurring reports"). Every write of a schedule is here: +// create, update, pause/resume, delete, and the tick's own bookkeeping (the +// claim that a tick is queued, its record when it ends, an edition's line). +// Each is a read-patch-write under the article store's lock +// (lib/report/registry.ts withArticleStoreLock), validated, and written whole +// and atomically; lib/report/schedule/store.ts says where. The ops action +// (`pnpm ops report-schedule`, controller/reportScheduleOps.ts) and the +// editor's runner are its only callers; umtool reads the files and writes +// through the ops action. +// +// A tick's own work is controller/reportTick.ts; when a tick is due is +// lib/report/schedule/cadence.ts. + +import { mkdir, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { writeJsonAtomic } from "../lib/jsonFile-server"; +import { withArticleStoreLock, RESERVED_ARTICLE_IDS, ARTICLE_ITERATIONS_DIRNAME } from "../lib/report/registry"; +import { isReportId } from "../lib/report/schema"; +import { capFor, type GenerationSettings } from "../lib/generationSettings"; +import { providerOf } from "../lib/llm"; +import { + CadenceError, + addDays, + anchorFor, + cadenceDays, + cadenceWords, + isTimeZone, + localDate, + localTimeZone, + nextTickAfter, + parseCadence, + tickWords, + type Cadence, +} from "../lib/report/schedule/cadence"; +import { + OFFERED_SHAPES, + SCHEDULE_FORMAT, + SCHEDULE_ID_RE, + SCHEDULE_VERSION, + TICKS_KEPT, + editionTitle, + parseSchedule, + type Edition, + type Schedule, + type ScheduleShape, + type Tick, +} from "../lib/report/schedule/types"; +import { + livingFile, + readScheduleById, + scheduleFile, + seriesDir, + seriesFile, + type SchedulePaths, +} from "../lib/report/schedule/store"; + +export class ScheduleInputError extends Error {} + +// A claim taken before its job's id is known (controller/reportTick.ts +// enqueueTick), moved onto the job as soon as it is. +export const PENDING_PREFIX = "pending-"; + +export type ScheduleDeps = { + paths: SchedulePaths & Partial<Pick<Paths, "exportIndexDir">>; + now?: () => Date; + settings?: () => { generation: GenerationSettings }; + // The channels a scope may name (the editor's); absent: not checked. + knownChannels?: () => Promise<string[]>; +}; + +const nowOf = (deps: ScheduleDeps) => deps.now?.() ?? new Date(); +const fail = (msg: string): never => { + throw new ScheduleInputError(msg); +}; + +// ─── the model and the cap a tick runs on ─── + +/** + * The model a tick's generation runs on: the schedule's, else the sweep + * route's — a sweep routed to Claude Code runs the API model here (a + * schedule runs in the editor; R4's refresh says the same). + */ +export function tickModel(gen: GenerationSettings, s: { model?: string; caps?: { maxUsd?: number } }): { model: string; provider: "api" | "local"; capUsd: number | null; note?: string } { + const route = gen.routes.sweep; + const model = s.model ?? (route === "local" ? gen.models.local : gen.models.api); + const provider = providerOf(model) === "local" ? "local" : "api"; + return { + model, + provider, + capUsd: provider === "api" ? capFor(gen.caps, "sweep", s.caps?.maxUsd) : null, + ...(!s.model && route === "code" ? { note: "sweeps are routed to Claude Code: a tick runs the API model here" } : {}), + }; +} + +// ─── ids ─── + +export function slugOf(text: string, max = 48): string { + const s = text + .toLowerCase() + .normalize("NFKD") + .replace(/[^\p{L}\p{N}]+/gu, "-") + .replace(/[^a-z0-9-]/g, "") + .replace(/-+/g, "-") + .replace(/^-|-$/g, ""); + return (s.slice(0, max).replace(/-$/, "") || "report").replace(/^[^a-z0-9]+/, "") || "report"; +} + +const exists = (p: string) => stat(p).then(() => true, () => false); + +async function idTaken(paths: SchedulePaths, id: string): Promise<boolean> { + return (await exists(seriesFile(paths, id))) || (isReportId(id) && (await exists(livingFile(paths, id)))); +} + +/** A free id from `base`: itself, else base-2, base-3, … */ +async function freeId(base: string, taken: (id: string) => Promise<boolean>): Promise<string> { + for (let k = 1; k < 1000; k++) { + const id = k === 1 ? base : `${base.slice(0, 44)}-${k}`; + if (!(await taken(id))) return id; + } + return fail(`no free id near "${base}"`); +} + +// ─── create ─── + +export type CreateInput = { + shape: ScheduleShape; + topic: string; + question?: string; + id?: string; + article?: string; + channels: string[]; + case?: string; + from?: string; + terms?: string; + regex?: boolean; + cadence: Cadence; + tz: string; + autoMakeCurrent?: boolean; + model?: string; + maxUsd?: number; +}; + +const ymdRe = /^\d{4}-\d{2}-\d{2}$/; + +/** The create body, judged without touching the disk. */ +export function parseCreate(b: Record<string, unknown>): CreateInput { + const shape = b.shape; + if (shape === "watch") fail('"watch" is reserved (triage first, R6): make a "living" report or a "series"'); + if (typeof shape !== "string" || !(OFFERED_SHAPES as readonly string[]).includes(shape)) fail(`"shape" is one of ${OFFERED_SHAPES.join(", ")}`); + const text = (k: string) => { + const v = b[k]; + if (v === undefined || v === null || v === "") return undefined; + if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`); + return (v as string).trim(); + }; + const topic = text("topic") ?? text("question"); + if (!topic) fail('a recurring report needs its "topic" (or "question")'); + const channels = b.channels === undefined ? [] : typeof b.channels === "string" ? b.channels.split(",") : b.channels; + if (!Array.isArray(channels) || !channels.every((c) => typeof c === "string" && c.trim())) fail('"channels" is a list of channel slugs'); + const chans = [...new Set((channels as string[]).map((c) => c.trim()))]; + if (!chans.length) fail('a recurring report needs its scope: "channels" (a board\'s, or named)'); + const from = text("from"); + if (from !== undefined && !ymdRe.test(from)) fail('"from" is a YYYY-MM-DD date'); + let cadence: Cadence; + try { + cadence = parseCadence(b.cadence ?? (b.at ? { kind: "daily", at: b.at } : undefined)); + } catch (e) { + return fail((e as Error).message); + } + const tz = text("tz") ?? localTimeZone(); + if (!isTimeZone(tz)) fail(`"tz" is a time zone this editor knows (an IANA name such as Europe/London): not ${JSON.stringify(tz)}`); + const id = text("id"); + if (id !== undefined && !SCHEDULE_ID_RE.test(id)) fail('"id" is a lowercase slug, at most 48 characters'); + const article = text("article"); + if (article !== undefined) { + if (shape !== "living") fail('"article" is a living report\'s: a series makes an article per edition'); + if (!isReportId(article) || RESERVED_ARTICLE_IDS.includes(article)) fail(`"article" is an article id (a lowercase slug): not ${JSON.stringify(article)}`); + } + if (b.autoMakeCurrent !== undefined && typeof b.autoMakeCurrent !== "boolean") fail('"autoMakeCurrent" is true or false'); + if (b.autoMakeCurrent === true && shape !== "living") fail('"autoMakeCurrent" is a living report\'s (an edition is its own article)'); + if (b.regex !== undefined && typeof b.regex !== "boolean") fail('"regex" is true or false'); + let maxUsd: number | undefined; + if (b.maxUsd !== undefined && b.maxUsd !== null) { + if (typeof b.maxUsd !== "number" || !(b.maxUsd > 0)) fail('"maxUsd" is a positive number of dollars'); + maxUsd = b.maxUsd as number; + } + return { + shape: shape as ScheduleShape, + topic: topic!, + ...(text("question") ? { question: text("question") } : {}), + ...(id ? { id } : {}), + ...(article ? { article } : {}), + channels: chans, + ...(text("case") ? { case: text("case") } : {}), + ...(from ? { from } : {}), + ...(text("terms") ? { terms: text("terms") } : {}), + ...(b.regex === true ? { regex: true } : {}), + cadence: cadence!, + tz, + ...(b.autoMakeCurrent === true ? { autoMakeCurrent: true } : {}), + ...(text("model") ? { model: text("model") } : {}), + ...(maxUsd !== undefined ? { maxUsd } : {}), + }; +} + +export type SchedulePlan = { + id: string; + shape: ScheduleShape; + topic: string; + question: string; + article: string | null; + channels: string[]; + cadence: string; + tz: string; + firstTick: string; + firstTickWords: string; + // A series' first window (the cadence's length back from the first tick's date). + firstWindow: { from: string; to: string } | null; + firstTitle: string | null; + model: string; + provider: "api" | "local"; + capUsd: number | null; + dailyCapUsd: number; + existingArticle: boolean; + warnings: string[]; +}; + +async function articleExists(paths: SchedulePaths, id: string): Promise<boolean> { + const dir = path.join(paths.articlesDir, id); + return (await exists(path.join(dir, "report.json"))) || (await exists(path.join(dir, ARTICLE_ITERATIONS_DIRNAME))); +} + +/** What create would make, nothing written. */ +export async function planCreate(input: CreateInput, deps: ScheduleDeps): Promise<{ plan: SchedulePlan; schedule: Schedule }> { + const paths = deps.paths; + const now = nowOf(deps); + const warnings: string[] = []; + if (deps.knownChannels) { + const known = new Set(await deps.knownChannels()); + const unknown = input.channels.filter((c) => !known.has(c)); + if (unknown.length) fail(`no such channel${unknown.length === 1 ? "" : "s"} in this editor: ${unknown.join(", ")}`); + } + let id: string; + let article: string | null = null; + let existingArticle = false; + if (input.shape === "living") { + if (input.article) { + article = input.article; + existingArticle = await articleExists(paths, article); + if (await exists(livingFile(paths, article))) fail(`"${article}" is a living report already: update its schedule instead`); + if (await exists(seriesFile(paths, article))) fail(`"${article}" is a series' id`); + } else { + const base = slugOf(input.id ?? input.topic, 60); + if (RESERVED_ARTICLE_IDS.includes(base)) fail(`"${base}" is reserved: name the article`); + article = await freeId(base, async (x) => (await articleExists(paths, x)) || (await idTaken(paths, x)) || RESERVED_ARTICLE_IDS.includes(x)); + } + id = article; + } else if (input.id) { + if (await idTaken(paths, input.id)) fail(`"${input.id}" is taken: a schedule has that id`); + id = input.id; + } else { + // Room for an edition's "-YYYY-MM-DD(-n)" in a 64-character article id. + id = await freeId(slugOf(input.topic, 48), (x) => idTaken(paths, x)); + } + const gen = deps.settings?.().generation; + const m = gen ? tickModel(gen, { ...(input.model ? { model: input.model } : {}), ...(input.maxUsd ? { caps: { maxUsd: input.maxUsd } } : {}) }) : null; + if (m?.note) warnings.push(m.note); + if (input.shape === "series" && !input.terms) warnings.push("no terms: a window is quiet only when no recording in scope falls in it"); + const first = nextTickAfter(input.cadence, now.getTime(), input.tz, null); + const anchor = anchorFor(input.cadence, first, input.tz); + const day = localDate(first, input.tz); + const back = addDays(day, -cadenceDays(input.cadence)); + const firstWindow = input.shape === "series" ? { from: input.from && input.from > back ? input.from : back, to: day } : null; + const at = now.toISOString(); + const schedule: Schedule = { + format: SCHEDULE_FORMAT, + version: SCHEDULE_VERSION, + id, + shape: input.shape, + topic: input.topic, + question: input.question ?? input.topic, + ...(article ? { article } : {}), + scope: { + channels: input.channels, + ...(input.case ? { case: input.case } : {}), + ...(input.from ? { from: input.from } : {}), + ...(input.terms ? { terms: input.terms } : {}), + ...(input.regex ? { regex: true } : {}), + }, + cadence: input.cadence, + tz: input.tz, + anchor, + paused: false, + ...(input.shape === "living" ? { autoMakeCurrent: input.autoMakeCurrent === true } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.maxUsd ? { caps: { maxUsd: input.maxUsd } } : {}), + createdAt: at, + updatedAt: at, + lastTick: null, + nextTick: new Date(first).toISOString(), + running: null, + ticks: [], + ...(input.shape === "series" ? { editions: [] } : {}), + }; + const checked = parseSchedule(schedule); + if (!checked.ok) fail(`the schedule does not validate: ${checked.problems.join("; ")}`); + return { + schedule, + plan: { + id, + shape: input.shape, + topic: input.topic, + question: schedule.question, + article, + channels: input.channels, + cadence: cadenceWords(input.cadence), + tz: input.tz, + firstTick: schedule.nextTick!, + firstTickWords: tickWords(first, input.tz, now.getTime()), + firstWindow, + firstTitle: firstWindow ? editionTitle(input.topic, input.cadence, firstWindow) : null, + model: m?.model ?? input.model ?? "", + provider: m?.provider ?? (input.model && providerOf(input.model) === "local" ? "local" : "api"), + capUsd: m?.capUsd ?? null, + dailyCapUsd: gen?.caps.daily ?? 0, + existingArticle, + warnings, + }, + }; +} + +/** Make the schedule (the operator's act: nothing else creates one). */ +export async function createSchedule(input: CreateInput, deps: ScheduleDeps): Promise<{ plan: SchedulePlan; schedule: Schedule }> { + return withArticleStoreLock(async () => { + const out = await planCreate(input, deps); + const s = out.schedule; + if (s.shape === "living") { + // A new article is "in the making" from the start (store.ts). + await mkdir(path.join(deps.paths.articlesDir, s.id, ARTICLE_ITERATIONS_DIRNAME), { recursive: true }); + } else { + await mkdir(seriesDir(deps.paths, s.id), { recursive: true }); + } + await writeJsonAtomic(scheduleFile(deps.paths, s.shape, s.id), s, { mkdir: true }); + return out; + }, deps.paths); +} + +// ─── read-patch-write ─── + +export async function mutateSchedule(id: string, deps: ScheduleDeps, fn: (s: Schedule, now: Date) => Schedule | Promise<Schedule>): Promise<Schedule> { + return withArticleStoreLock(async () => { + const r = await readScheduleById(id, deps.paths); + if (!r) fail(`no schedule "${id}"`); + if (!r!.ok) fail(`the schedule "${id}" does not read (${r!.file}): ${(r as { problem: string }).problem}`); + const now = nowOf(deps); + const next = { ...(await fn((r as { schedule: Schedule }).schedule, now)), updatedAt: now.toISOString() }; + const checked = parseSchedule(next); + if (!checked.ok) fail(`the schedule "${id}" would not validate: ${checked.problems.join("; ")}`); + await writeJsonAtomic(r!.file, next); + return next; + }, deps.paths); +} + +export type UpdateInput = { + topic?: string; + question?: string; + cadence?: Cadence; + tz?: string; + channels?: string[]; + from?: string | null; + terms?: string | null; + regex?: boolean; + autoMakeCurrent?: boolean; + model?: string | null; + maxUsd?: number | null; +}; + +export function parseUpdate(b: Record<string, unknown>): UpdateInput { + const out: UpdateInput = {}; + const text = (k: string) => { + const v = b[k]; + if (v === undefined) return undefined; + if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`); + return (v as string).trim(); + }; + const orNull = (k: string) => (b[k] === null || b[k] === "" ? null : text(k)); + if (b.topic !== undefined) out.topic = text("topic"); + if (b.question !== undefined) out.question = text("question"); + if (b.cadence !== undefined) { + try { + out.cadence = parseCadence(b.cadence); + } catch (e) { + fail((e as Error).message); + } + } + if (b.tz !== undefined) { + const tz = text("tz")!; + if (!isTimeZone(tz)) fail(`"tz" is a time zone this editor knows: not ${JSON.stringify(tz)}`); + out.tz = tz; + } + if (b.channels !== undefined) { + const arr = typeof b.channels === "string" ? b.channels.split(",") : b.channels; + if (!Array.isArray(arr) || !arr.length || !arr.every((c) => typeof c === "string" && c.trim())) fail('"channels" is a non-empty list of channel slugs'); + out.channels = [...new Set((arr as string[]).map((c) => c.trim()))]; + } + if (b.from !== undefined) { + const v = orNull("from"); + if (v !== null && !ymdRe.test(v!)) fail('"from" is a YYYY-MM-DD date'); + out.from = v ?? null; + } + if (b.terms !== undefined) out.terms = orNull("terms") ?? null; + if (b.regex !== undefined) { + if (typeof b.regex !== "boolean") fail('"regex" is true or false'); + out.regex = b.regex as boolean; + } + if (b.autoMakeCurrent !== undefined) { + if (typeof b.autoMakeCurrent !== "boolean") fail('"autoMakeCurrent" is true or false'); + out.autoMakeCurrent = b.autoMakeCurrent as boolean; + } + if (b.model !== undefined) out.model = orNull("model") ?? null; + if (b.maxUsd !== undefined) { + if (b.maxUsd !== null && (typeof b.maxUsd !== "number" || !(b.maxUsd > 0))) fail('"maxUsd" is a positive number of dollars, or null'); + out.maxUsd = b.maxUsd as number | null; + } + if (!Object.keys(out).length) fail("nothing to change: send topic, question, cadence, tz, channels, from, terms, regex, autoMakeCurrent, model or maxUsd"); + return out; +} + +/** Change a schedule. A new cadence or zone re-plans the next tick (and an every-N-days grid's anchor) from now. */ +export async function updateSchedule(id: string, patch: UpdateInput, deps: ScheduleDeps): Promise<Schedule> { + if (patch.channels && deps.knownChannels) { + const known = new Set(await deps.knownChannels()); + const unknown = patch.channels.filter((c) => !known.has(c)); + if (unknown.length) fail(`no such channel${unknown.length === 1 ? "" : "s"} in this editor: ${unknown.join(", ")}`); + } + const gen = deps.settings?.().generation; + if (gen && patch.maxUsd) capFor(gen.caps, "sweep", patch.maxUsd); + return mutateSchedule(id, deps, (s, now) => { + if (patch.autoMakeCurrent !== undefined && s.shape !== "living") fail('"autoMakeCurrent" is a living report\'s'); + const cadence = patch.cadence ?? s.cadence; + const tz = patch.tz ?? s.tz; + const replan = patch.cadence !== undefined || patch.tz !== undefined; + let nextTick = s.nextTick; + let anchor = s.anchor ?? null; + if (replan) { + const t = nextTickAfter(cadence, now.getTime(), tz, null); + anchor = anchorFor(cadence, t, tz); + nextTick = new Date(t).toISOString(); + } + const scope = { ...s.scope }; + if (patch.channels) scope.channels = patch.channels; + if (patch.from !== undefined) { + if (patch.from === null) delete scope.from; + else scope.from = patch.from; + } + if (patch.terms !== undefined) { + if (patch.terms === null) delete scope.terms; + else scope.terms = patch.terms; + } + if (patch.regex !== undefined) scope.regex = patch.regex; + const next: Schedule = { ...s, cadence, tz, anchor, nextTick, scope }; + if (patch.topic) next.topic = patch.topic; + if (patch.question) next.question = patch.question; + if (patch.autoMakeCurrent !== undefined) next.autoMakeCurrent = patch.autoMakeCurrent; + if (patch.model !== undefined) { + if (patch.model === null) delete next.model; + else next.model = patch.model; + } + if (patch.maxUsd !== undefined) { + if (patch.maxUsd === null) delete next.caps; + else next.caps = { ...(s.caps ?? {}), maxUsd: patch.maxUsd }; + } + return next; + }); +} + +/** Pause or resume. A resume re-plans the next tick from now: the windows a pause skipped are not caught up. */ +export async function setPaused(id: string, paused: boolean, deps: ScheduleDeps): Promise<Schedule> { + return mutateSchedule(id, deps, (s, now) => { + if (s.paused === paused) return s; + if (paused) return { ...s, paused: true }; + const t = nextTickAfter(s.cadence, now.getTime(), s.tz, s.anchor); + return { ...s, paused: false, nextTick: new Date(t).toISOString() }; + }); +} + +// ─── delete ─── + +export type DeletePlan = { + id: string; + shape: ScheduleShape; + file: string; + // Words for the plan's head and its confirm. + removes: string; + keeps: string[]; + refused: string | null; +}; + +export async function planDelete(id: string, deps: ScheduleDeps): Promise<DeletePlan> { + const r = await readScheduleById(id, deps.paths); + if (!r) fail(`no schedule "${id}"`); + if (!r!.ok) { + // An unreadable file is still removable: say what it is. + const shape: ScheduleShape = r!.file.endsWith("series.json") ? "series" : "living"; + return { id, shape, file: r!.file, removes: `the unreadable schedule ${path.relative(deps.paths.articlesDir, r!.file)}`, keeps: [], refused: null }; + } + const s = (r as { schedule: Schedule }).schedule; + const refused = s.running ? `a tick is ${s.running.trigger === "now" ? "queued or running" : "running"} (job ${s.running.jobId}) — cancel it or let it end first` : null; + if (s.shape === "living") { + return { + id, + shape: s.shape, + file: r!.file, + removes: `the schedule of ${s.article ?? s.id} (${cadenceWords(s.cadence)}, ${s.ticks.length} tick${s.ticks.length === 1 ? "" : "s"} recorded)`, + keeps: [`the article ${s.article ?? s.id} and its iterations`], + refused, + }; + } + const eds = (s.editions ?? []).filter((e) => e.article); + const quiet = (s.editions ?? []).length - eds.length; + return { + id, + shape: s.shape, + file: r!.file, + removes: `the series ${s.id} (${cadenceWords(s.cadence)}): its schedule, ${s.ticks.length} tick${s.ticks.length === 1 ? "" : "s"} and ${(s.editions ?? []).length} edition line${(s.editions ?? []).length === 1 ? "" : "s"}${quiet ? ` (${quiet} quiet)` : ""}`, + keeps: eds.length ? [`${eds.length} edition article${eds.length === 1 ? "" : "s"}, as articles: ${eds.map((e) => e.article).join(", ")}`] : [], + refused, + }; +} + +/** Delete a schedule. The plan is re-read under the lock; a refusal stands. */ +export async function deleteSchedule(id: string, deps: ScheduleDeps): Promise<DeletePlan> { + return withArticleStoreLock(async () => { + const plan = await planDelete(id, deps); + if (plan.refused) fail(plan.refused); + if (plan.shape === "living") await rm(plan.file, { force: true }); + else await rm(seriesDir(deps.paths, id), { recursive: true, force: true }); + return plan; + }, deps.paths); +} + +// ─── the tick's bookkeeping (controller/reportTick.ts, the runner) ─── + +/** + * Claim a tick for job `jobId`: refused (null) when one is already queued or + * running. A scheduled claim moves `nextTick` on to the first window after + * now — the missed ones are counted, never queued. + */ +export async function claimTick( + id: string, + o: { jobId: string; trigger: "schedule" | "now"; scheduledFor?: string; next?: string }, + deps: ScheduleDeps, +): Promise<Schedule | null> { + let refused = false; + const out = await mutateSchedule(id, deps, (s, now) => { + if (s.running) { + refused = true; + return s; + } + return { + ...s, + running: { jobId: o.jobId, at: now.toISOString(), trigger: o.trigger, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}) }, + ...(o.next ? { nextTick: o.next } : {}), + }; + }); + return refused ? null : out; +} + +/** Give a claim back (its job never started). */ +export async function releaseClaim(id: string, jobId: string, deps: ScheduleDeps): Promise<void> { + await mutateSchedule(id, deps, (s) => (s.running?.jobId === jobId ? { ...s, running: null } : s)).catch(() => {}); +} + +/** Point a claim at the job that holds it (the job's id is known only once it is enqueued). */ +export async function moveClaim(id: string, from: string, to: string, deps: ScheduleDeps): Promise<void> { + await mutateSchedule(id, deps, (s) => (s.running?.jobId === from ? { ...s, running: { ...s.running, jobId: to } } : s)); +} + +/** Record a tick's end: its line in the history (the newest TICKS_KEPT), the claim released, `lastTick`. */ +export async function recordTick(id: string, tick: Tick, deps: ScheduleDeps): Promise<Schedule> { + return mutateSchedule(id, deps, (s) => ({ + ...s, + running: s.running && (!tick.jobId || s.running.jobId === tick.jobId || s.running.jobId.startsWith(PENDING_PREFIX)) ? null : s.running, + lastTick: tick.at, + ticks: [...s.ticks, tick].slice(-TICKS_KEPT), + })); +} + +/** Drop a series' edition line (a tick that made nothing). */ +export async function dropEdition(id: string, n: number, deps: ScheduleDeps): Promise<void> { + await mutateSchedule(id, deps, (s) => ({ ...s, editions: (s.editions ?? []).filter((e) => e.n !== n) })); +} + +/** Add or replace a series' edition (by its number). */ +export async function putEdition(id: string, e: Edition, deps: ScheduleDeps): Promise<Schedule> { + return mutateSchedule(id, deps, (s) => { + if (s.shape !== "series") fail(`"${id}" is not a series`); + const rest = (s.editions ?? []).filter((x) => x.n !== e.n); + return { ...s, editions: [...rest, e].sort((a, b) => a.n - b.n) }; + }); +} + +export { CadenceError }; diff --git a/common/controller/reportScheduleOps.ts b/common/controller/reportScheduleOps.ts @@ -0,0 +1,165 @@ +// `pnpm ops report-schedule` — a recurring report's schedule, as one ops action +// (umtool R5). The editor's route is an adapter over `reportScheduleAction`; +// umtool's Create, series page and chip post here. The writes are +// controller/reportSchedule.ts's; a tick is controller/reportTick.ts's. +// +// {"action": "list", "id"?} every schedule (or one), with its +// chip, its call and its spend +// {"action": "create", …, "dryRun"?} the plan (first tick, model, cap) +// with dryRun, else the schedule +// {"action": "update", "id", …} topic, question, cadence, tz, +// channels, from, terms, regex, +// autoMakeCurrent, model, maxUsd +// {"action": "pause" | "resume", "id"} a resume re-plans from now +// {"action": "delete", "id", "confirm"?} the plan, unless confirm: true +// {"action": "tick-now", "id"} one tick now (refused while one +// is queued or running) + +import { getSettings } from "../lib/settings"; +import { ArticleRegistryError } from "../lib/report/registry"; +import { CadenceError } from "../lib/report/schedule/cadence"; +import { isGateHeld } from "../lib/pauseGates"; +import { listScheduleReads, readScheduleById } from "../lib/report/schedule/store"; +import { callOf, scheduleChip, spentOf, type Schedule, type Tick } from "../lib/report/schedule/types"; +import { + ScheduleInputError, + createSchedule, + deleteSchedule, + parseCreate, + parseUpdate, + planCreate, + planDelete, + setPaused, + updateSchedule, +} from "./reportSchedule"; +import { enqueueTick, type TickDeps } from "./reportTick"; +import { isReportScheduleArmed } from "./reportScheduleRunner"; + +export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now"] as const; +export type ReportScheduleActionName = (typeof REPORT_SCHEDULE_ACTIONS)[number]; + +export const REPORT_SCHEDULE_BODY_KEYS = [ + "action", + "id", + "shape", + "topic", + "question", + "article", + "channels", + "case", + "from", + "terms", + "regex", + "cadence", + "at", + "tz", + "autoMakeCurrent", + "model", + "maxUsd", + "confirm", + "dryRun", +] as const; + +export type ScheduleView = Schedule & { + chip: string; + // The newest tick when it is the operator's call (failed, held by a cap, interrupted). + call: Tick | null; + spentUsd: number; +}; + +export const viewOf = (s: Schedule, now?: number): ScheduleView => ({ ...s, chip: scheduleChip(s, now), call: callOf(s), spentUsd: spentOf(s) }); + +export type LaneView = { held: boolean; armed: boolean }; + +export function laneView(settings: () => Parameters<typeof isGateHeld>[0] = getSettings): LaneView { + let held = false; + try { + held = isGateHeld(settings(), "report-schedule"); + } catch { + /* settings unreadable: not held */ + } + return { held, armed: isReportScheduleArmed() }; +} + +type Ok = { ok: true } & Record<string, unknown>; +type Refused = { ok: false; error: string; status?: number }; + +const idOf = (b: Record<string, unknown>): string => { + if (typeof b.id !== "string" || !b.id.trim()) throw new ScheduleInputError('"id" names the schedule (a series\' id, or a living report\'s article)'); + return b.id.trim(); +}; + +/** One `report-schedule` ask. Input errors answer `{ok: false, error}` (a 400); nothing throws for them. */ +export async function reportScheduleAction( + body: Record<string, unknown>, + deps: TickDeps & { lane?: () => LaneView }, +): Promise<Ok | Refused> { + const action = body.action; + if (typeof action !== "string" || !(REPORT_SCHEDULE_ACTIONS as readonly string[]).includes(action)) { + return { ok: false, error: `"action" is one of ${REPORT_SCHEDULE_ACTIONS.join(", ")}` }; + } + const now = (deps.now?.() ?? new Date()).getTime(); + try { + switch (action as ReportScheduleActionName) { + case "list": { + const lane = (deps.lane ?? (() => laneView()))(); + if (body.id !== undefined) { + const r = await readScheduleById(idOf(body), deps.paths); + if (!r) return { ok: false, error: `no schedule "${String(body.id)}"`, status: 404 }; + if (!r.ok) return { ok: false, error: `the schedule "${r.id}" does not read (${r.file}): ${r.problem}` }; + return { ok: true, schedule: viewOf(r.schedule, now), lane }; + } + const reads = await listScheduleReads(deps.paths); + return { + ok: true, + schedules: reads.flatMap((r) => (r.ok ? [viewOf(r.schedule, now)] : [])), + problems: reads.flatMap((r) => (r.ok ? [] : [{ id: r.id, file: r.file, problem: r.problem }])), + lane, + }; + } + case "create": { + const input = parseCreate(body); + if (body.dryRun === true) { + const { plan } = await planCreate(input, deps); + return { ok: true, plan }; + } + const { plan, schedule } = await createSchedule(input, deps); + return { ok: true, plan, schedule: viewOf(schedule, now) }; + } + case "update": { + const s = await updateSchedule(idOf(body), parseUpdate(body), deps); + return { ok: true, schedule: viewOf(s, now) }; + } + case "pause": + case "resume": { + const s = await setPaused(idOf(body), action === "pause", deps); + return { ok: true, schedule: viewOf(s, now) }; + } + case "delete": { + const id = idOf(body); + if (body.confirm !== true) { + const plan = await planDelete(id, deps); + return { ok: true, confirmed: false, plan }; + } + const plan = await deleteSchedule(id, deps); + return { ok: true, confirmed: true, deleted: plan }; + } + case "tick-now": { + const id = idOf(body); + const r = await readScheduleById(id, deps.paths); + if (!r) return { ok: false, error: `no schedule "${id}"`, status: 404 }; + if (!r.ok) return { ok: false, error: `the schedule "${id}" does not read: ${r.problem}` }; + const out = await enqueueTick(id, { trigger: "now" }, deps); + if (!out.ok) return { ok: false, error: out.error, ...(out.running ? { status: 409 } : {}) }; + return { ok: true, jobId: out.jobId }; + } + } + } catch (e) { + if (e instanceof ScheduleInputError || e instanceof CadenceError) return { ok: false, error: (e as Error).message }; + // The registry's own refusals (the store busy, a bad id) are input-shaped too. + if (e instanceof ArticleRegistryError) return { ok: false, error: (e as Error).message }; + if (/maxUsd/.test((e as Error).message)) return { ok: false, error: (e as Error).message }; + throw e; + } + return { ok: false, error: "unreachable" }; +} diff --git a/common/controller/reportScheduleRunner.ts b/common/controller/reportScheduleRunner.ts @@ -0,0 +1,180 @@ +// THE `report-schedule` LANE (umtool R5): the editor keeps the schedules. +// +// Armed by the editor's instrumentation BELOW the idle gate, beside the +// research auto-continue it is shaped after (controller/ +// researchAutoContinue.ts): ARCHILYZER_IDLE_BOOT arms nothing, and +// `armReportSchedule` refuses an idle boot itself too. Once armed, a SCAN +// runs now and then every CHECK_MS on an unref'd timer (the process's +// lifetime, like the sync heartbeat), and: +// +// - the lane's PAUSE GATE (lib/pauseGates.ts, lane `report-schedule`, +// `settings.reportSchedule.held`) is read first: held, the scan +// enqueues nothing. A hold is never a stop — a tick already queued or +// running finishes. Tick now is the operator's word and is not held; +// - a claim whose job is gone (the editor stopped mid-tick) is recorded +// `interrupted` and released, so the schedule ticks again; +// - each schedule not paused, not ticking and due (cadence.ts dueTick) +// gets ONE `report-tick` job (controller/reportTick.ts enqueueTick), +// its claim taken first, its next window the first after now — a +// window missed while the editor was down is one catch-up tick, never N. +// The ticks themselves run one at a time (REPORT_TICK_QUEUE). +// +// Not a long-lived registry job (the auto-queue runners are): a tick is the +// job, and the Running list shows the ticks rather than a runner that only +// waits. + +import { isIdleBoot } from "../lib/idleBoot"; +import { getRegistry } from "../jobs/registry"; +import { getSettings, type SiteSettings } from "../lib/settings"; +import { isGateHeld } from "../lib/pauseGates"; +import { dueTick } from "../lib/report/schedule/cadence"; +import { listSchedules } from "../lib/report/schedule/store"; +import type { Schedule } from "../lib/report/schedule/types"; +import { PENDING_PREFIX, recordTick } from "./reportSchedule"; +import { enqueueTick, type EnqueueTickResult, type TickDeps } from "./reportTick"; + +export const CHECK_MS = 60_000; +// A claim taken and never handed to a job (the editor died between the two). +export const PENDING_STALE_MS = 2 * 60_000; + +export type ScanDeps = { + deps: TickDeps; + // The lane's gate (default: settings.reportSchedule.held). + held?: () => boolean; + // Is this job queued or running in this process? (default: the registry) + isLive?: (jobId: string) => boolean; + enqueue?: (id: string, o: { trigger: "schedule"; scheduledFor: string; next: string; missed: number }) => Promise<EnqueueTickResult>; + log?: (line: string) => void; +}; + +export type ScanResult = { + held: boolean; + schedules: number; + enqueued: { id: string; jobId: string; scheduledFor: string; missed: number }[]; + refused: { id: string; error: string }[]; + interrupted: string[]; +}; + +const liveInRegistry = (jobId: string) => { + const j = getRegistry().get(jobId); + return !!j && (j.status === "queued" || j.status === "running"); +}; + +function gateHeld(settings: () => SiteSettings = getSettings): boolean { + try { + return isGateHeld(settings(), "report-schedule"); + } catch { + return false; + } +} + +/** Is this schedule's claim dead (its job gone)? */ +function deadClaim(s: Schedule, now: number, isLive: (id: string) => boolean): boolean { + if (!s.running) return false; + if (s.running.jobId.startsWith(PENDING_PREFIX)) return now - Date.parse(s.running.at) > PENDING_STALE_MS; + return !isLive(s.running.jobId); +} + +/** One pass over the schedules (see the head of this file). */ +export async function scanSchedules(o: ScanDeps): Promise<ScanResult> { + const { deps } = o; + const now = (deps.now?.() ?? new Date()).getTime(); + const isLive = o.isLive ?? liveInRegistry; + const out: ScanResult = { held: false, schedules: 0, enqueued: [], refused: [], interrupted: [] }; + const schedules = await listSchedules(deps.paths); + out.schedules = schedules.length; + for (const s of schedules) { + if (!deadClaim(s, now, isLive)) continue; + await recordTick( + s.id, + { + at: new Date(now).toISOString(), + trigger: s.running!.trigger, + jobId: s.running!.jobId, + status: "interrupted", + usd: 0, + reason: "the editor stopped during the tick (its job is gone)", + ...(s.running!.scheduledFor ? { scheduledFor: s.running!.scheduledFor } : {}), + }, + deps, + ).catch(() => {}); + s.running = null; + out.interrupted.push(s.id); + o.log?.(`report-schedule: ${s.id}: a tick was interrupted (job gone); released`); + } + if ((o.held ?? (() => gateHeld()))()) { + out.held = true; + return out; + } + const enqueue = o.enqueue ?? ((id, x) => enqueueTick(id, x, deps)); + for (const s of schedules) { + if (s.running) continue; + const d = dueTick(s, now); + if (!d.due) continue; + const scheduledFor = new Date(d.scheduledFor).toISOString(); + const r = await enqueue(s.id, { trigger: "schedule", scheduledFor, next: new Date(d.next).toISOString(), missed: d.missed }); + if (r.ok) { + out.enqueued.push({ id: s.id, jobId: r.jobId, scheduledFor, missed: d.missed }); + o.log?.(`report-schedule: ${s.id}: tick for ${scheduledFor}${d.missed ? ` (stands in for ${d.missed} missed)` : ""} → job ${r.jobId}`); + } else { + out.refused.push({ id: s.id, error: r.error }); + o.log?.(`report-schedule: ${s.id}: not ticked: ${r.error}`); + } + } + return out; +} + +// ─── arming (the editor's instrumentation, below the idle gate) ─── + +type Armed = { o: ScanDeps; timer: ReturnType<typeof setInterval> | null; scanning: Promise<ScanResult> | null }; + +declare global { + // eslint-disable-next-line no-var + var __yttReportSchedule__: Armed | undefined; +} + +/** One scan at a time: a second caller shares the one going. Null when unarmed. */ +export function reportScheduleTick(): Promise<ScanResult> | null { + const a = globalThis.__yttReportSchedule__; + if (!a) return null; + if (!a.scanning) { + a.scanning = scanSchedules(a.o).finally(() => { + a.scanning = null; + }); + } + return a.scanning; +} + +/** + * Arm the lane: a scan now and every `everyMs` (default CHECK_MS). Refused + * (false) on an idle boot. Idempotent: a second call only replaces the deps. + */ +export function armReportSchedule(o: ScanDeps, opts: { env?: Record<string, string | undefined>; everyMs?: number; bootScan?: boolean } = {}): boolean { + if (isIdleBoot(opts.env)) return false; + const armed = globalThis.__yttReportSchedule__; + if (armed) { + armed.o = o; + return true; + } + const state: Armed = { o, timer: null, scanning: null }; + globalThis.__yttReportSchedule__ = state; + const every = opts.everyMs ?? CHECK_MS; + if (every > 0) { + state.timer = setInterval(() => { + void reportScheduleTick()?.catch((e) => state.o.log?.(`report-schedule: the scan failed: ${(e as Error).message}`)); + }, every); + state.timer.unref?.(); + } + if (opts.bootScan !== false) void reportScheduleTick()?.catch(() => {}); + return true; +} + +export function disarmReportSchedule(): void { + const a = globalThis.__yttReportSchedule__; + if (a?.timer) clearInterval(a.timer); + globalThis.__yttReportSchedule__ = undefined; +} + +export function isReportScheduleArmed(): boolean { + return globalThis.__yttReportSchedule__ !== undefined; +} diff --git a/common/controller/reportTick.ts b/common/controller/reportTick.ts @@ -0,0 +1,430 @@ +// A RECURRING REPORT'S TICK (umtool R5; plans/umtool-redesign.md "R5"): ONE +// editor job, kind `report-tick` on its own queue (REPORT_TICK_QUEUE: one tick +// at a time machine-wide), whose steps go through a SEAM, `TickSteps`: +// +// fetchAndBuild(scope) R4's stage 1: the editor's own paced fetches for the +// scope's channels, then a LOCAL build of the site +// that holds them (a sweep reads a composed build) +// refresh(article) R4's `report-draft {"task":"refresh"}` — what +// changed, then an update when anything did (its +// own no-change/$0 and held-by-cap outcomes) +// generateEdition(...) a sweep over a window as a new article (the +// existing generate path with from/to), after a +// window check: nothing in it is a QUIET edition +// triage?(...) reserved for R6 (triage first) +// +// THE TICK, by shape: +// living fetchAndBuild → refresh → when `autoMakeCurrent`, the new +// iteration made current, else left ready (an iteration-ready +// Review card). A living report with no report yet takes its first +// sweep instead of a refresh. +// series fetchAndBuild → an EDITION: a new article +// `<series>-<YYYY-MM-DD>` over the window since the last edition's +// window end (the first: the cadence's length back), titled +// "<topic> · week of <date>" / "<topic> · <date>". A quiet window is +// recorded, no article, $0. +// +// Caps: the generation policy's per-job cap (the schedule's own, never above +// caps.max) and the daily cap; a refusal ends the tick `held-by-cap` — the +// operator's call, with the reason and the estimate. +// +// Every tick ends with a line in the schedule's history (controller/ +// reportSchedule.ts recordTick) and the log's `@@report-tick {json}`. + +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import type { Paths } from "../lib/paths"; +import { REPORT_TICK_QUEUE } from "../lib/queueKeys"; +import { getSettings } from "../lib/settings"; +import type { GenerationSettings } from "../lib/generationSettings"; +import { + currentIteration, + iterationUsd, + listIterations, + makeCurrent, + readIteration, + readIterationFile, + writeIterationFile, +} from "../lib/report/iterations"; +import { addDays, cadenceDays, localDate } from "../lib/report/schedule/cadence"; +import { readSchedule } from "../lib/report/schedule/store"; +import { editionTitle, type Edition, type Schedule, type Tick, type TickStatus } from "../lib/report/schedule/types"; +import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage"; +import { enqueueReportDraft, type ReportDraftDeps } from "./reportDraft"; +import { + PENDING_PREFIX, + claimTick, + dropEdition, + moveClaim, + putEdition, + recordTick, + releaseClaim, + tickModel, + type ScheduleDeps, +} from "./reportSchedule"; +import { stat } from "node:fs/promises"; +import path from "node:path"; + +export const REPORT_TICK_JOB_KIND = "report-tick"; +export const REPORT_TICK_RESULT_MARKER = "@@report-tick "; + +// ─── the seam ─── + +export type StepCtx = { log: (line: string) => void; signal: AbortSignal }; + +export type FetchOutcome = { ok: true; note?: string } | { ok: false; status: "failed" | "held-by-cap"; reason: string }; + +export type StepStatus = "done" | "no-change" | "quiet" | "held-by-cap" | "failed" | "cancelled"; +export type StepOutcome = { + status: StepStatus; + // The iteration made (a refresh's, an edition's sweep). + iteration?: number; + usd: number; + reason?: string; + jobId?: string; + // What a held step would have cost at most (its cap). + estimateUsd?: number; + // Recordings the window check matched. + matched?: number; +}; + +export type EditionInput = { + schedule: Schedule; + // The article the sweep writes (a new one; an edition's, or a living + // report's first). + article: string; + // The report's title once done (an edition's); null keeps the model's. + title: string | null; + window: { from: string; to: string }; + // A series' window check (a living report's first sweep has none). + quietCheck: boolean; +}; + +export type TickSteps = { + fetchAndBuild(scope: { channels: string[] }, ctx: StepCtx): Promise<FetchOutcome>; + refresh(article: string, o: { model?: string; maxUsd?: number }, ctx: StepCtx): Promise<StepOutcome>; + generateEdition(input: EditionInput, ctx: StepCtx): Promise<StepOutcome>; + // R6: a cheap pass that flags what is worth a sweep (not called yet). + triage?(input: { schedule: Schedule; window: { from: string; to: string } }, ctx: StepCtx): Promise<unknown>; +}; + +// Until R4 is in this editor, its two steps refuse, saying so. +export const NOT_WIRED_FETCH = "not wired: R4's stage 1 (fetch + local build) is not in this editor yet"; +export const NOT_WIRED_REFRESH = "not wired: R4's refresh (report-draft task refresh) is not in this editor yet"; +export const notWiredFetch: TickSteps["fetchAndBuild"] = async () => ({ ok: false, status: "failed", reason: NOT_WIRED_FETCH }); +export const notWiredRefresh: TickSteps["refresh"] = async () => ({ status: "failed", usd: 0, reason: NOT_WIRED_REFRESH }); + +// ─── the real generateEdition ─── + +/** A window's recordings for the quiet check: `{recordings}` or why it could not say. */ +export type CountWindow = (q: { channels: string[]; from: string; to: string; terms?: string; regex?: boolean }) => Promise<{ recordings: number } | { error: string }>; + +export type EditionDeps = { + draft: ReportDraftDeps; + // The window check (the editor's enumerate over the corpus). Absent: no + // quiet editions — every window is swept. + countWindow?: CountWindow; +}; + +const settingsOf = (d: { settings?: () => { generation: GenerationSettings } }) => (d.settings ?? getSettings)().generation; + +/** The cap refusal's words (the daily cap's own sentence): a refusal that says them is held, not failed. */ +export const isCapRefusal = (reason: string) => /daily cap|caps\.daily|caps\.max|over the settings' max/.test(reason); + +/** The existing generate path (a `report-draft` sweep with from/to) as a tick step: window check, cap, the job, its end. */ +export function editionGenerator(deps: EditionDeps): TickSteps["generateEdition"] { + return async (input, ctx) => { + const { schedule: s, window } = input; + const paths = deps.draft.paths; + const gen = settingsOf(deps.draft); + let matched: number | undefined; + if (input.quietCheck && deps.countWindow) { + const c = await deps.countWindow({ + channels: s.scope.channels, + from: window.from, + to: window.to, + ...(s.scope.terms ? { terms: s.scope.terms } : {}), + ...(s.scope.regex ? { regex: true } : {}), + }); + if ("error" in c) return { status: "failed", usd: 0, reason: `the window check failed: ${c.error}` }; + matched = c.recordings; + if (c.recordings === 0) { + return { + status: "quiet", + usd: 0, + matched: 0, + reason: s.scope.terms ? `nothing in ${window.from} … ${window.to} matches ${s.scope.terms}` : `no recording in scope in ${window.from} … ${window.to}`, + }; + } + ctx.log(`window ${window.from} … ${window.to}: ${c.recordings} recording${c.recordings === 1 ? "" : "s"} match`); + } + let m: ReturnType<typeof tickModel>; + try { + m = tickModel(gen, s); + } catch (e) { + return { status: "held-by-cap", usd: 0, reason: (e as Error).message }; + } + if (m.note) ctx.log(m.note); + if (m.provider === "api") { + const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.draft.now?.())), gen.caps.daily); + if (refusal) return { status: "held-by-cap", usd: 0, reason: refusal, ...(m.capUsd !== null ? { estimateUsd: m.capUsd } : {}), ...(matched !== undefined ? { matched } : {}) }; + } + const out = await enqueueReportDraft( + { + task: "sweep", + article: input.article, + question: s.question, + channels: s.scope.channels, + from: window.from, + to: window.to, + model: m.model, + ...(m.capUsd !== null ? { maxUsd: m.capUsd } : {}), + }, + deps.draft, + ); + if (!out.result.ok || !("iteration" in out)) { + const reason = (out.result as { error: string }).error; + return { status: isCapRefusal(reason) ? "held-by-cap" : "failed", usd: 0, reason, ...(m.capUsd !== null ? { estimateUsd: m.capUsd } : {}) }; + } + const result = out.result as Extract<StreamActionResult, { ok: true }>; + void result.stream.cancel(); + const n = out.iteration; + ctx.log(`sweep ${input.article} i${n} on ${m.model}: job ${result.jobId}`); + // A tick cancelled cancels its sweep. + const stop = () => getRegistry().cancel(result.jobId); + ctx.signal.addEventListener("abort", stop, { once: true }); + try { + await result.done; + } finally { + ctx.signal.removeEventListener("abort", stop); + } + const it = await readIteration(input.article, n, paths); + const usd = it ? iterationUsd(it) : 0; + 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. + const text = await readIterationFile(input.article, n, "report.json", paths).catch(() => null); + if (text) { + try { + const doc = JSON.parse(text) as Record<string, unknown>; + await writeIterationFile(input.article, n, "report.json", { ...doc, title: input.title }, paths); + } catch (e) { + ctx.log(`the report kept its own title: ${(e as Error).message}`); + } + } + } + return { + status, + iteration: n, + usd, + jobId: result.jobId, + ...(it?.error && status !== "done" ? { reason: it.error } : {}), + ...(matched !== undefined ? { matched } : {}), + }; + }; +} + +// ─── the tick ─── + +export type TickDeps = ScheduleDeps & { + paths: Paths; + steps: TickSteps; + // Default: lib/report/iterations makeCurrent. + makeCurrent?: (article: string, n: number) => Promise<unknown>; +}; + +/** Whether a living report has a report to refresh: a current one, or a done iteration carrying one. */ +export async function hasReportToRefresh(article: string, paths: Pick<Paths, "articlesDir" | "exportIndexDir">): Promise<boolean> { + const cur = await currentIteration(article, paths).catch(() => null); + if (cur?.report != null) return true; + for (const it of await listIterations(article, paths).catch(() => [])) { + if (it.status === "done" && (await readIterationFile(article, it.n, "report.json", paths).catch(() => null)) !== null) return true; + } + return false; +} + +const exists = (p: string) => stat(p).then(() => true, () => false); + +/** The window a series' next edition covers: from the last swept (or quiet) edition's window end, else the cadence's length back. */ +export function nextWindow(s: Schedule, today: string): { from: string; to: string } { + const covered = [...(s.editions ?? [])].reverse().find((e) => e.status === "done" || e.status === "quiet" || e.status === "running"); + let from = covered ? covered.window.to : addDays(today, -cadenceDays(s.cadence)); + if (!covered && s.scope.from && s.scope.from > from) from = s.scope.from; + if (from > today) from = today; + return { from, to: today }; +} + +/** The edition's article id: `<series>-<date>`, then -2, -3 … when the store has it. */ +async function editionArticle(s: Schedule, day: string, paths: Pick<Paths, "articlesDir">): Promise<string> { + const base = `${s.id}-${day}`; + const used = new Set((s.editions ?? []).map((e) => e.article).filter(Boolean)); + for (let k = 1; k < 100; k++) { + const id = k === 1 ? base : `${base}-${k}`; + if (!used.has(id) && !(await exists(path.join(paths.articlesDir, id)))) return id; + } + throw new Error(`no free edition id after ${base}`); +} + +export type TickRun = { trigger: "schedule" | "now"; scheduledFor?: string; missed?: number; jobId: string }; + +/** Run one tick of schedule `id` and record it. Answers the history line it wrote. */ +export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: StepCtx): Promise<Tick> { + const now = deps.now?.() ?? new Date(); + const t0 = Date.now(); + const s = await readSchedule(id, deps.paths); + if (!s) throw new Error(`no schedule "${id}"`); + const base = { + at: now.toISOString(), + trigger: run.trigger, + jobId: run.jobId, + ...(run.scheduledFor ? { scheduledFor: run.scheduledFor } : {}), + ...(run.missed ? { missed: run.missed } : {}), + }; + const finish = async (o: Partial<Tick> & { status: TickStatus; usd: number }): Promise<Tick> => { + const tick: Tick = { ...base, ...o, minutes: Math.round(((Date.now() - t0) / 60_000) * 100) / 100 }; + await recordTick(id, tick, deps); + ctx.log(`${REPORT_TICK_RESULT_MARKER}${JSON.stringify({ schedule: id, ...tick })}`); + return tick; + }; + const today = localDate(now.getTime(), s.tz); + let edition: Edition | null = null; + try { + ctx.log(`${s.shape} ${id}: ${run.trigger === "now" ? "ticked now" : `the ${run.scheduledFor} window`}${run.missed ? ` (stands in for ${run.missed} missed)` : ""}`); + const f = await deps.steps.fetchAndBuild({ channels: s.scope.channels }, ctx); + if (!f.ok) return await finish({ status: f.status, usd: 0, reason: f.reason }); + if (f.note) ctx.log(f.note); + if (ctx.signal.aborted) return await finish({ status: "cancelled", usd: 0, reason: "cancelled" }); + + if (s.shape === "living") { + const article = s.article ?? s.id; + let out: StepOutcome; + if (!(await hasReportToRefresh(article, deps.paths))) { + ctx.log(`${article} has no report yet: its first sweep`); + const back = addDays(today, -cadenceDays(s.cadence)); + out = await deps.steps.generateEdition( + { schedule: s, article, title: null, window: { from: s.scope.from ?? back, to: today }, quietCheck: false }, + ctx, + ); + } else { + out = await deps.steps.refresh(article, { ...(s.model ? { model: s.model } : {}), ...(s.caps?.maxUsd ? { maxUsd: s.caps.maxUsd } : {}) }, ctx); + } + let reason = out.reason; + if (out.status === "done" && out.iteration && s.autoMakeCurrent) { + try { + await (deps.makeCurrent ?? ((a: string, n: number) => makeCurrent(a, n, deps.paths)))(article, out.iteration); + ctx.log(`${article} i${out.iteration} made current (autoMakeCurrent)`); + } catch (e) { + reason = `made, not current: ${(e as Error).message}`; + } + } + return await finish({ + status: out.status, + usd: out.usd, + article, + ...(out.iteration ? { iteration: out.iteration } : {}), + ...(reason ? { reason } : {}), + ...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}), + }); + } + + if (s.shape !== "series") return await finish({ status: "failed", usd: 0, reason: `a ${s.shape} schedule has no tick yet (R6)` }); + const window = nextWindow(s, today); + const n = Math.max(0, ...(s.editions ?? []).map((e) => e.n)) + 1; + const article = await editionArticle(s, window.to, deps.paths); + const title = editionTitle(s.topic, s.cadence, window); + edition = { n, at: now.toISOString(), window, title, status: "running", article, usd: 0, jobId: run.jobId }; + await putEdition(id, edition, deps); + const out = await deps.steps.generateEdition({ schedule: s, article, title, window, quietCheck: true }, ctx); + const made = out.iteration !== undefined; + if (out.status === "quiet" || made) { + edition = { + n, + at: edition.at, + window, + title, + status: out.status === "no-change" ? "done" : out.status, + ...(out.status !== "quiet" ? { article, iteration: out.iteration } : {}), + usd: out.usd, + ...(out.jobId ? { jobId: out.jobId } : {}), + ...(out.reason ? { reason: out.reason } : {}), + ...(out.matched !== undefined ? { matched: out.matched } : {}), + }; + await putEdition(id, edition, deps); + } else { + // Nothing was made (held, refused): no edition — the next tick covers this window. + await dropEdition(id, n, deps); + } + return await finish({ + status: out.status, + usd: out.usd, + ...(out.status === "quiet" || made ? { edition: n } : {}), + ...(made ? { article, iteration: out.iteration } : {}), + ...(out.reason ? { reason: out.reason } : {}), + ...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}), + }); + } catch (e) { + const cancelled = ctx.signal.aborted; + if (edition?.status === "running") await dropEdition(id, edition.n, deps).catch(() => {}); + return finish({ status: cancelled ? "cancelled" : "failed", usd: 0, reason: cancelled ? "cancelled" : (e as Error).message }); + } +} + +// ─── the job ─── + +export type EnqueueTickResult = { ok: true; jobId: string } | { ok: false; error: string; running?: string }; + +/** + * Enqueue ONE `report-tick` job for schedule `id`: the claim first (refused + * when a tick of it is queued or running), then the job; a scheduled tick's + * claim moves `nextTick` on to `next`. + */ +export async function enqueueTick( + id: string, + o: { trigger: "schedule" | "now"; scheduledFor?: string; next?: string; missed?: number }, + deps: TickDeps, +): Promise<EnqueueTickResult> { + const pending = `${PENDING_PREFIX}${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; + const claimed = await claimTick(id, { jobId: pending, trigger: o.trigger, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}), ...(o.next ? { next: o.next } : {}) }, deps); + if (!claimed) { + const s = await readSchedule(id, deps.paths); + return { ok: false, error: `a tick of "${id}" is already queued or running (job ${s?.running?.jobId ?? "?"})`, ...(s?.running ? { running: s.running.jobId } : {}) }; + } + const result = await runManagedFunction({ + kind: REPORT_TICK_JOB_KIND, + queueKey: REPORT_TICK_QUEUE, + paths: deps.paths, + fn: async (onLog, signal, _setProgress, ctx) => { + // The claim names its job before anything runs. + await moveClaim(id, pending, ctx.jobId, deps).catch(() => {}); + const tick = await runTick(id, { trigger: o.trigger, jobId: ctx.jobId, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}), ...(o.missed ? { missed: o.missed } : {}) }, deps, { log: onLog, signal }); + if (tick.status === "cancelled") throw new Error("cancelled"); + if (tick.status === "failed" || tick.status === "interrupted") throw new Error(tick.reason ?? "the tick failed"); + }, + }); + if (!result.ok) { + await releaseClaim(id, pending, deps); + return { ok: false, error: result.error }; + } + void result.stream.cancel(); + await moveClaim(id, pending, result.jobId, deps).catch(() => {}); + // A job cancelled before it ran never ran runTick: record it and give the claim back. + void result.done.then(async (d) => { + const s = await readSchedule(id, deps.paths).catch(() => null); + if (s?.running?.jobId === result.jobId || s?.running?.jobId === pending) { + await recordTick( + id, + { + at: (deps.now?.() ?? new Date()).toISOString(), + trigger: o.trigger, + jobId: result.jobId, + status: d.status === "cancelled" ? "cancelled" : "interrupted", + usd: 0, + reason: `the job ended ${d.status} before the tick ran`, + ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}), + }, + deps, + ).catch(() => {}); + } + }); + return { ok: true, jobId: result.jobId }; +} diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -942,6 +942,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: false, queueKeyStrategy: "custom", }, + // A recurring report's tick (umtool R5, controller/reportTick.ts): ONE job + // per tick, on `report-tick` (one at a time machine-wide), enqueued by the + // editor's report-schedule lane or `report-schedule {"action":"tick-now"}`. + // It reads and writes the article store and waits on the jobs it asks for + // (R4's fetches and build, a `report-draft` sweep): never a channel's data + // itself, so neither guard. Not replayable: the schedule ticks again at its + // next window, or Tick now asks again. + "report-tick": { + kind: "report-tick", + label: "Report tick", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + }, // The verdict bench (release 28 M7): ruled fact-check claims asked of // models, one per call — `pnpm ops bench-verdicts`, on `draft:local` when // any model is local (the GPU arbiter's path) else `draft:api`. It reads diff --git a/common/lib/autoQueueTypes.ts b/common/lib/autoQueueTypes.ts @@ -216,6 +216,6 @@ export type AutoQueueKind = (typeof LANES)[number]; // tree per entry of LANES (channelPriority, channelWriters, the storage watch, // operationBatch, the channel snapshot, the auto-queue schema …). Its // settings are `settings.publish`, not an `autoQueue` policy. -export const PIPELINE_LANES = ["publish"] as const; +export const PIPELINE_LANES = ["publish", "report-schedule"] as const; export type PipelineLane = (typeof PIPELINE_LANES)[number]; diff --git a/common/lib/pauseGates.ts b/common/lib/pauseGates.ts @@ -50,6 +50,10 @@ import { // WIDENED BY ONE in release 18: the publish lane is a PIPELINE lane // (autoQueueTypes.ts PIPELINE_LANES), not a LANES entry, and its gate is // `settings.publish.held` — the one gate that is not on an `autoQueue` policy. +// +// AND BY ONE MORE in umtool R5: the recurring reports' lane, `report-schedule`, +// whose gate is `settings.reportSchedule.held` (controller/ +// reportScheduleRunner.ts reads it before it starts a tick). export type PauseLane = AutoQueueKind | PipelineLane; // WHICH LANE'S GATE HOLDS THIS OPERATION — the answer to "the operator is on @@ -102,6 +106,7 @@ export function isGateHeld(settings: SiteSettings, lane: PauseLane): boolean { // The publish lane's gate is its own block's (release 18): there is no // `autoQueue.publish`. if (lane === "publish") return settings.publish?.held === true; + if (lane === "report-schedule") return settings.reportSchedule?.held === true; return settings.autoQueue?.[lane]?.held === true; } @@ -125,6 +130,9 @@ export function withGateHeld( if (lane === "publish") { return { ...settings, publish: { ...settings.publish, held } }; } + if (lane === "report-schedule") { + return { ...settings, reportSchedule: { ...settings.reportSchedule, held } }; + } return { ...settings, autoQueue: { diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts @@ -48,6 +48,13 @@ export const REFRESH_REPORT_QUEUE = "refresh-report"; // takes every core and ~1 GB; two at once only thrash. export const TTS_QUEUE = "tts"; +// A recurring report's tick (umtool R5, controller/reportTick.ts): one at a +// time machine-wide. A tick mostly WAITS — on its fetches, a site build, the +// generation job it enqueues on `draft:api`/`draft:local` — so it must hold +// none of those lanes itself; and two schedules due at once tick in turn, not +// together (their sweeps would race the day's cap). +export const REPORT_TICK_QUEUE = "report-tick"; + // Per-channel queue for channel-local bookkeeping jobs (clean/clear/verify). export function channelQueueKey(slug: string): string { return `channel:${slug}`; diff --git a/common/lib/report/schedule/cadence.test.ts b/common/lib/report/schedule/cadence.test.ts @@ -0,0 +1,124 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + addDays, + anchorFor, + cadenceDays, + cadenceWords, + chipWords, + dueTick, + instantOf, + localDate, + nextTickAfter, + parseCadence, + wallOf, + type Cadence, +} from "./cadence"; + +const NY = "America/New_York"; +const iso = (t: number) => new Date(t).toISOString(); +const at = (s: string) => Date.parse(s); + +test("parseCadence: objects and phrases; what to fix when wrong", () => { + assert.deepEqual(parseCadence({ kind: "daily", at: "6:00" }), { kind: "daily", at: "06:00" }); + assert.deepEqual(parseCadence("weekly mon 06:00"), { kind: "weekly", dow: 1, at: "06:00" }); + assert.deepEqual(parseCadence("weekly Monday"), { kind: "weekly", dow: 1, at: "06:00" }); + assert.deepEqual(parseCadence("every 3 days 21:30"), { kind: "every", days: 3, at: "21:30" }); + assert.deepEqual(parseCadence({ kind: "weekly", dow: "fri", at: "07:15" }), { kind: "weekly", dow: 5, at: "07:15" }); + assert.throws(() => parseCadence({ kind: "every", days: 1, at: "06:00" }), /2 to 365/); + assert.throws(() => parseCadence({ kind: "daily", at: "25:00" }), /HH:MM/); + assert.throws(() => parseCadence("monthly"), /a cadence is/); + assert.throws(() => parseCadence({ kind: "weekly", dow: 9 }), /day of the week/); + assert.equal(cadenceDays({ kind: "weekly", dow: 1, at: "06:00" }), 7); + assert.equal(cadenceDays({ kind: "every", days: 3, at: "06:00" }), 3); +}); + +test("daily: the next HH:MM after an instant, on the local clock", () => { + const c: Cadence = { kind: "daily", at: "06:00" }; + // 2026-10-14 05:00 New York (EDT, UTC-4) → 06:00 the same day. + assert.equal(iso(nextTickAfter(c, at("2026-10-14T09:00:00Z"), NY)), "2026-10-14T10:00:00.000Z"); + // Exactly at the tick: strictly after, so tomorrow. + assert.equal(iso(nextTickAfter(c, at("2026-10-14T10:00:00Z"), NY)), "2026-10-15T10:00:00.000Z"); +}); + +test("DST: a fall-back keeps the wall time (and the first 01:30); a spring-forward skips the gap, never the day", () => { + const six: Cadence = { kind: "daily", at: "06:00" }; + // New York falls back on 2026-11-01: 06:00 EDT (10:00Z) on Oct 31, 06:00 EST (11:00Z) on Nov 1. + const a = nextTickAfter(six, at("2026-10-31T12:00:00Z"), NY); + assert.equal(iso(a), "2026-11-01T11:00:00.000Z"); + assert.equal(wallOf(a, NY).hh, 6); + // 01:30 happens twice on Nov 1: the first (EDT, 05:30Z). + assert.equal(iso(instantOf({ y: 2026, m: 11, d: 1, hh: 1, mm: 30 }, NY)), "2026-11-01T05:30:00.000Z"); + // Springs forward on 2026-03-08: 02:30 does not exist; the tick is 03:30 EDT (07:30Z), that day. + const half: Cadence = { kind: "daily", at: "02:30" }; + const b = nextTickAfter(half, at("2026-03-08T00:00:00Z"), NY); + assert.equal(iso(b), "2026-03-08T07:30:00.000Z"); + assert.equal(localDate(b, NY), "2026-03-08"); + // And the day after is 02:30 again. + assert.equal(iso(nextTickAfter(half, b, NY)), "2026-03-09T06:30:00.000Z"); + // Europe changes on its own Sunday. + const ldn = nextTickAfter(six, at("2026-03-29T00:00:00Z"), "Europe/London"); + assert.equal(iso(ldn), "2026-03-29T05:00:00.000Z"); +}); + +test("weekly on a day: that weekday's HH:MM, never another", () => { + const mon: Cadence = { kind: "weekly", dow: 1, at: "06:00" }; + // Wed 2026-10-14 → Mon 2026-10-19. + const t = nextTickAfter(mon, at("2026-10-14T12:00:00Z"), NY); + assert.equal(localDate(t, NY), "2026-10-19"); + assert.equal(iso(t), "2026-10-19T10:00:00.000Z"); + // From Monday 05:59 local: the same day. + assert.equal(localDate(nextTickAfter(mon, at("2026-10-19T09:59:00Z"), NY), NY), "2026-10-19"); + // From Monday 06:00 local: next week. + assert.equal(localDate(nextTickAfter(mon, at("2026-10-19T10:00:00Z"), NY), NY), "2026-10-26"); +}); + +test("every N days: anchored to the first tick's date, whatever the instant asked from", () => { + const c: Cadence = { kind: "every", days: 3, at: "06:00" }; + const first = nextTickAfter(c, at("2026-10-14T12:00:00Z"), NY); + assert.equal(localDate(first, NY), "2026-10-15"); + const anchor = anchorFor(c, first, NY); + assert.equal(anchor, "2026-10-15"); + assert.equal(localDate(nextTickAfter(c, first, NY, anchor), NY), "2026-10-18"); + // From any day in between, the next on the anchor's grid. + assert.equal(localDate(nextTickAfter(c, at("2026-10-19T12:00:00Z"), NY, anchor), NY), "2026-10-21"); + assert.equal(localDate(nextTickAfter(c, at("2026-10-21T09:00:00Z"), NY, anchor), NY), "2026-10-21"); + // Across the fall-back, still 06:00 local. + const after = nextTickAfter(c, at("2026-10-30T12:00:00Z"), NY, anchor); + assert.equal(localDate(after, NY), "2026-11-02"); + assert.equal(wallOf(after, NY).hh, 6); + assert.equal(anchorFor({ kind: "daily", at: "06:00" }, first, NY), null); +}); + +test("a missed window is ONE catch-up tick, never N", () => { + const c: Cadence = { kind: "daily", at: "06:00" }; + const s = { cadence: c, tz: NY, nextTick: "2026-10-10T10:00:00.000Z" }; + // Down from the 10th; back on the 14th at 08:00 local (12:00Z): four windows passed. + const now = at("2026-10-14T12:00:00Z"); + const d = dueTick(s, now); + assert.equal(d.due, true); + if (!d.due) return; + assert.equal(iso(d.scheduledFor), "2026-10-10T10:00:00.000Z"); + assert.equal(d.missed, 4); + assert.equal(iso(d.next), "2026-10-15T10:00:00.000Z"); + // The schedule moved on: nothing else is due now. + assert.deepEqual(dueTick({ ...s, nextTick: iso(d.next) }, now), { due: false }); + // Not yet, or paused, or never. + assert.deepEqual(dueTick(s, at("2026-10-10T09:59:59Z")), { due: false }); + assert.deepEqual(dueTick({ ...s, paused: true }, now), { due: false }); + assert.deepEqual(dueTick({ ...s, nextTick: null }, now), { due: false }); + // On time: due, nothing missed. + const onTime = dueTick(s, at("2026-10-10T10:00:30Z")); + assert.equal(onTime.due && onTime.missed, 0); +}); + +test("words: the cadence, the chip", () => { + assert.equal(cadenceWords({ kind: "weekly", dow: 1, at: "06:00" }), "weekly · Mon 06:00"); + assert.equal(cadenceWords({ kind: "every", days: 3, at: "06:00" }), "every 3 days 06:00"); + const s = { cadence: { kind: "weekly", dow: 1, at: "06:00" } as Cadence, tz: NY, nextTick: "2026-10-19T10:00:00.000Z" }; + assert.equal(chipWords(s, at("2026-10-14T12:00:00Z")), "weekly · next Mon 06:00"); + assert.equal(chipWords({ ...s, paused: true }), "weekly · paused"); + assert.equal(chipWords({ ...s, cadence: { kind: "daily", at: "06:00" } }, at("2026-10-01T12:00:00Z")), "daily · next 2026-10-19 06:00"); + assert.equal(addDays("2026-03-01", -1), "2026-02-28"); + assert.equal(addDays("2026-12-31", 7), "2027-01-07"); +}); diff --git a/common/lib/report/schedule/cadence.ts b/common/lib/report/schedule/cadence.ts @@ -0,0 +1,301 @@ +// A RECURRING REPORT'S CADENCE (umtool R5; plans/umtool-redesign.md "R5 — +// Recurring reports"): when a schedule ticks, as pure maths on the local +// clock of a named time zone. No disk, no Date.now(): every function takes +// the instant it reasons about, so the editor's runner, the ops action's plan +// and umtool's chip agree and the tests can stand on a DST change. +// +// daily every day at HH:MM +// weekly <dow> every <dow> (0 = Sunday … 6 = Saturday) at HH:MM +// every N days every N days at HH:MM, counted from the ANCHOR — the +// local date of the schedule's first tick (2 ≤ N ≤ 365) +// +// THE LOCAL CLOCK. "06:00" is wall-clock time in the schedule's `tz` (the +// editor's zone when it was made). A wall time a spring-forward skips +// (02:30 on the day clocks jump 02:00 → 03:00) ticks at the same distance +// past the gap (03:30); a time a fall-back repeats (01:30 twice) ticks at its +// FIRST occurrence. Never twice, never not at all. +// +// A MISSED WINDOW IS ONE CATCH-UP TICK, NEVER N. An editor down over three +// daily windows ticks ONCE when it comes back (`dueTick`), and the next tick +// is the next window after now — the three it missed are counted, not run. +// +// Pure: safe for a client component. + +export const CADENCE_KINDS = ["daily", "weekly", "every"] as const; +export type CadenceKind = (typeof CADENCE_KINDS)[number]; + +export type Cadence = + | { kind: "daily"; at: string } + | { kind: "weekly"; dow: number; at: string } + | { kind: "every"; days: number; at: string }; + +export const DOW_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const; +const DOW_LONG = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; + +export const EVERY_MIN_DAYS = 2; +export const EVERY_MAX_DAYS = 365; + +const HHMM = /^([01]\d|2[0-3]):([0-5]\d)$/; +const YMD = /^(\d{4})-(\d{2})-(\d{2})$/; +const DAY_MS = 86_400_000; + +export class CadenceError extends Error {} + +/** The editor's (this process's) IANA zone. */ +export function localTimeZone(): string { + try { + return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + } catch { + return "UTC"; + } +} + +/** Whether `tz` is a zone this runtime knows. */ +export function isTimeZone(tz: unknown): tz is string { + if (typeof tz !== "string" || !tz) return false; + try { + new Intl.DateTimeFormat("en-US", { timeZone: tz }); + return true; + } catch { + return false; + } +} + +// ─── parsing ─── + +function normAt(v: unknown): string { + if (typeof v !== "string") throw new CadenceError('"at" is a time of day, HH:MM (24-hour)'); + const s = v.trim(); + const m = /^(\d{1,2}):(\d{2})$/.exec(s); + const t = m ? `${m[1].padStart(2, "0")}:${m[2]}` : s; + if (!HHMM.test(t)) throw new CadenceError(`"at" is a time of day, HH:MM (24-hour): not ${JSON.stringify(v)}`); + return t; +} + +function normDow(v: unknown): number { + if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 6) return v; + if (typeof v === "string") { + const s = v.trim().toLowerCase(); + if (/^[0-6]$/.test(s)) return Number(s); + const i = DOW_LONG.findIndex((d) => s.length >= 3 && d.startsWith(s)); + if (i >= 0) return i; + } + throw new CadenceError(`"dow" is a day of the week (0 = Sunday … 6 = Saturday, or its name): not ${JSON.stringify(v)}`); +} + +/** + * A cadence from an object (`{kind, at, dow?, days?}`) or a phrase: + * "daily 06:00", "weekly mon 06:00", "every 3 days 06:00" (the time defaults + * to 06:00 when a phrase leaves it out). Throws CadenceError, saying what to fix. + */ +export function parseCadence(input: unknown): Cadence { + if (typeof input === "string") { + const words = input.trim().toLowerCase().split(/\s+/).filter(Boolean); + const at = words.find((w) => /^\d{1,2}:\d{2}$/.test(w)) ?? "06:00"; + const rest = words.filter((w) => w !== at && w !== "at" && w !== "on"); + if (rest[0] === "daily" || (rest[0] === "every" && rest[1] === "day")) return { kind: "daily", at: normAt(at) }; + if (rest[0] === "weekly") return { kind: "weekly", dow: normDow(rest[1]), at: normAt(at) }; + if (rest[0] === "every" && rest[1] && /^\d+$/.test(rest[1])) return parseCadence({ kind: "every", days: Number(rest[1]), at }); + throw new CadenceError(`a cadence is "daily HH:MM", "weekly <day> HH:MM" or "every N days HH:MM": not ${JSON.stringify(input)}`); + } + if (!input || typeof input !== "object" || Array.isArray(input)) { + throw new CadenceError('"cadence" is {kind: "daily" | "weekly" | "every", at: "HH:MM", dow?, days?} or a phrase like "weekly mon 06:00"'); + } + const r = input as Record<string, unknown>; + const at = normAt(r.at ?? "06:00"); + if (r.kind === "daily") return { kind: "daily", at }; + if (r.kind === "weekly") return { kind: "weekly", dow: normDow(r.dow), at }; + if (r.kind === "every") { + const days = typeof r.days === "string" ? Number(r.days) : r.days; + if (typeof days !== "number" || !Number.isInteger(days) || days < EVERY_MIN_DAYS || days > EVERY_MAX_DAYS) { + throw new CadenceError(`"days" is a whole number of days, ${EVERY_MIN_DAYS} to ${EVERY_MAX_DAYS} (every day is "daily")`); + } + return { kind: "every", days, at }; + } + throw new CadenceError(`"kind" is one of ${CADENCE_KINDS.join(", ")}`); +} + +/** The cadence's length in days: what one window covers. */ +export function cadenceDays(c: Cadence): number { + return c.kind === "daily" ? 1 : c.kind === "weekly" ? 7 : c.days; +} + +// ─── the local clock ─── + +export type CivilDate = { y: number; m: number; d: number }; +type Wall = CivilDate & { hh: number; mm: number }; + +const fmtCache = new Map<string, Intl.DateTimeFormat>(); +function fmt(tz: string): Intl.DateTimeFormat { + let f = fmtCache.get(tz); + if (!f) { + f = new Intl.DateTimeFormat("en-US", { + timeZone: tz, + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + fmtCache.set(tz, f); + } + return f; +} + +/** The wall clock in `tz` at instant `t` (ms). */ +export function wallOf(t: number, tz: string): Wall & { ss: number } { + const parts = fmt(tz).formatToParts(new Date(t)); + const n = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? 0); + return { y: n("year"), m: n("month"), d: n("day"), hh: n("hour") % 24, mm: n("minute"), ss: n("second") }; +} + +// The zone's offset from UTC at instant t, in ms (local = utc + offset). +function offsetAt(t: number, tz: string): number { + const w = wallOf(t, tz); + const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.hh, w.mm, w.ss); + return asUtc - Math.floor(t / 1000) * 1000; +} + +/** + * The instant whose wall clock in `tz` is `w` — the first of two in a + * fall-back, the same distance past the gap in a spring-forward. + */ +export function instantOf(w: Wall, tz: string): number { + const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.hh, w.mm); + const before = asUtc - offsetAt(asUtc - DAY_MS, tz); + const after = asUtc - offsetAt(asUtc + DAY_MS, tz); + const ok = (t: number) => { + const x = wallOf(t, tz); + return x.y === w.y && x.m === w.m && x.d === w.d && x.hh === w.hh && x.mm === w.mm; + }; + const hits = [before, after].filter(ok); + if (hits.length) return Math.min(...hits); + // In the gap: the offset before it carries the wall time past it. + return before; +} + +/** Days since 1970-01-01 of a civil date. */ +const dayNumber = (c: CivilDate) => Math.round(Date.UTC(c.y, c.m - 1, c.d) / DAY_MS); +const civilOf = (n: number): CivilDate => { + const dt = new Date(n * DAY_MS); + return { y: dt.getUTCFullYear(), m: dt.getUTCMonth() + 1, d: dt.getUTCDate() }; +}; +const dowOf = (c: CivilDate) => new Date(Date.UTC(c.y, c.m - 1, c.d)).getUTCDay(); + +export const ymdOf = (c: CivilDate) => `${String(c.y).padStart(4, "0")}-${String(c.m).padStart(2, "0")}-${String(c.d).padStart(2, "0")}`; +export function parseYmd(s: string): CivilDate { + const m = YMD.exec(s); + if (!m) throw new CadenceError(`not a YYYY-MM-DD date: ${JSON.stringify(s)}`); + return { y: Number(m[1]), m: Number(m[2]), d: Number(m[3]) }; +} + +/** The local date (YYYY-MM-DD) in `tz` at instant t. */ +export function localDate(t: number, tz: string): string { + return ymdOf(wallOf(t, tz)); +} + +/** `ymd` moved by `days` (negative: back). */ +export function addDays(ymd: string, days: number): string { + return ymdOf(civilOf(dayNumber(parseYmd(ymd)) + days)); +} + +const atOf = (c: Cadence) => { + const [hh, mm] = c.at.split(":").map(Number); + return { hh, mm }; +}; + +// ─── the windows ─── + +/** + * The first tick strictly after `after` (ms). `anchor` (YYYY-MM-DD) is an + * every-N-days schedule's first tick's local date; without one the series + * starts at the next HH:MM, as a daily one would. + */ +export function nextTickAfter(c: Cadence, after: number, tz: string, anchor?: string | null): number { + const { hh, mm } = atOf(c); + const today = dayNumber(wallOf(after, tz)); + const at = (day: number) => instantOf({ ...civilOf(day), hh, mm }, tz); + if (c.kind === "daily" || (c.kind === "every" && !anchor)) { + for (let k = 0; k < 3; k++) { + const t = at(today + k); + if (t > after) return t; + } + } else if (c.kind === "weekly") { + for (let k = 0; k < 9; k++) { + const day = today + k; + if (dowOf(civilOf(day)) !== c.dow) continue; + const t = at(day); + if (t > after) return t; + } + } else { + const a = dayNumber(parseYmd(anchor!)); + const first = Math.max(0, Math.floor((today - a) / c.days)); + for (let k = first; k < first + 3; k++) { + const t = at(a + k * c.days); + if (t > after) return t; + } + } + // Unreachable for a valid cadence; never a tick in the past. + throw new CadenceError("no next tick: the cadence is not valid"); +} + +/** The anchor an every-N-days schedule takes from its first tick (its local date); null for the others. */ +export function anchorFor(c: Cadence, firstTick: number, tz: string): string | null { + return c.kind === "every" ? localDate(firstTick, tz) : null; +} + +/** + * Is a tick due at `now`? `nextTick` is the window the schedule waits for. + * Due: ONE tick, for that window, however many have passed since (`missed` + * counts the later ones it stands in for), and the window after it is the + * first one after now — never a queue of catch-ups. + */ +export function dueTick( + s: { cadence: Cadence; tz: string; anchor?: string | null; nextTick: string | null; paused?: boolean }, + now: number, +): { due: false } | { due: true; scheduledFor: number; missed: number; next: number } { + if (s.paused || !s.nextTick) return { due: false }; + const scheduledFor = Date.parse(s.nextTick); + if (!Number.isFinite(scheduledFor) || scheduledFor > now) return { due: false }; + let missed = 0; + let t = scheduledFor; + // Count the windows passed since (bounded: a schedule asleep for years is + // not a loop of thousands). + for (; missed < 1000; missed++) { + t = nextTickAfter(s.cadence, t, s.tz, s.anchor); + if (t > now) break; + } + return { due: true, scheduledFor, missed, next: t }; +} + +// ─── words ─── + +/** "daily 06:00", "weekly · Mon 06:00", "every 3 days 06:00". */ +export function cadenceWords(c: Cadence): string { + if (c.kind === "daily") return `daily ${c.at}`; + if (c.kind === "weekly") return `weekly · ${DOW_NAMES[c.dow]} ${c.at}`; + 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. */ +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}`; + return `${day} ${time}`; +} + +/** The chip: "weekly · next Mon 06:00", "daily · paused". */ +export function chipWords( + s: { cadence: Cadence; tz: string; nextTick: string | null; paused?: boolean }, + now?: number, +): string { + const kind = s.cadence.kind === "every" ? `every ${s.cadence.days} days` : s.cadence.kind; + if (s.paused) return `${kind} · paused`; + const next = s.nextTick ? Date.parse(s.nextTick) : NaN; + if (!Number.isFinite(next)) return kind; + return `${kind} · next ${tickWords(next, s.tz, now)}`; +} diff --git a/common/lib/report/schedule/store.ts b/common/lib/report/schedule/store.ts @@ -0,0 +1,111 @@ +// WHERE A RECURRING REPORT'S SCHEDULE LIVES, AND ITS READS (umtool R5). +// +// living transcripts/reports/<article>/schedule.json — beside the article +// it keeps current: it goes where the article goes (a delete parks +// the whole directory), and nothing that reads an article reads it +// (compose copies named files, the site history commits +// report.json, report.md and exports.json). A living report made +// for a NEW article creates `<article>/iterations/` with it, so +// the article is "in the making" (registry.ts listPendingArticles) +// from the start — never a directory the registry would list as an +// article with no report.json. +// series transcripts/reports/.series/<id>/series.json — the schedule and +// its editions listed in it. A dot-directory: the registry lists +// only id-named directories (registry.ts idDirs), so a series is +// never read as an article. Each edition is an ordinary article in +// the store (`<series>-<date>`), the edition list naming it. +// +// The ids share one namespace: a series may not take a living schedule's id +// (its article's) and a living schedule may not take a series'. +// +// Written ONLY by controller/reportSchedule.ts, under the article store's +// lock (registry.ts withArticleStoreLock), atomically. Reads are lock-free: +// a write replaces the file whole. +// +// SERVER-ONLY (node:fs). + +import { readdir } from "node:fs/promises"; +import path from "node:path"; +import type { Paths } from "../../paths"; +import { readJsonFile } from "../../jsonFile-server"; +import { isReportId } from "../schema"; +import { parseSchedule, SCHEDULE_ID_RE, type Schedule, type ScheduleShape } from "./types"; + +export type SchedulePaths = Pick<Paths, "articlesDir">; + +export const SERIES_DIRNAME = ".series"; +export const SERIES_FILENAME = "series.json"; +export const LIVING_FILENAME = "schedule.json"; + +export const seriesDir = (paths: SchedulePaths, id: string) => path.join(paths.articlesDir, SERIES_DIRNAME, id); +export const seriesFile = (paths: SchedulePaths, id: string) => path.join(seriesDir(paths, id), SERIES_FILENAME); +export const livingFile = (paths: SchedulePaths, article: string) => path.join(paths.articlesDir, article, LIVING_FILENAME); +export const scheduleFile = (paths: SchedulePaths, shape: ScheduleShape, id: string) => + shape === "living" ? livingFile(paths, id) : seriesFile(paths, id); + +export type ScheduleRead = { ok: true; schedule: Schedule; file: string } | { ok: false; id: string; file: string; problem: string }; + +async function readAt(file: string, id: string): Promise<ScheduleRead | null> { + const r = await readJsonFile(file); + if (!r.ok) return r.reason === "absent" ? null : { ok: false, id, file, problem: `${path.basename(file)} is ${r.reason}` }; + const p = parseSchedule(r.value); + if (!p.ok) return { ok: false, id, file, problem: p.problems.join("; ") }; + if (p.value.id !== id) return { ok: false, id, file, problem: `it names "${p.value.id}", not "${id}"` }; + return { ok: true, schedule: p.value, file }; +} + +/** One schedule by id (a series first, then a living report's), or null. A file that does not read is a read with its problem. */ +export async function readScheduleById(id: string, paths: SchedulePaths): Promise<ScheduleRead | null> { + if (!SCHEDULE_ID_RE.test(id) && !isReportId(id)) return null; + return (await readAt(seriesFile(paths, id), id)) ?? (isReportId(id) ? await readAt(livingFile(paths, id), id) : null); +} + +/** One schedule, or null (an unreadable one is null too). */ +export async function readSchedule(id: string, paths: SchedulePaths): Promise<Schedule | null> { + const r = await readScheduleById(id, paths); + return r?.ok ? r.schedule : null; +} + +/** A living report's schedule, by its article. */ +export async function readLivingSchedule(article: string, paths: SchedulePaths): Promise<Schedule | null> { + if (!isReportId(article)) return null; + const r = await readAt(livingFile(paths, article), article); + return r?.ok ? r.schedule : null; +} + +async function dirNames(dir: string): Promise<string[]> { + try { + return (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); + } catch { + return []; + } +} + +/** Every schedule — the series, then the living reports — and the files that do not read. Sorted by id within each. */ +export async function listScheduleReads(paths: SchedulePaths): Promise<ScheduleRead[]> { + const out: ScheduleRead[] = []; + for (const id of (await dirNames(path.join(paths.articlesDir, SERIES_DIRNAME))).filter((n) => SCHEDULE_ID_RE.test(n)).sort()) { + const r = await readAt(seriesFile(paths, id), id); + if (r) out.push(r); + } + for (const id of (await dirNames(paths.articlesDir)).filter(isReportId).sort()) { + const r = await readAt(livingFile(paths, id), id); + if (r) out.push(r); + } + return out; +} + +/** Every schedule that reads. */ +export async function listSchedules(paths: SchedulePaths): Promise<Schedule[]> { + return (await listScheduleReads(paths)).flatMap((r) => (r.ok ? [r.schedule] : [])); +} + +/** Article id → the series it is an edition of (every series' editions). */ +export async function editionIndex(paths: SchedulePaths): Promise<Map<string, { series: string; n: number }>> { + const out = new Map<string, { series: string; n: number }>(); + for (const s of await listSchedules(paths)) { + if (s.shape !== "series") continue; + for (const e of s.editions ?? []) if (e.article) out.set(e.article, { series: s.id, n: e.n }); + } + return out; +} diff --git a/common/lib/report/schedule/types.ts b/common/lib/report/schedule/types.ts @@ -0,0 +1,181 @@ +// A RECURRING REPORT'S SCHEDULE — its shape (umtool R5; plans/umtool-redesign.md +// "R5 — Recurring reports"). Pure: the types, the schema, the words, and what +// a reader (umtool's chip, the series page, the Inbox) derives from a +// schedule. The store is ./store.ts (reads) and controller/reportSchedule.ts +// (the ONE writer); the editor's runner (controller/reportScheduleRunner.ts) +// ticks it. +// +// living one article kept current: each tick re-fetches what the scope +// holds and runs R4's Refresh over the article (its first tick, +// with no report yet, is the article's first sweep); the new +// iteration is left ready for review, or made current when +// `autoMakeCurrent` says so +// series a new dated EDITION each tick — a new article over the window +// since the last edition's window end — titled +// "<topic> · week of <date>" (weekly) or "<topic> · <date>"; a +// window nothing in scope matches is a QUIET edition: recorded, +// no article, $0 +// watch RESERVED for R6 (triage first: no article until something is +// found). Not offered, refused by create. +// +// Safe for a client component: zod and ./cadence only. + +import { z } from "zod"; +import { chipWords, parseCadence, type Cadence } from "./cadence"; + +export const SCHEDULE_FORMAT = "archilyzer-schedule"; +export const SCHEDULE_VERSION = 1; + +export const SCHEDULE_SHAPES = ["living", "series", "watch"] as const; +export type ScheduleShape = (typeof SCHEDULE_SHAPES)[number]; +// The shapes create offers (R6 adds "watch"). +export const OFFERED_SHAPES: readonly ScheduleShape[] = ["living", "series"]; + +export const TICK_STATUSES = ["done", "no-change", "quiet", "held-by-cap", "failed", "cancelled", "interrupted"] as const; +export type TickStatus = (typeof TICK_STATUSES)[number]; +// The outcomes that are the operator's call (a Your call card). +export const CALL_STATUSES: readonly TickStatus[] = ["failed", "held-by-cap", "interrupted"]; + +export const EDITION_STATUSES = ["running", "done", "quiet", "failed", "cancelled", "held-by-cap"] as const; +export type EditionStatus = (typeof EDITION_STATUSES)[number]; + +// The history a schedule keeps: the newest ticks, the oldest dropped. +export const TICKS_KEPT = 100; + +const isoTime = z.string().refine((s) => Number.isFinite(Date.parse(s)), "is not an ISO 8601 time"); +const ymd = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "is not a YYYY-MM-DD date"); +// A series' id: room left for an edition's "-YYYY-MM-DD-n" in a 64-character +// article id. A living report's id is its article's (any article id). +export const SCHEDULE_ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/; +const ANY_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; +const channelSlug = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "is not a channel slug"); + +const cadenceSchema = z.unknown().transform((v, ctx): Cadence => { + try { + return parseCadence(v); + } catch (e) { + ctx.addIssue({ code: "custom", message: (e as Error).message }); + return z.NEVER; + } +}); + +export const scheduleScopeSchema = z.looseObject({ + channels: z.array(channelSlug).min(1), + // The research board (R2 case) the scope came from, when it did. + case: z.string().min(1).optional(), + // The first window starts no earlier than this. + from: ymd.optional(), + // A series' window check: what an edition's window must match to be worth a + // sweep (enumerate_matches' query). Absent: any recording in the window. + terms: z.string().min(1).optional(), + regex: z.boolean().optional(), +}); +export type ScheduleScope = z.infer<typeof scheduleScopeSchema>; + +export const tickSchema = z.looseObject({ + at: isoTime, + // The window it ticked for (absent: Tick now). + scheduledFor: isoTime.optional(), + trigger: z.enum(["schedule", "now"]), + status: z.enum(TICK_STATUSES), + jobId: z.string().optional(), + // Living: the iteration the tick made (or refreshed into). + iteration: z.number().int().positive().optional(), + // Series: the edition's number. + edition: z.number().int().positive().optional(), + article: z.string().optional(), + usd: z.number().nonnegative(), + // Why it ended so (one line), and what a held tick would have cost. + reason: z.string().optional(), + estimateUsd: z.number().nonnegative().optional(), + // Windows passed while the editor was away, that this one tick stood in for. + missed: z.number().int().nonnegative().optional(), + minutes: z.number().nonnegative().optional(), +}); +export type Tick = z.infer<typeof tickSchema>; + +export const editionSchema = z.looseObject({ + n: z.number().int().positive(), + at: isoTime, + window: z.looseObject({ from: ymd, to: ymd }), + title: z.string().min(1), + status: z.enum(EDITION_STATUSES), + // The edition's article in the store (absent: a quiet one). + article: z.string().optional(), + iteration: z.number().int().positive().optional(), + usd: z.number().nonnegative(), + jobId: z.string().optional(), + reason: z.string().optional(), + // How many recordings the window held for the terms (the quiet check). + matched: z.number().int().nonnegative().optional(), +}); +export type Edition = z.infer<typeof editionSchema>; + +export const scheduleSchema = z.looseObject({ + format: z.literal(SCHEDULE_FORMAT), + version: z.literal(SCHEDULE_VERSION), + id: z.string().regex(ANY_ID_RE), + shape: z.enum(SCHEDULE_SHAPES), + // The topic: a series' edition titles start with it; a living report's name. + topic: z.string().min(1), + // What a sweep asks. + question: z.string().min(1), + // Living: the article kept current. + article: z.string().optional(), + scope: scheduleScopeSchema, + cadence: cadenceSchema, + // The local clock the cadence is on (the editor's zone when it was made). + tz: z.string().min(1), + // An every-N-days schedule's grid: its first tick's local date. + anchor: ymd.nullable().optional(), + paused: z.boolean(), + // Living: make each refreshed iteration current with no review (default off). + autoMakeCurrent: z.boolean().optional(), + // The model a tick's generation runs on (default: the policy's route). + model: z.string().min(1).optional(), + // A tick's per-job cap (USD; never above the policy's max). Default: the + // policy's sweep cap. + caps: z.looseObject({ maxUsd: z.number().positive().optional() }).optional(), + createdAt: isoTime, + updatedAt: isoTime, + lastTick: isoTime.nullable(), + nextTick: isoTime.nullable(), + // A tick queued or running (its job): never two of one schedule at once. + running: z.looseObject({ jobId: z.string().min(1), at: isoTime, trigger: z.enum(["schedule", "now"]), scheduledFor: isoTime.optional() }).nullable(), + ticks: z.array(tickSchema), + // Series: every edition, oldest first. + editions: z.array(editionSchema).optional(), +}); +export type Schedule = z.infer<typeof scheduleSchema>; + +export function parseSchedule(raw: unknown): { ok: true; value: Schedule } | { ok: false; problems: string[] } { + const r = scheduleSchema.safeParse(raw); + if (r.success) return { ok: true, value: r.data }; + return { ok: false, problems: r.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`) }; +} + +// ─── what a reader derives ─── + +/** The cadence chip: "weekly · next Mon 06:00", "daily · paused". */ +export const scheduleChip = (s: Pick<Schedule, "cadence" | "tz" | "nextTick" | "paused">, now?: number) => chipWords(s, now); + +/** The newest tick, or null. */ +export const lastTickOf = (s: Pick<Schedule, "ticks">): Tick | null => s.ticks[s.ticks.length - 1] ?? null; + +/** The tick that is the operator's call now: the newest, when it failed or was held, and nothing has ticked since. */ +export function callOf(s: Pick<Schedule, "ticks" | "running">): Tick | null { + if (s.running) return null; + const t = lastTickOf(s); + return t && CALL_STATUSES.includes(t.status) ? t : null; +} + +/** Editions newest first. */ +export const editionsNewestFirst = (s: Pick<Schedule, "editions">): Edition[] => [...(s.editions ?? [])].sort((a, b) => b.n - a.n); + +/** What the schedule's ticks spent, in USD. */ +export const spentOf = (s: Pick<Schedule, "ticks">): number => Math.round(s.ticks.reduce((n, t) => n + t.usd, 0) * 10_000) / 10_000; + +/** "Co-host updates · week of 2026-10-13" (weekly) or "Co-host updates · 2026-10-14". */ +export function editionTitle(topic: string, cadence: Cadence, window: { from: string; to: string }): string { + return cadence.kind === "weekly" ? `${topic} · week of ${window.from}` : `${topic} · ${window.to}`; +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -19,6 +19,7 @@ import { DIARIZATION_SETTINGS_FIELD_DOCS, PACING_SETTINGS_FIELD_DOCS, PUBLISH_SETTINGS_FIELD_DOCS, + REPORT_SCHEDULE_SETTINGS_FIELD_DOCS, DIGEST_SETTINGS_FIELD_DOCS, SAVED_VIDEO_BACKUP_SETTINGS_FIELD_DOCS, SEEDER_SETTINGS_FIELD_DOCS, @@ -264,6 +265,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.publish), }, ], + reportSchedule: [ + { + path: "reportSchedule", + docs: REPORT_SCHEDULE_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.reportSchedule), + }, + ], seeder: [ { path: "seeder", diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -41,6 +41,7 @@ import type { DigestSettings, PacingSettingsBlock, PublishSettings, + ReportScheduleSettings, ReportDebouncePreset, SavedVideoBackupSettings, SocialLink, @@ -106,6 +107,8 @@ type PreSchemaSiteSettings = { archiveOrg: ArchiveOrgFetchSettings; // The publish lane (release 18). publish: PublishSettings; + // The recurring reports' lane (umtool R5). + reportSchedule: ReportScheduleSettings; // The home seeder of last resort (release 21 D4b). seeder: SeederSettings; // Local text-to-speech (release 25 T1). @@ -118,7 +121,7 @@ type PreSchemaSiteSettings = { type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 39 fields, in file order", () => { +test("SiteSettings keeps its 40 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -157,6 +160,7 @@ test("SiteSettings keeps its 39 fields, in file order", () => { "attribution", "archiveOrg", "publish", + "reportSchedule", "seeder", "tts", "generation", diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -1694,6 +1694,23 @@ export function sanitizePublish(value: unknown): PublishSettings { }; } +// --- The report-schedule lane (umtool R5) ----------------------------------- + +// The editor's recurring reports (controller/reportScheduleRunner.ts): its +// one key is the lane's pause gate. Each schedule's own pause is in its file +// (lib/report/schedule/store.ts), not here. +export type ReportScheduleSettings = { held: boolean }; + +export const REPORT_SCHEDULE_SETTINGS_FIELD_DOCS: FieldDocs<ReportScheduleSettings> = { + held: + "The lane's pause gate (lib/pauseGates.ts, lane `report-schedule`; `pnpm ops lane {\"lane\":\"report-schedule\",\"held\":true}`). A hold stops the runner STARTING ticks: a tick already queued or running finishes, a schedule's Tick now still runs, and the windows a hold spans are caught up by ONE tick per schedule when it lifts. Default false.", +}; + +export function sanitizeReportSchedule(value: unknown): ReportScheduleSettings { + const r = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {}; + return { held: r.held === true }; +} + // Coerce a raw settings.transcriptionApps value into a clean keyed map of // AppInstanceConfig, dropping unknown/ill-typed fields. export function sanitizeTranscriptionApps( @@ -1839,6 +1856,9 @@ export const siteSettingsSchema = z.object({ publish: settingsField((v): PublishSettings => sanitizePublish(v)).describe( "The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.", ), + reportSchedule: settingsField((v): ReportScheduleSettings => sanitizeReportSchedule(v)).describe( + "The recurring reports' lane (umtool R5): the editor ticks each schedule (`pnpm ops report-schedule`; a living report or a dated series, stored in the article store) when its cadence is due, one `report-tick` job at a time, never on an idle boot. Its one key is the lane's pause gate. See ReportScheduleSettings and common/controller/reportScheduleRunner.ts.", + ), seeder: settingsField((v): SeederSettings => sanitizeSeeder(v)).describe( "The home seeder of last resort (release 21): `archilyzer seed` seeds the sites' playable torrents (`archilyzer media playable`), each one only while no other seeder has it, and only behind a VPN (the docker profile `seeder`, docker-compose.seeder.yml). Not configured until `sites` names one. See SeederSettings and common/controller/seeder.ts.", ), diff --git a/editor/app/api/ops/_reportSchedule.ts b/editor/app/api/ops/_reportSchedule.ts @@ -0,0 +1,72 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels"; +import { pickCorpusBuild } from "yt-dlp-transcript-common/lib/report/draft/tasks/corpusSource"; +import { + editionGenerator, + notWiredFetch, + notWiredRefresh, + type CountWindow, + type TickDeps, +} from "yt-dlp-transcript-common/controller/reportTick"; +import { armReportSchedule } from "yt-dlp-transcript-common/controller/reportScheduleRunner"; +import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; +import { SourceRegistry, enumerate } from "yt-dlp-transcript-mcp/research"; +import { researchEditor } from "./_researchEditor"; + +// THE RECURRING REPORTS' EDITOR SIDE (umtool R5): the deps a tick runs on, +// shared by the `report-schedule` route and the lane instrumentation.ts arms. +// +// generateEdition the existing generate path: a `report-draft` sweep over +// the window, after the window check below +// countWindow enumerate_matches' own scan (the MCP's, in process) over +// the build a sweep would read (the newest holding the +// channels): the schedule's terms, or any recording, in +// the window. 0 is a quiet edition. +// fetchAndBuild, R4's (stage 1 fetch + local build; report-draft +// refresh refresh): NOT WIRED until R4 is in this editor — each +// refuses, and the tick ends failed saying so. + +const countWindow: CountWindow = async (q) => { + const paths = getPaths(); + let dir: string; + try { + dir = (await pickCorpusBuild(q.channels, { exportBuildsDir: paths.exportBuildsDir })).dir; + } catch (e) { + return { error: (e as Error).message }; + } + const { source } = await new SourceRegistry({ kind: "local", dir }).resolve(); + const e = await enumerate(source, { + // No terms: any recording at all in the window. + query: q.terms ?? ".", + regex: q.terms ? q.regex === true : true, + channels: q.channels, + date_from: q.from, + date_to: q.to, + }); + if ("error" in e) return { error: e.error }; + return { recordings: e.result.total }; +}; + +export function reportScheduleDeps(): TickDeps { + const paths = getPaths(); + return { + paths, + settings: () => getSettings(), + knownChannels: async () => (await listChannelConfigs(paths)).map((c) => c.slug), + steps: { + fetchAndBuild: notWiredFetch, + refresh: notWiredRefresh, + generateEdition: editionGenerator({ + draft: { paths, corpusTools: (source) => createCorpusTools({ source }), researchEditor }, + countWindow, + }), + }, + }; +} + +// Armed by instrumentation.ts below the idle gate (and refused on an idle +// boot by the runner itself). See common/controller/reportScheduleRunner.ts. +export function armReportScheduleLane(): boolean { + return armReportSchedule({ deps: reportScheduleDeps(), log: (line) => console.log(line) }); +} diff --git a/editor/app/api/ops/lane/route.ts b/editor/app/api/ops/lane/route.ts @@ -23,7 +23,7 @@ import { OpsInputError, okResponse, ops, oneOf, optBool } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { lane: transcription|download|digest|backfill|publish, +// POST { lane: transcription|download|digest|backfill|publish|report-schedule, // held?: boolean, enabled?: boolean, action?: "start"|"stop"|"drain" } // // One lane, up to three independent changes, applied in the order the operator @@ -81,6 +81,12 @@ export async function POST(request: Request) { 'nothing to do — send at least one of "enabled", "held" or "action"', ); } + // THE RECURRING REPORTS' LANE (umtool R5) has a gate and nothing else: its + // schedules are switched one by one (`report-schedule` pause/resume) and + // its runner is armed at boot. + if (lane === "report-schedule" && (enabled !== undefined || action !== undefined)) { + throw new OpsInputError('the report-schedule lane takes only "held" — pause a schedule with report-schedule {"action":"pause"}'); + } if (enabled !== undefined) { if (lane === "publish") { const saved = await savePublishSettingsAction(undefined, publishForm(enabled)); @@ -90,8 +96,8 @@ export async function POST(request: Request) { // `root`: saveAutoQueueAction refuses a tree edit while the priority // model compiles the roots, and handing it back the stored tree is what // makes this a pure enable/disable rather than a tree write. - const policy = getSettings().autoQueue[lane]; - const saved = await saveAutoQueueAction(lane, { + const policy = getSettings().autoQueue[lane as AutoQueueKind]; + const saved = await saveAutoQueueAction(lane as AutoQueueKind, { enabled, maxWorkers: policy.maxWorkers, replaceAutoSubs: policy.replaceAutoSubs === true, diff --git a/editor/app/api/ops/report-schedule/route.ts b/editor/app/api/ops/report-schedule/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server"; +import { + REPORT_SCHEDULE_BODY_KEYS, + reportScheduleAction, +} from "yt-dlp-transcript-common/controller/reportScheduleOps"; +import { ops, opsFail } from "../_lib"; +import { reportScheduleDeps } from "../_reportSchedule"; + +export const dynamic = "force-dynamic"; + +// POST {"action": "list" | "create" | "update" | "pause" | "resume" | +// "delete" | "tick-now", …} +// +// A recurring report (umtool R5): a LIVING report (one article kept current — +// each tick re-fetches the scope and refreshes it) or a SERIES (a dated +// edition each tick over the window since the last), on a cadence the editor +// keeps (its report-schedule lane, held by `pnpm ops lane +// {"lane":"report-schedule","held":true}`). +// list {id?} -> {schedules | schedule, problems, lane: {held, armed}} +// create {shape: living | series, topic, question?, channels, case?, +// from?, terms?, regex?, cadence ({kind, at, dow?, days?} or +// "weekly mon 06:00"), tz?, article? (living), autoMakeCurrent? +// (living), model?, maxUsd?, dryRun?} -> {plan, schedule?} +// update {id, …} -> {schedule} a new cadence re-plans from now +// pause / resume {id} -> {schedule} a resume re-plans from now +// delete {id, confirm?} -> {plan} | {deleted} the plan unless confirm +// tick-now {id} -> {jobId} one `report-tick` job now (409 while +// one is queued or running) +// AN ADAPTER: every refusal and write is the controller's +// (common/controller/reportScheduleOps.ts). +export async function POST(request: Request) { + return ops(request, REPORT_SCHEDULE_BODY_KEYS, async (body) => { + const out = await reportScheduleAction(body, reportScheduleDeps()); + if (!out.ok) return opsFail(out.error, out.status ?? 400); + return NextResponse.json(out); + }); +} diff --git a/editor/app/components/lanes/pauseControl.tsx b/editor/app/components/lanes/pauseControl.tsx @@ -91,6 +91,20 @@ const PAUSE_COPY: Record<PauseLane, { held: PauseCopy; free: PauseCopy }> = { title: "Resume the publish lane. Its next check decides whether a pass is due.", }, }, + // The recurring reports' lane (umtool R5): a hold stops the runner starting + // ticks; a tick in flight finishes and Tick now still runs. + "report-schedule": { + free: { + label: "Hold the lane", + ariaLabel: "pause recurring reports", + title: "Hold the recurring reports: no schedule starts a tick. A tick in flight finishes; Tick now still runs.", + }, + held: { + label: "Resume the lane", + ariaLabel: "resume recurring reports", + title: "Resume the recurring reports. Each schedule whose window passed ticks once.", + }, + }, backfill: { free: { label: "Hold the lane", diff --git a/editor/app/operations/actions.ts b/editor/app/operations/actions.ts @@ -209,8 +209,15 @@ async function setLaneHeld( const cur = getSettings(); if (isGateHeld(cur, lane) !== held) { const next = withGateHeld(cur, lane, held); - // The publish lane's gate is its own block (release 18), not a policy. - await saveSettings(lane === "publish" ? { publish: next.publish } : { autoQueue: next.autoQueue }); + // The publish lane's gate is its own block (release 18), as is the + // recurring reports' (umtool R5); neither is a policy. + await saveSettings( + lane === "publish" + ? { publish: next.publish } + : lane === "report-schedule" + ? { reportSchedule: next.reportSchedule } + : { autoQueue: next.autoQueue }, + ); } } catch (e) { // REPORTED, not swallowed. The workers page's old best-effort persist diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -247,6 +247,17 @@ export async function register() { /* auto-continue that fails to arm must not block server readiness */ } + // THE RECURRING REPORTS (umtool R5): the report-schedule lane — a scan now + // and every minute, ONE report-tick job per due schedule, held by its pause + // gate. Below the idle gate: a tick is generation work. + // See common/controller/reportScheduleRunner.ts. + try { + const { armReportScheduleLane } = await import("./app/api/ops/_reportSchedule"); + armReportScheduleLane(); + } catch { + /* a lane that fails to arm must not block server readiness */ + } + // NO SECOND RESUME HOOK. There used to be two more here, one per sweep, and // each re-launched a corpus-wide pass from its own persisted flag. Both lanes // are runner lanes now, so `startAutoRunnersIfEnabled` above resumes all four diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -110,6 +110,10 @@ // pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}' // pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}' // pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait +// pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}' +// pnpm ops report-schedule --json '{"action":"list"}' +// pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait +// pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}' // // --file reads the BODY from a JSON file, which is how a big one gets sent: a // four-thousand-id tag-videos body is written by a script, not typed by a model @@ -413,6 +417,10 @@ const ACTIONS = [ // model, one per call ({models, run?, reports?, window?, maxUsd?, limit?}), // as a bench-verdicts job on draft:local (any local model) or draft:api. "bench-verdicts", + // RECURRING REPORTS (umtool R5): a living report or a dated series on a + // cadence the editor keeps ({action: list | create | update | pause | + // resume | delete | tick-now, …}); tick-now is a report-tick job. + "report-schedule", ]; // The log line a transcribe job ends with: this marker, then the result as @@ -425,6 +433,9 @@ export const TTS_RESULT_MARKER = "@@tts-result "; // The same for a generation (REPORT_DRAFT_RESULT_MARKER in // common/controller/reportDraft.ts). export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft "; +// The same for a recurring report's tick (REPORT_TICK_RESULT_MARKER in +// common/controller/reportTick.ts). +export const REPORT_TICK_RESULT_MARKER = "@@report-tick "; // The same for the verdict bench (BENCH_VERDICTS_RESULT_MARKER in // common/controller/benchVerdicts.ts). export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts "; @@ -656,6 +667,7 @@ export function parseArgs(argv) { ...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}), ...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}), ...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}), + ...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}), wait, quiet, waitTimeout, @@ -853,7 +865,8 @@ export function usage() { ' dropped), named with what would be saved. Answers the saved values.', "", 'lane takes {"lane": "transcription"|"download"|"digest"|"backfill"|', - ' "publish", "enabled"?, "held"?, "action"?: "start"|"stop"|"drain"}.', + ' "publish", "enabled"?, "held"?, "action"?: "start"|"stop"|"drain"}, or', + ' {"lane": "report-schedule", "held"}: the recurring reports\' gate, its only key.', "", 'clear-platform-hold clears a platform\'s rate-limit hold, backoff and raised', ' pace, as the lane strip\'s Clear hold: {"platform"}. Answers the sentence.', @@ -1276,6 +1289,29 @@ export function usage() { " .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with", " @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.", "", + 'report-schedule keeps a recurring report on a cadence the editor ticks:', + ' {"action": "list" | "create" | "update" | "pause" | "resume" | "delete" |', + ' "tick-now", …}. create takes {"shape": "living" | "series", "topic",', + ' "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence"', + ' ({"kind": "daily" | "weekly" | "every", "at": "HH:MM", "dow"?, "days"?}', + ' or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"?', + ' (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan', + " names the first tick, the model and its cap. A living report is one", + " article kept current: each tick fetches the scope (R4's stage 1) and", + " refreshes it, the new iteration left ready (or made current with", + ' autoMakeCurrent); its first tick is its first sweep. A series makes an', + ' edition each tick: a new article <series>-<date> over the window since the', + ' last edition ("<topic> · week of <date>"); a window the terms (or, with', + ' none, any recording) do not match is a quiet edition: recorded, no', + ' article, $0. Ticks run as report-tick jobs, one at a time, never on an', + " idle boot, held by the lane's gate (lane report-schedule); a window missed", + " while the editor was down is ONE catch-up tick. A cap refusal ends a tick", + ' held-by-cap. update {"id", …} (a new cadence re-plans from now); pause /', + ' resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm', + ' is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued', + ' or running); --wait prints the tick\'s @@report-tick {json}. list {"id"?}', + ' answers the schedules with their chip, call and spend, and the lane.', + "", "Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,", " ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").", " WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -866,3 +866,13 @@ test("get generation-usage and get iterations read the generation state (release assert.match(parseArgs(["get", "iterations"]).error, /needs an argument/); assert.match(usage(), /get generation-usage \[<day>\] is the day's Claude API spend/); }); + +test("report-schedule is registered, posts to its route, and --wait prints a tick's result (umtool R5)", () => { + const p = parseArgs(["report-schedule", "--json", '{"action":"tick-now","id":"co-host-updates"}', "--wait"]); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/report-schedule"); + assert.deepEqual(p.body, { action: "tick-now", id: "co-host-updates" }); + assert.equal(p.resultMarker, "@@report-tick "); + assert.match(usage(), /report-schedule keeps a recurring report on a cadence the editor ticks/); + assert.match(usage(), /\{"lane": "report-schedule", "held"\}/); +}); diff --git a/settings.json.example b/settings.json.example @@ -208,6 +208,9 @@ "hub": "off", "homepage": "off" }, + "reportSchedule": { + "held": false + }, "seeder": { "sites": [], "trackers": [],