commit 5f262003c8d5d91590961d3d71485a9ea638223e
parent 5b07e9e16298c2b4f2093f07d10c946591da3325
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 06:37:27 -0400
merge ux/integration (92ac00fa: R2 research boards, the transition and toggle fixes) into ux/p4a
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
46 files changed, 4432 insertions(+), 49 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,7 +145,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
-| `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", ...} -> {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). | `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}'` |
+| `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", ...} -> {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"?} -> {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"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {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/<run>/ (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` |
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -14,6 +14,11 @@
// settings.generation.models.extractor): a Claude model id the
// price table knows (release 28 F2)
// question / channels / from / to a sweep's
+// seed a NEW sweep's starting report: cited markdown in the /sweep
+// shape (umtool's research board, R2), kept as the iteration's
+// seed.md; the agent's report starts from it and the sweep
+// verifies and extends it. API models only (the local pipeline
+// writes its report from scratch)
// feedback a revision's
// copyOf run iteration N again on another model (same kind and inputs)
// maxUsd the job's cap (default by task; never above caps.max)
@@ -56,6 +61,7 @@ import {
readIterationFile,
reportSourceOf,
updateIteration,
+ writeIterationFile,
type Iteration,
} from "../lib/report/iterations";
import { diskPostChannelOf } from "../lib/report/convert-server";
@@ -96,8 +102,12 @@ export const REPORT_DRAFT_BODY_KEYS = [
"entries",
"force",
"autonomy",
+ "seed",
] as const;
+// A seed's size: a board of a few hundred quotes, with room.
+export const SEED_MAX_CHARS = 200_000;
+
export class ReportDraftInputError extends Error {}
export type ReportDraftBody = {
@@ -119,6 +129,7 @@ export type ReportDraftBody = {
entries?: string[];
force?: boolean;
autonomy?: Autonomy;
+ seed?: string;
};
// A Claude model the price table knows: one of its ids, or a dated id of one
@@ -199,6 +210,12 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (out.task !== "research") fail('"autonomy" is a research run\'s');
out.autonomy = b.autonomy as Autonomy;
}
+ if (b.seed !== undefined && b.seed !== null) {
+ if (typeof b.seed !== "string" || !b.seed.trim()) fail('"seed" is markdown text');
+ if (b.seed.length > SEED_MAX_CHARS) fail(`"seed" is at most ${SEED_MAX_CHARS} characters`);
+ if (out.task !== "sweep" || out.iteration !== undefined || out.copyOf !== undefined) fail('"seed" starts a new sweep: no "iteration", no "copyOf"');
+ out.seed = b.seed;
+ }
if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:<dir>, remote:<url> or hub:<url>');
if (out.source && out.build) fail('give "source" or "build", not both');
// What each task needs.
@@ -361,6 +378,9 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
}
const model = modelFor(gen, body.task, body.model);
const provider = providerOf(model);
+ if (body.seed && provider !== "api") {
+ return refuse(`a seeded sweep runs the agent on a Claude model, not ${model}: the local pipeline writes its report from scratch`);
+ }
if (body.extractorModel && provider === "local") {
warnings.push(`extractorModel ${body.extractorModel} is unused: a sweep on a local model runs the pipeline, which has no extractor`);
}
@@ -408,6 +428,8 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
paths,
)
).n;
+ // A seeded sweep's starting report, beside the iteration (the task reads it).
+ if (body.seed) await writeIterationFile(body.article, n, "seed.md", body.seed, paths);
}
const result = await runManagedFunction({
kind: REPORT_DRAFT_JOB_KIND,
diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts
@@ -11,7 +11,7 @@
// finding whose quote still fails is dropped.
import { providerOf, runAgent, type AgentTool } from "../../../llm";
-import { iterationLabel, writeIterationFile } from "../../iterations";
+import { iterationLabel, readIterationFile, writeIterationFile } from "../../iterations";
import {
CLAIM_QUOTES_RULE,
COVERAGE_RULE,
@@ -105,6 +105,15 @@ function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from
].join("\n");
}
+// What a seeded sweep is told (the seed is already the report file).
+export const SEED_NOTE = [
+ "THE REPORT FILE ALREADY HOLDS THE OPERATOR'S RESEARCH BOARD (read_report): findings a person pinned after reading them, in sections, each a claim, a verbatim quote and its link, some with a `Note:` line.",
+ "- Start from it: keep its sections, its order and its claims. Check every quote against its transcript with get_transcripts like any other; correct a quote the transcript does not hold word for word, or remove it, and say which in the summary.",
+ "- A `Note:` line is the operator's: heed what it says (a speaker not checked, a drifted quote, a different en-orig track), then drop the Note lines from the final report.",
+ "- Its links may be on another origin: cite every finding as the rules say.",
+ "- Then sweep the plan for what the board does not cover, and merge it into the board's sections (or new ones).",
+].join("\n");
+
const REPAIR_SYSTEM = [
UNATTENDED_RULE,
"",
@@ -182,9 +191,13 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
const batch = input.batchSize ?? 10;
const resolver = slugResolver(deps.corpus, channels);
const rewrite = (t: string) => rewriteMomentBases(t, resolver, origin);
- const file = reportFile({ article: h.article, n: h.n, paths: h.paths });
+ // A SEEDED sweep (reportDraft's `seed`, a research board): the report starts
+ // as the seed, and the agent verifies and extends it.
+ const seed = (await readIterationFile(h.article, h.n, "seed.md", h.paths).catch(() => null))?.trim() || null;
+ const file = reportFile({ article: h.article, n: h.n, paths: h.paths, ...(seed ? { initial: seed } : {}) });
+ if (seed) await file.set(seed); // sweep.md holds it from the first turn, as a run cut short keeps it
const extracts = { n: 0 };
- h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}`);
+ h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}`);
const request =
`${question} channels=${channels.join(",")} batch_size=${batch} parse_model=${input.extractorModel} report=sweep.md`;
@@ -216,7 +229,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
llm: deps.llm,
model,
system: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to }),
- user: plan,
+ user: seed ? `${plan}\n\n${SEED_NOTE}` : plan,
tools,
meter: h.meter,
maxUsd: input.maxUsd,
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -66,7 +66,8 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number];
// The files writeIterationFile may write (iteration.json is written by
// create/update only). A later slice adds a name here, never a path.
-export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json"] as const;
+// `seed.md`: a seeded sweep's starting report (a research board, umtool R2).
+export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md"] as const;
export type IterationFile = (typeof ITERATION_FILES)[number];
// A revision needs something to revise.
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -5,6 +5,11 @@
- **Research keeps a reading log.** Every hit is read, skipped or unread, and the header says **read 37 of 97**. The log is umtool's, under `REPORTS_ROOT/.umtool/research/sessions/`, one per query and scope, never in the corpus.
- **umtool's archive inventory, `/research/archive`.** Channels × years: the videos the editor holds (its `GET /api/ops/coverage`, the MCP's `channel_coverage`) or the videos the source publishes, on the Meter ramp, gaps over 60 days marked, nothing held as —. Hover or focus a cell for what it holds, published, deleted or unlisted, and transcripts vs captions; the arrow keys walk the grid; **Table** lists the same numbers. When umtool has no `WORKER_TOKEN` or the editor does not answer, the page says which, and for the local corpus reads the held counts on disk instead.
- **The MCP's enumerate is shared as data.** `enumerate_matches` renders `mcp/src/enumerate.ts`, which umtool calls through the new `yt-dlp-transcript-mcp/research` export; `fetch_clip`'s cite-to-directory mapping is `clipTarget.ts`, and a caller can name itself to the editor (`requestedBy`). Nothing an agent sees changed.
+- **umtool has research boards: `/research/<case>`.** Pin a hit on `/research` with `p` or the reader's **Pin to board**, to the board chosen beside the ask bar or one the pin asks for (a new case is named for the query). A pin keeps a **snapshot**: the words the transcript has at the cite, read again by the server, and the cite (recording, channel, date, second, track, the house-format link). On the board each quote is a slip on the reader surface, with our **claim line** and **note** under it (`e`, `n`), the flags (**Speaker not checked** until `s`; drifted; en-orig differs), in sections and order (`a` adds a section, `alt+j`/`alt+k` or a drag moves a quote or a section, `m` picks a section, `x` removes after a confirm). The side panel says the scope, how many recordings the search found, **read N of M** (the search's reading log becomes the case's), and where the case is stored: `REPORTS_ROOT/.umtool/research/<case>/case.json`, never in the corpus. `/research` lists the cases before a search. Needs a restart of umtool.
+- **Re-verify a board.** **Re-verify quotes** (`v`) reads every quote again at its cite in the current transcript (±30 s): a quote whose words changed is marked **Drifted** with the words there now, a recording gone is **Missing**, and where a recording has both the served `en` track and `en-orig` and they differ at the cite, it says so (the `en` track can rewrite what was said). A quote's words never change by themselves: **Use the current words** takes the new ones and keeps the old in the quote's history.
+- **A board exports as cited markdown.** **Copy as cited markdown** (`c`) and **Download .md**: the case's title, its notes as the summary, a `##` per section, each quote as a finding — the claim, the quote in quotes, `[title @ m:ss](link)` — with our note under it, and a `## Coverage` paragraph (the scope, what was searched and read, what is pinned, drifted and unchecked). It converts as a /sweep report.
+- **Hand off a board, plan first.** **Draft an article from this board** shows the plan — the article, the question, the channels, the model and the most it may spend — and on **Start the sweep** asks the editor for a `report-draft` sweep seeded with the board's markdown. **Start a video from this board** shows the clips — one per quote, its window the quote's cue span — and on **Create the project** scaffolds a report-video project under the reports root. A board with a quote from a local-only channel never becomes an article. The API (`/api/research/cases`, documented in its route) is what Create will use.
+- **A sweep can start from a seed.** `pnpm ops report-draft --json '{"task": "sweep", …, "seed": "<markdown>"}'` keeps the markdown as the iteration's `seed.md`; the sweep agent's report starts from it, checks its quotes, and extends it. A seed is a new sweep's, on a Claude model (a local model is refused: its pipeline writes the report from scratch). Needs a restart of the editor.
- **umtool drafts each section of a report video with a model you pick.** A video project made from an article's iteration has a **draft** section: for the cut, the on-screen titles, the teaser, the flips, the threads, the narration and the YouTube text, **Draft with** and a model (the generation policy's models, the task's route chosen first), **force** (re-drafts only what a model drafted; what you wrote or edited is never replaced), and for a per-entry task the entries to draft. The job's progress shows while it runs; when it ends the page shows what it wrote, skipped and had refused by a check, the **drafted by** badge with **Approve** and **Reject**, and any draft kept aside with **Use this**. A project not made from an iteration says so and offers none. The article's Iterations tab gains the same drafts beside **Narrate**. Needs a restart of umtool.
- **Draft everything.** One button on the Iterations tab (or `umtool chain <article> <n> --draft-all [--model M]`) runs the chain with every media draft in it, on the model you choose: the cut, on-screen, teaser, flips, threads and narration after the manifest, then the voices, a fast build and the podcast, then the YouTube text, whose chapters are re-muxed so `out/youtube.txt` is written. A draft the editor refuses or that fails is marked failed and the chain carries on; one with nothing to draft, or flips and threads with no on-screen deck (or with the other panel on), is skipped. It does not attach the video to the article: review the drafts first. Started again, it resumes after the last draft that ran. Needs a restart of umtool.
- **A site's Delete shows its plan before anything goes.** On `/sites`, **Delete** lists what would be removed (the site, its publish state and last bundle, its staging), how much, what is kept and what refuses; **Confirm delete** removes it. A site with a deploy target, a recorded deploy or reports of its own is refused unless you tick the box and press **Delete with force**; a site whose directory is a link, or a publish stage running, is refused outright. The delete is `pnpm ops delete-site`'s, so it now removes the build state too.
diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts
@@ -11,7 +11,7 @@ import { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-comm
import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage";
-import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations";
+import { createIteration, projectOf, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations";
import type { Paths } from "yt-dlp-transcript-common/lib/paths";
// Run with:
@@ -165,6 +165,38 @@ test("an API sweep with its own extractorModel: the batches are read on it, its
assert.ok(it.usage["claude-haiku-5-5"]!.calls === 1);
});
+test("seed (umtool R2): a new sweep's starting report — text, sized, a new sweep's only", () => {
+ const sweep = { task: "sweep", article: "a", question: "q", channels: ["x"] };
+ assert.equal(parseReportDraftBody({ ...sweep, seed: "# Board\n" }).seed, "# Board\n");
+ assert.throws(() => parseReportDraftBody({ ...sweep, seed: " " }), /"seed" is markdown text/);
+ assert.throws(() => parseReportDraftBody({ ...sweep, seed: "x".repeat(200_001) }), /"seed" is at most 200000 characters/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", iteration: 1, seed: "# B" }), /"seed" starts a new sweep/);
+ assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f", seed: "# B" }), /"seed" starts a new sweep/);
+});
+
+test("a seeded sweep: refused on a local model; on the API the seed is kept as seed.md and the agent is told to start from it", async () => {
+ const seed = '# Board\n\n## Pinned\n\n- The pier was never approved: "the pier was never approved" — [Kitchen @ 0:10](https://example.test/?v=synth-kitchen%2Fk1&t=10)\n';
+ const local = await enqueueReportDraft({ task: "sweep", article: "synth-seed-local", model: "qwen3:8b", question: "q", channels: ["synth-kitchen"], source, seed }, deps());
+ assert.equal(local.result.ok, false);
+ assert.match((local.result as { error: string }).error, /a seeded sweep runs the agent on a Claude model/);
+ assert.equal(await readIteration("synth-seed-local", 1, paths), null);
+
+ const r = await run("sweep-agent");
+ api.push(...r.turns);
+ const before = api.requests.length;
+ const out = await enqueueReportDraft({ task: "sweep", article: "synth-seeded", model: r.model, question: r.question, channels: r.channels, source, seed }, deps());
+ assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const job = getRegistry().get(out.result.jobId)!;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.match(log, /seeded \(\d+ chars\)/);
+ assert.equal(await readIterationFile("synth-seeded", out.iteration, "seed.md", paths), seed);
+ const first = JSON.stringify(api.requests[before]);
+ assert.match(first, /THE REPORT FILE ALREADY HOLDS THE OPERATOR'S RESEARCH BOARD/);
+});
+
test("the daily cap: a job that would start past the day's total is refused, naming it", async () => {
const before = await readGenerationUsage(paths.generationUsageFile);
const total = before.reduce((s, x) => s + x.usd, 0);
diff --git a/editor/app/channels/components/ChannelBuildToggle.tsx b/editor/app/channels/components/ChannelBuildToggle.tsx
@@ -1,6 +1,7 @@
"use client";
import { toggleChannelBuildInclusionAction } from "../actions";
+import { useHydrated } from "../../operations/components/useOperationsStatus";
export function ChannelBuildToggle({
slug,
@@ -9,6 +10,10 @@ export function ChannelBuildToggle({
slug: string;
excluded: boolean;
}) {
+ // Disabled until hydrated: the form's action is a client closure, so a click
+ // that lands before hydration submits natively and silently does nothing
+ // (channel-build-toggle.spec's toggle-back, clicked right after a goto).
+ const hydrated = useHydrated();
return (
<form
action={async () => {
@@ -17,6 +22,7 @@ export function ChannelBuildToggle({
>
<button
type="submit"
+ disabled={!hydrated}
aria-label={`toggle build inclusion for ${slug}`}
aria-pressed={!excluded}
title={
diff --git a/editor/app/cleanup/components/ChannelCleanupToggle.tsx b/editor/app/cleanup/components/ChannelCleanupToggle.tsx
@@ -1,6 +1,7 @@
"use client";
import { toggleChannelCleanupInclusionAction } from "../../channels/actions";
+import { useHydrated } from "../../operations/components/useOperationsStatus";
// Per-channel include/exclude switch for the aggregate cleanable-data total.
// Token-driven (semantic success / muted) so it recolors with every theme.
@@ -11,6 +12,9 @@ export function ChannelCleanupToggle({
slug: string;
excluded: boolean;
}) {
+ // Disabled until hydrated: the form action is a client closure, so a click
+ // before hydration submits natively and silently does nothing.
+ const hydrated = useHydrated();
return (
<form
action={async () => {
@@ -19,6 +23,7 @@ export function ChannelCleanupToggle({
>
<button
type="submit"
+ disabled={!hydrated}
aria-label={`toggle cleanup-total inclusion for ${slug}`}
aria-pressed={!excluded}
title={
diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -350,10 +350,11 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─
| P1 foundation | `ux/p1` → `main` `37354f70` | LIVE 2026-10-14 (umtool BUILD_ID LQxTh16Pe…) |
| R1 research | `ux/r1` → `main` `01120bfe` | LIVE 2026-10-14 |
| P3 inbox/work/tools/URLs | `ux/p3` → `main` `01120bfe` | LIVE 2026-10-14 (umtool BUILD_ID q7e29Em…) |
-| P2b jobs + drafts | `ux/p2b` | in progress |
-| R2 research boards | `ux/r2` | in progress |
+| P2b jobs + drafts | `ux/p2b` → `main` `44c7b758` | LIVE 2026-10-14 (umtool BUILD_ID J2YDbFuc…) |
+| R2 research boards | `ux/r2` | gates green, not merged (record below) |
| P5 create + settings | — | after R2 (consumes the board API) |
-| P4a piece page | `ux/p4a` | P4a-1 shipped on the branch (the frame); P4a-2, P4a-3 next |
+| P4a-1 piece frame | `ux/p4a` | shipped on the branch (record below); review follow-up in progress |
+| P4a-2, P4a-3 | — | after P4a-1 |
| R3, P4b, P6 | — | after R2 / P4a / all |
### P2a, as shipped
@@ -1018,6 +1019,184 @@ group shows the drafts cards beside the iteration cards.
kind's `WHAT` label (`drafts-unreviewed`: "drafts to review"). Gates: tsc and typecheck clean; unit 814, 0 fail;
`running.spec` + `inbox.spec` + `inbox-engine.spec` 20/20 through the umtool e2e entry.
+### P2b rollout (orchestrator, 2026-10-14)
+
+Rulings: lane runners stay out of "Running N"; queued syncs only in the "+ N queued" line; a drafts card counts
+unreviewed and changed-since-approved fields, not rejected ones; the card is titled by what was drafted (follow-up
+`bec88600`). Gates on `44c7b758`: repo-wide tsc clean; full umtool e2e 384 passed, 0 failed, 6 skipped (7.2 min);
+test:scripts 965, 962 pass, 0 fail. `main` fast-forwarded to `44c7b758`; umtool built (41 s) and restarted
+(`scripts/p2b-umtool.sh`). Live: `/`, `/work`, `/research`, `/tools` 200; `/api/rail` inbox 53, work 60; decisions API
+828 rows, 0 `drafts-unreviewed` (as predicted), notes' hrefs intact; `/api/running` against the live editor: nothing
+running, "+ 3 lanes", $5.73 today over 15 jobs, editor reachable.
+
+### R2, as shipped
+
+**What.** Research boards: a case is a question being researched — its scope, the quotes pinned from Research as
+snapshots, their sections and order, our claim line and note on each — at `/research/<case>`, with re-verify, a
+cited-markdown export, and two hand-offs behind plans. Umtool-side state; read-only on the corpus.
+
+- **The store** (`umtool/lib/research/cases.mjs`, plain ESM, unit-tested): `REPORTS_ROOT/.umtool/research/<case>/case.json`,
+ `{format: "umtool-research-case", version: 1, id, title, scope, search, sessions, sections, quotes, notes, handoffs,
+ counters, createdAt, updatedAt}`. The lifecycle store's discipline (one writer, serialised, temp + rename, an unreadable
+ file never overwritten — 409, listed with its error). A case id is a piece segment; `sessions`, `census`, `archive`,
+ `runs`, `cases`, `new` are reserved (the reading logs and the census live beside the cases; the pages under
+ `/research`). The piece id is `c:<case>`; a created case takes the title's slug, `-2`, `-3` … when taken.
+- **A quote is a snapshot** (`lib/shortlist.ts` `Pick`'s reasoning): the words at the cite, read by the SERVER at pin
+ time through the MCP engine (`findVideo`/`findPost`, the cue nearest the cited second, `until` for several cues), and
+ the cite — source handle, channel slug and key, recording id (and the editor's directory id when a Rumble URL slug
+ differs), title, date, first cue start and last cue end, clock, track (and the alternate track id), the moment link,
+ the house-format citation, local-only. The same cite twice answers the quote already there (`duplicate`). A pin
+ carrying its search (`session`, counts) makes that search the case's: `search` and `sessions` — "searched N",
+ and "read N of M" from that session's reading log, which R1's page keeps writing (the log becomes the case's by
+ reference, not by copy).
+- **Re-verify** (`lib/research/boards.ts` `verifyQuote`): R1's `windowOf` (±30 s) on the quote's own track; the words
+ found (case, punctuation, spacing aside; whole words) → `ok` (with where they start now when they moved ≥ 1 s); else
+ `drifted` with the words over the quote's seconds now; a recording gone → `missing`; a source not offered → `unreadable`.
+ Where the record has both `en` and an `en-orig` and their words differ over the cite, `enOrig {text, quoted, other}`.
+ Nothing changes a quote's words but the operator's `useCurrentWords` (a drifted quote only; the old words kept in
+ `history`).
+- **The export** (`lib/research/board.mjs` `exportMarkdown`): `# title`, the notes as the summary and a line saying what
+ the board is, a `##` per section (`Unsorted` when there are sections, `Findings` when there are none) with one finding
+ per quote — `- <claim>: "<quote>" — [<title> @ m:ss](<link>)` (a post `[post by <author>, <date>](<link>)`), our note,
+ speaker-not-checked, drifted and en-orig as a `Note:` line under it — and `## Coverage` (scope, searched, read, pinned,
+ drifted, unchecked). It converts as a /sweep report (`boards.test.ts` runs common's `sweepToReport` on it: one
+ citation per quote, verbatim, no problems).
+- **Hand-offs, plan then confirm** (`lib/research/handoff.ts`):
+ - **Article.** Neither form the plan named existed: report-draft's sweep took a question and channels, nothing seeded,
+ and no task took a markdown input. The smallest additive change in common: report-draft's **`seed`** (a new sweep's,
+ ≤ 200,000 characters, on a Claude model) is kept as the iteration's `seed.md` (`ITERATION_FILES` + `seed.md`); the
+ sweep agent's report file starts as the seed and its first message says to verify every quote, heed and drop the
+ `Note:` lines, and extend it (`SEED_NOTE`). A local model is refused: the pipeline writes its report from scratch.
+ So the hand-off is "a report-draft sweep seeded with the board", whose seed is "the exported markdown" — both
+ readings in one. umtool asks the editor (`askEditor` → `POST /api/ops/report-draft`; it writes nothing of the article
+ store) with `task: "sweep"`, the case id as the article, the scope's query (else the title) as the question, the
+ scope's channels (else the quoted ones), dates, the source handle, the policy's API model (a seeded sweep runs the API
+ agent whatever the sweep route; the plan says so) and the seed. The plan shows the article (new or a new iteration),
+ question, channels, seed size, model and the cap it may spend; the confirm answers `{href, jobId, iteration}`.
+ - **Video.** `scaffoldReportVideo` (`lib/projects/scaffold.mjs`) takes a board's `timeline` (additive; refused with
+ `--from`/`--seed`, every entry checked): one clip per video quote in board order, its window the quote's cue span
+ (start, end, cite, quote, date, the claim as `note`, the alternate track; `siteVideo`/`siteChannel` when the editor's
+ directory id differs), `provenance.siteOrigin` when every link shares one viewer origin, and a README listing the
+ windows to review. No title or chapter cards (the operator's evidence-first rule). The plan shows the folder, title,
+ clips, origin and what it writes; a taken folder is refused.
+ - **Research rules.** A board with a local-only quote (`rules.mjs`, Candace's channels) is refused an article (the
+ article store publishes); its video plan warns it must stay local. The export itself is local and allowed. The X
+ archive is on no site, so no R1 source can reach it and a board cannot hold it.
+- **The API** (documented in `app/api/research/cases/route.ts`; shapes in `lib/research/case-types.ts`, for P5):
+ `GET/POST /api/research/cases`; `GET/PATCH …/<id>` (title, notes, scope; `sections` as the whole ordered list,
+ `order` as every quote with its section); `POST …/<id>/quotes` (pin); `PATCH/DELETE …/quotes/<qid>`;
+ `POST …/<id>/verify`; `GET …/<id>/export.md[?download=1]`; `POST …/<id>/handoff {to, confirm?}` → `{plan}` /
+ `{href}`. JSON, `no-store`, errors in words (400, 404, 409, 502). Mutations answer the `CaseView`.
+- **`/research/<case>`** (`components/research/BoardView.tsx`, `QuoteSlip.tsx`, `HandoffDialog.tsx`; canvas "Research
+ board"): the header (Research · case, the title, quotes · sections · from "query" · source, Re-verify quotes,
+ Copy as cited markdown, Download .md); ONE lit list of section heads and quotes — each quote a slip on the reader
+ surface (the words in the reader serif, the cite in mono, linked), the claim line and the note edited in place on the
+ desk, the flags (**Speaker not checked** until checked, **Drifted** with the words there now and **Use the current
+ words**, **Missing**, **en-orig differs** with en-orig's words); the lit quote's section menu, speaker toggle, Remove;
+ the side panel (Hand off, Scope, Searched, Read N of M, Stored, Piece, Search and pin more, + Section, Notes, what was
+ made from it). Keys: `j`/`k`, `alt+j`/`alt+k` (a quote, across sections; or a section), `e` claim, `n` note, `s`
+ speaker, `m` section, `a` add section, `r` rename (the lit section, else the case), `x` remove (confirm), `v`
+ re-verify, `c` copy, `/` search more; a quote drags by its grip onto a quote or a section head.
+- **`/research`**: a **Board** chooser beside Search (in the URL as `case=`, remembered in this browser); `p` or the
+ reader's **Pin to board** (now the reader's one filled action; Copy citation an outline) pins the lit hit's cited cue —
+ to the chosen case, or the dialog asks (an open case, or a new one named for the query). The reader says "Pinned to …
+ · N quotes · Open board" or "Already on … (q2)". A hit in a description or tags (no moment) is refused. Before a search
+ the page lists the **Cases** (a lit list: title, quotes · sections · drifted, updated).
+- **⌘K** lists every case as `c:<case>` (its board), through `/api/jump` (the palette is P2b's; not touched).
+
+**Commits** (`ux/r2`, from `main` `8f08fc0b`):
+
+| sha | what |
+|---|---|
+| `77b03246` | common: report-draft's `seed` (a new sweep's starting report, kept as `seed.md`; the agent starts from it; refused on a local model), its tests, the ops help and COMMANDS.md |
+| `2582dbe7` | the case store, pin as a snapshot, re-verify, the export, the hand-offs, the API (seven routes), scaffold's `timeline`, the fixture's `en` track and board, unit tests |
+| `c9d716b3` | `/research/<case>` (the board), pinning from Research's results and reader, the Board chooser and the Cases list |
+| `7c3f5c3d` | `e2e/board.spec.ts`; the claim and note save once |
+| `3400db75` | `[Unreleased]` bullets |
+| `99430f38` | ⌘K lists the cases (`/api/jump`) |
+| `2a51bbb5` | a quote's claim and note are in the Tab order on the lit quote only |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| repo-wide `tsc --noEmit` | clean (umtool's at every commit; repo-wide at `77b03246`, `3400db75` and the tip `2a51bbb5`) |
+| `pnpm --filter umtool typecheck` | clean |
+| umtool unit, `node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs` | 817 tests, 815 pass, 2 skipped, 0 fail (new: cases 7, board 6) |
+| `pnpm --filter umtool test` | 16/16 (new: `boards.test.ts` 5 — the pin, re-verify on the fixture's drifted and `en` quotes, the export through common's `sweepToReport`, both hand-offs planned and confirmed against a stand-in editor) |
+| `pnpm run test:scripts` (reads the capped build's traces) | 968 tests, 966 pass, 2 skipped, 0 fail |
+| common `pnpm --filter yt-dlp-transcript-common test` | 4096 tests, 4094 pass, 2 fail — both `controller/autoRunner.test.ts` (`computeLeafPending…`, `a channel with a move marker…`), which read the repo's `settings.json`: a worktree has none. With `SETTINGS_FILE` at the primary's (read only) the file passes 24/24; on `main` in the primary it passes 24/24. Not this lane's |
+| editor unit `pnpm --filter editor test` | 297/297 (2 new in `_reportDraft.test.ts`: the seed's body rules; a seeded sweep refused on a local model, and on the API kept as `seed.md` with the agent told to start from it) |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | 363/363 |
+| `pnpm archilyzer docs cli --check` | clean (COMMANDS.md regenerated for the `seed` sentence) |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`, heavy slot) | exit 0; compiled 11.2 s, 34 s wall, 1.40 GB max RSS. The new routes' traces: 873–952 files, none from `transcripts/`, `export/public`, `.e2e-song`, `.next-e2e` or `.env*` |
+| full umtool e2e (`pnpm --filter umtool run e2e`, detached, queued) at `7c3f5c3d` | 394 tests: **388 passed, 0 failed, 6 skipped** (the song-data skips), 7.9 min. `board.spec` 7/7 |
+| `board.spec` + `research.spec` + `shell.spec` at the tip `2a51bbb5` (after ⌘K and the Tab change) | 39 passed, 0 failed |
+
+**Screenshots and keys.** Job scratch `r2-shots/`: `/research/<case>` and `/research` with cases at 1366×768 and
+1440×900, dark and light, on the REAL local corpus (the primary's `export/public`, Rekietalyzer, read only; every write
+— the case, the reading log — in a scratch REPORTS_DIR): a "Contempt of court" board of five pins from the 70-recording
+search, two sections, a claim and note, re-verified; plus Research after a pin ("Already on …"), and both hand-off
+plans. Against the canvas: the same columns (the board, the 300 px side panel), the slip on the reader surface with
+the cite in mono, Claim / note / flags on the desk, the section heads in small caps with Meter counts, the lit quote's
+Signal edge, the side panel's Hand off (the filled one is Draft an article), Scope / Searched / Read (Meter) / Stored.
+Differences: an **Unsorted** group above the sections (where a new pin lands), the lit quote's action row (section,
+speaker, Remove), the key legend at the foot, Notes and Piece in the side panel. Keyboard only (reduced motion): the
+rail's 11 stops, the header's three, the board ONE stop (the lit line, dashed 1 px), the section heads' actions, the
+side panel's; a quote's claim and note only on the lit quote (`e`/`n` reach them, Escape returns to the line); `j`/`k`,
+`alt+j`/`alt+k`, `a` (the dialog focuses its field) all work; the head moves in 0 s under reduced motion.
+
+**Found and left.**
+- **A seeded sweep needs an API model.** A policy that routes sweeps to Claude Code or the local model still gets the
+ API agent for a board (the plan says so); the local pipeline would need a seed step of its own.
+- **The seed's links stay on the board's origin;** the agent is told to cite on its own. A case on a hub keeps
+ `<site>:<slug>` keys in its scope; the sweep gets the slugs.
+- **A pin is one cue** from the UI (the cited cue); the API takes `until` for several, and the reader has no
+ range-select yet. Cue ends are where a caption wrapped, so a video clip's window can stop mid-thought (the README
+ says so; the bench is where it is cut).
+- **The case's reading log is the search's session, by reference.** A second search pinned into the same case becomes
+ `search`; earlier sessions stay listed in `sessions`, and "read N of M" is the latest's.
+- **No case delete yet** (not asked for); a case is a directory under `.umtool/research/`. P5/P6 can add it, plan
+ then confirm.
+- **Not on Work or the Inbox.** `c:<case>` is in ⌘K only; P5 (Create's "Research a question" opens a case) and P4a (a
+ case as a piece's Research stage) consume the API.
+- **The header buttons' focus ring** (`buttonVariants`) computes to the text colour rather than Signal on this page as
+ elsewhere — P1/P3's global ring, not changed here.
+- Not touched (P2b's): `lib/activity.ts`, `components/shell/**` (the board renders `AppRail` and `AppHeader` as they
+ are), `e2e/fixtures/editor-stub.mjs`, `lib/articles/generation.ts` (its `askEditor` and `readPolicy` are called, not
+ edited), `lib/inbox*`, `lib/projects/report.mjs`.
+
+**Follow-up (after review, 2026-10-14).**
+- **Merged `ux/integration` `1462f63a` (P2b)** at `91b40a81`. One conflict, in this plan: the status table takes P2b's
+ LIVE row and R2's own; the P2b record and its rollout stay where they are, and R2's record follows them. No conflict
+ in code: none of P2b's files had been touched here.
+- **One door to the editor's drafts.** P2b's `enqueueDraft` (`lib/articles/generation.ts`) now lists `source` and
+ `seed` among the report-draft keys, and the board's article hand-off goes through it instead of calling `askEditor`
+ itself. `POST /api/articles/generate` accepts the two keys as well; the editor judges them as before.
+- **Focus rings no longer fade in.** The "Found and left" line on the header buttons' ring was wrong about the
+ cause: it was not the wrong colour but a 150 ms fade — Tailwind v4's `transition-colors` includes `outline-color`, so
+ the Signal ring eased in from `currentColor`. Button, Badge, the reader's buttons (`paperButtonVariants`), the project
+ grid's cards and `VerdictRow` (bare `transition`) now ease `color, background-color, border-color,
+ text-decoration-color, fill, stroke` (VerdictRow also `opacity`) and leave the outline out. `shell.spec` reads the
+ focused Search button's outline the moment Tab lands: `solid 2px` in Signal, and no `outline`/`all` in its
+ transition properties.
+- **Gates** at `b282e83d`: repo-wide tsc clean; umtool unit 827 tests, 825 pass, 2 skipped, 0 fail; `pnpm --filter
+ umtool test` 16/16; test:scripts 978, 976 pass, 2 skipped, 0 fail; common with `SETTINGS_FILE` at the primary's
+ (read only) **4096/4096**; capped build exit 0 (11.6 s compile, 39 s wall, 1.45 GB); full umtool e2e **398 tests: 392
+ passed, 0 failed, 6 skipped**, 7.8 min.
+
+| sha | what |
+|---|---|
+| `91b40a81` | merge `ux/integration` `1462f63a` (P2b) |
+| `b282e83d` | the hand-off through `enqueueDraft` (`seed`, `source` on its key list); no control's focus ring fades in; the shell.spec assertion |
+
+**R2 editor gate (orchestrator, 2026-10-14).** R2 changes common's `report-draft` (the `seed`), so the editor was
+gated too, on `ab2e6830`: editor unit 297/297; capped editor build ok; full editor e2e 693 passed, 1 failed, 12 skipped
+(22.3 min; the worktree needed `export/public` linked from the primary first). The red, `channel-build-toggle.spec:85`,
+was a real editor bug also seen on r24/r25: the build and cleanup toggles' forms take a client-closure `action`, so a
+click before hydration submitted natively and was dropped. Fixed in `ff3baf6b` (both disabled until `useHydrated()`);
+`channel-build-toggle.spec` + `cleanup-page.spec` then 3 runs, 2/2 each.
+
### P4a-1, as shipped
**What.** A report video's project page (`/projects/<path>`) is a piece page: a frame around one tab of the
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1244,7 +1244,10 @@ export function usage() {
' 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).',
+ ' 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.",
"",
'research-approve settles a research run\'s acquisitions: {"article",',
' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->',
diff --git a/umtool/app/api/jump/route.ts b/umtool/app/api/jump/route.ts
@@ -1,23 +1,29 @@
import { listPieces } from "@/lib/pieces";
+import { listCases } from "@/lib/research/boards";
+import { researchCaseHref } from "@/lib/research/hrefs";
export const dynamic = "force-dynamic";
// What the ⌘K palette can jump to that is not a fixed place: every piece, as
-// { id, title, href, kind, stage, lifecycle }. The places, tools and create
-// actions are the palette's own (components/shell/JumpPalette.tsx).
+// { id, title, href, kind, stage, lifecycle }, and every research case (R2:
+// `c:<case>`, its board). The places, tools and create actions are the
+// palette's own (components/shell/JumpPalette.tsx).
export async function GET() {
- const pieces = await listPieces();
+ const [pieces, cases] = await Promise.all([listPieces(), listCases().catch(() => [])]);
return Response.json(
{
- pieces: pieces.map((p) => ({
- id: p.id,
- title: p.title,
- href: p.href,
- kind: p.kind,
- site: p.site,
- stage: p.stage,
- lifecycle: p.lifecycle,
- })),
+ pieces: [
+ ...pieces.map((p) => ({
+ id: p.id,
+ title: p.title,
+ href: p.href,
+ kind: p.kind,
+ site: p.site,
+ stage: p.stage,
+ lifecycle: p.lifecycle,
+ })),
+ ...cases.map((c) => ({ id: c.piece, title: c.title, href: researchCaseHref(c.id), kind: "case", site: null, stage: "research", lifecycle: "active" })),
+ ],
},
{ headers: { "cache-control": "no-store" } },
);
diff --git a/umtool/app/api/research/cases/[id]/export.md/route.ts b/umtool/app/api/research/cases/[id]/export.md/route.ts
@@ -0,0 +1,26 @@
+import { exportCase } from "@/lib/research/boards";
+import { exportFileName } from "@/lib/research/board.mjs";
+import { fail } from "../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// The board as cited markdown in the house format (lib/research/board.mjs
+// exportMarkdown): `# title`, the summary, a `##` per section, one finding per
+// quote -- claim, "quote" — [title @ m:ss](link) -- and `## Coverage`. It
+// converts as a /sweep report. `?download=1` names it as a file.
+export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await ctx.params;
+ const { doc, markdown } = await exportCase(id);
+ const download = new URL(request.url).searchParams.get("download") === "1";
+ return new Response(markdown, {
+ headers: {
+ "content-type": "text/markdown; charset=utf-8",
+ "cache-control": "no-store",
+ ...(download ? { "content-disposition": `attachment; filename="${exportFileName(doc)}"` } : {}),
+ },
+ });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/cases/[id]/handoff/route.ts b/umtool/app/api/research/cases/[id]/handoff/route.ts
@@ -0,0 +1,35 @@
+import { CaseError } from "@/lib/research/cases.mjs";
+import { confirmArticle, confirmVideo, planArticle, planVideo } from "@/lib/research/handoff";
+import { fail, ok } from "../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// HAND-OFFS, plan then confirm (lib/research/handoff.ts; the API is
+// documented in ../../route.ts).
+// { to: "article", article?, model?, question? } -> { plan: ArticlePlan }
+// { to: "article", confirm: true, … } -> { href, jobId, iteration }
+// { to: "video", slug?, title? } -> { plan: VideoPlan }
+// { to: "video", confirm: true, … } -> { href }
+// An article is a seeded report-draft sweep the editor runs (it spends: the
+// plan says on what model, under which cap); a video is a project scaffolded
+// under the reports root (it writes one).
+export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await ctx.params;
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b || typeof b !== "object" || Array.isArray(b)) throw new CaseError('expected a JSON object: { to: "article" | "video", confirm? }');
+ const s = (k: string) => (typeof b[k] === "string" && (b[k] as string).trim() ? (b[k] as string).trim() : undefined);
+ const confirm = b.confirm === true;
+ if (b.to === "article") {
+ const over = { ...(s("article") ? { article: s("article") } : {}), ...(s("model") ? { model: s("model") } : {}), ...(s("question") ? { question: s("question") } : {}) };
+ return ok(confirm ? await confirmArticle(id, over) : { plan: (await planArticle(id, over)).plan });
+ }
+ if (b.to === "video") {
+ const over = { ...(s("slug") ? { slug: s("slug") } : {}), ...(s("title") ? { title: s("title") } : {}) };
+ return ok(confirm ? await confirmVideo(id, over) : { plan: await planVideo(id, over) });
+ }
+ throw new CaseError('to is "article" or "video"');
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/cases/[id]/quotes/[qid]/route.ts b/umtool/app/api/research/cases/[id]/quotes/[qid]/route.ts
@@ -0,0 +1,32 @@
+import { caseView, deleteQuote, patchQuote } from "@/lib/research/boards";
+import { CaseError } from "@/lib/research/cases.mjs";
+import { fail, ok } from "../../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// One quote of a case (the API is documented in ../../../route.ts).
+// PATCH { claim?, note?, section?, speakerChecked?, useCurrentWords? } -> { quote, case: CaseView }
+// DELETE -> { quote, index, case: CaseView }
+type Ctx = { params: Promise<{ id: string; qid: string }> };
+
+export async function PATCH(request: Request, ctx: Ctx) {
+ try {
+ const { id, qid } = await ctx.params;
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new CaseError("expected a JSON object: { claim?, note?, section?, speakerChecked?, useCurrentWords? }");
+ const r = await patchQuote(id, qid, body);
+ return ok({ quote: r.quote, case: await caseView(id) });
+ } catch (e) {
+ return fail(e);
+ }
+}
+
+export async function DELETE(_request: Request, ctx: Ctx) {
+ try {
+ const { id, qid } = await ctx.params;
+ const r = await deleteQuote(id, qid);
+ return ok({ quote: r.quote, index: r.index, case: await caseView(id) });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/cases/[id]/quotes/route.ts b/umtool/app/api/research/cases/[id]/quotes/route.ts
@@ -0,0 +1,46 @@
+import { caseView, pinQuote, type PinBody } from "@/lib/research/boards";
+import { CaseError } from "@/lib/research/cases.mjs";
+import { fail, ok } from "../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// PIN a cite to the case as a snapshot quote (the API is documented in
+// ../../route.ts): { source, channel, video, t, until?, track?, kind?, claim?,
+// note?, section?, search?, scope?, at? } -> { quote, duplicate, case: CaseView }
+export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await ctx.params;
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b || typeof b !== "object" || Array.isArray(b)) throw new CaseError("expected a JSON object: { source, channel, video, t, … }");
+ const s = (k: string) => (typeof b[k] === "string" && (b[k] as string).trim() ? (b[k] as string).trim() : undefined);
+ const source = s("source");
+ const channel = s("channel");
+ const video = s("video");
+ if (!source || !channel || !video) throw new CaseError("a pin names its source, channel and video");
+ const kind = b.kind === "post" ? "post" : "video";
+ const t = Number(b.t ?? 0);
+ if (!Number.isFinite(t) || t < 0) throw new CaseError("t is a second, 0 or more");
+ const until = b.until === undefined || b.until === null ? undefined : Number(b.until);
+ if (until !== undefined && (!Number.isFinite(until) || until < t)) throw new CaseError("until is a second at or after t");
+ const obj = (k: string) => (b[k] && typeof b[k] === "object" && !Array.isArray(b[k]) ? (b[k] as Record<string, unknown>) : undefined);
+ const body: PinBody = {
+ source,
+ channel,
+ video,
+ t,
+ kind,
+ ...(until !== undefined ? { until } : {}),
+ ...(s("track") ? { track: s("track") } : {}),
+ ...(typeof b.claim === "string" ? { claim: b.claim } : {}),
+ ...(typeof b.note === "string" ? { note: b.note } : {}),
+ ...(typeof b.section === "string" || b.section === null ? { section: b.section as string | null } : {}),
+ ...(obj("search") ? { search: obj("search") as PinBody["search"] } : {}),
+ ...(obj("scope") ? { scope: obj("scope") as PinBody["scope"] } : {}),
+ ...(Number.isInteger(b.at) ? { at: b.at as number } : {}),
+ };
+ const r = await pinQuote(id, body);
+ return ok({ quote: r.quote, duplicate: r.duplicate, case: await caseView(id) });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/cases/[id]/route.ts b/umtool/app/api/research/cases/[id]/route.ts
@@ -0,0 +1,29 @@
+import { caseView, patchCase } from "@/lib/research/boards";
+import { CaseError } from "@/lib/research/cases.mjs";
+import { fail, ok } from "../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// One case (the API is documented in ../route.ts).
+// GET -> CaseView
+// PATCH { title?, notes?, scope?, sections?, order? } -> CaseView
+export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await ctx.params;
+ return ok(await caseView(id));
+ } catch (e) {
+ return fail(e);
+ }
+}
+
+export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await ctx.params;
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new CaseError("expected a JSON object: { title?, notes?, scope?, sections?, order? }");
+ await patchCase(id, body);
+ return ok(await caseView(id));
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/cases/[id]/verify/route.ts b/umtool/app/api/research/cases/[id]/verify/route.ts
@@ -0,0 +1,20 @@
+import { caseView, verifyCase } from "@/lib/research/boards";
+import { fail, ok } from "../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// RE-VERIFY (the API is documented in ../../route.ts): every quote (or the
+// ones named) read again at its cite in the CURRENT transcript. Drifted or
+// missing is recorded with what is there now; a quote's own words never
+// change here. { quotes?: [qid] } -> { results: [{ id, verify }], case: CaseView }
+export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await ctx.params;
+ const body = (await request.json().catch(() => ({}))) as { quotes?: unknown } | null;
+ const only = Array.isArray(body?.quotes) ? body.quotes.filter((x): x is string => typeof x === "string") : undefined;
+ const r = await verifyCase(id, only);
+ return ok({ results: r.results, case: await caseView(id) });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/cases/route.ts b/umtool/app/api/research/cases/route.ts
@@ -0,0 +1,83 @@
+import { createCase, listCases } from "@/lib/research/boards";
+import { CaseError } from "@/lib/research/cases.mjs";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// ---------------------------------------------------------------------------
+// THE BOARD API (plans/umtool-redesign.md, R2). Research cases, umtool-side
+// under REPORTS_ROOT/.umtool/research/<case>/case.json (lib/research/cases.mjs)
+// -- never in the corpus. A case's piece id is `c:<case>`. P5's Create
+// consumes this; the shapes are lib/research/case-types.ts. Every answer is
+// JSON, `no-store`; an error is `{ error }` in words with its status (400 bad
+// input, 404 no such case or quote or recording, 409 a case.json that cannot
+// be read -- never overwritten -- or a name taken, 502 a corpus or the editor
+// that cannot be read).
+//
+// GET /api/research/cases
+// -> { cases: [{ id, piece, title, quotes, sections, updatedAt, scope, drifted, error? }] }
+// POST /api/research/cases { title?, id?, query?, scope?, notes? }
+// a case from a query and scope (the title defaults to the query),
+// or empty (a title); the id is the title's slug unless named
+// -> { case: CaseDoc }
+// GET /api/research/cases/<id>
+// -> CaseView { case, piece, stored, sourceLabel, reading, localOnly }
+// PATCH /api/research/cases/<id> { title?, notes?, scope?, sections?, order? }
+// sections: the whole ordered list [{ id?, title }] (no id = new;
+// left out = removed, its quotes to Unsorted); order: every quote
+// [{ id, section }] in board order -> CaseView
+// POST /api/research/cases/<id>/quotes
+// { source, channel, video, t, until?, track?, kind?, claim?, note?,
+// section?, search?, scope?, at? }
+// PIN: the cite is read from the corpus NOW and kept as a snapshot
+// (the words, the cite, the house-format citation); the same cite
+// twice answers the quote already there with `duplicate: true`.
+// `search` ({ session, query, total, complete, notReached,
+// sourceLabel }) makes that search's reading log the case's.
+// -> { quote, duplicate, case: CaseView }
+// PATCH /api/research/cases/<id>/quotes/<qid>
+// { claim?, note?, section?, speakerChecked?, useCurrentWords? }
+// useCurrentWords: true takes the words the last re-verify read
+// (only for a drifted quote; the old words kept in its history)
+// -> { quote, case: CaseView }
+// DELETE /api/research/cases/<id>/quotes/<qid>
+// -> { quote, index, case: CaseView } (POST it back with `at` to undo)
+// POST /api/research/cases/<id>/verify { quotes?: [qid] }
+// re-read every quote (or those) at its cite in the CURRENT
+// transcript (R1's window, ±30 s); drifted / missing with the words
+// there now, and en vs en-orig where both exist. Never changes a
+// quote's words. -> { results: [{ id, verify }], case: CaseView }
+// GET /api/research/cases/<id>/export.md[?download=1]
+// the board as cited markdown in the house format (text/markdown)
+// POST /api/research/cases/<id>/handoff { to: "article" | "video", confirm?, ... }
+// without confirm -> { plan } (ArticlePlan | VideoPlan; writes nothing)
+// with confirm: true -> { href } (article: { href, jobId, iteration })
+// article: { article?, model?, question? } video: { slug?, title? }
+// ---------------------------------------------------------------------------
+
+export async function GET() {
+ try {
+ return ok({ cases: await listCases() });
+ } catch (e) {
+ return fail(e);
+ }
+}
+
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new CaseError("expected a JSON object: { title?, id?, query?, scope?, notes? }");
+ const scope = body.scope && typeof body.scope === "object" && !Array.isArray(body.scope) ? (body.scope as Record<string, unknown>) : undefined;
+ return ok({
+ case: await createCase({
+ ...(typeof body.title === "string" ? { title: body.title } : {}),
+ ...(typeof body.id === "string" ? { id: body.id } : {}),
+ ...(typeof body.query === "string" ? { query: body.query } : {}),
+ ...(typeof body.notes === "string" ? { notes: body.notes } : {}),
+ ...(scope ? { scope } : {}),
+ }),
+ });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/research/[case]/page.tsx b/umtool/app/research/[case]/page.tsx
@@ -0,0 +1,46 @@
+import Link from "next/link";
+import AppHeader from "@/components/shell/AppHeader";
+import AppRail from "@/components/shell/AppRail";
+import BoardView from "@/components/research/BoardView";
+import { EmptyState } from "@/components/ui/empty-state";
+import { caseView } from "@/lib/research/boards";
+import { researchHref } from "@/lib/research/hrefs";
+import type { CaseView } from "@/lib/research/case-types";
+
+export const dynamic = "force-dynamic";
+
+// A RESEARCH BOARD (plans/umtool-redesign.md, R2; canvas "Research board"):
+// one case, umtool-side under REPORTS_ROOT/.umtool/research/<case>/. The
+// static segments beside it (archive, and R3's runs) win over this one, and
+// the case store reserves their names. The board is the client's
+// (components/research/BoardView.tsx); this reads the case for the first frame.
+export default async function CasePage({ params }: { params: Promise<{ case: string }> }) {
+ const { case: id } = await params;
+ let view: CaseView | null = null;
+ let error: { status: number; message: string } | null = null;
+ try {
+ view = await caseView(decodeURIComponent(id));
+ } catch (e) {
+ error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message };
+ }
+ return (
+ <div className="flex h-full flex-col">
+ <AppRail active="research" />
+ {view ? (
+ <BoardView initial={view} />
+ ) : (
+ <>
+ <AppHeader crumbs={[{ href: researchHref(), label: "research" }, { label: id }]} />
+ <div className="px-7 pt-6">
+ <EmptyState title={error?.status === 404 ? `No case “${id}”` : "This case cannot be read"}>
+ <span role="alert">{error?.message}</span>{" "}
+ <Link href={researchHref()} className="ink-link">
+ Research
+ </Link>
+ </EmptyState>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/app/research/page.tsx b/umtool/app/research/page.tsx
@@ -2,6 +2,7 @@ import Link from "next/link";
import AppShell from "@/components/shell/AppShell";
import ResearchView from "@/components/research/ResearchView";
import { buttonVariants } from "@/components/ui/button";
+import { listCases } from "@/lib/research/boards";
import { scopeFrom, scopeOf } from "@/lib/research/corpus";
import { researchArchiveHref } from "@/lib/research/hrefs";
import { listSources } from "@/lib/research/sources";
@@ -30,6 +31,9 @@ export default async function ResearchPage({ searchParams }: { searchParams: Pro
summaryError = (e as Error).message;
}
const q = typeof sp.q === "string" ? sp.q : "";
+ // R2: the cases a pin can go to, and the one the URL chose.
+ const cases = await listCases().catch(() => []);
+ const initialCase = typeof sp.case === "string" ? sp.case : null;
return (
<div className="flex h-full flex-col">
<AppShell
@@ -41,7 +45,15 @@ export default async function ResearchPage({ searchParams }: { searchParams: Pro
</Link>
}
/>
- <ResearchView sources={sources} initialQuery={q} initialScope={scope} initialSummary={summary} initialSummaryError={summaryError} />
+ <ResearchView
+ sources={sources}
+ initialQuery={q}
+ initialScope={scope}
+ initialSummary={summary}
+ initialSummaryError={summaryError}
+ initialCases={cases}
+ initialCase={initialCase}
+ />
</div>
);
}
diff --git a/umtool/components/VerdictRow.tsx b/umtool/components/VerdictRow.tsx
@@ -106,7 +106,7 @@ export default function VerdictRow({
data-verdict={c.verdict}
disabled={!ready}
onClick={() => onChoose(c)}
- className={`flex-1 rounded-md border px-4 py-3 text-left transition disabled:opacity-40 ${TONE[c.tone]}`}
+ className={`flex-1 rounded-md border px-4 py-3 text-left transition-[color,background-color,border-color,text-decoration-color,fill,stroke,opacity] disabled:opacity-40 ${TONE[c.tone]}`}
>
<div className="flex items-center gap-2">
<kbd>{c.key}</kbd>
diff --git a/umtool/components/projects/ProjectGrid.tsx b/umtool/components/projects/ProjectGrid.tsx
@@ -41,7 +41,7 @@ export default function ProjectGrid({
data-template={p.template}
data-state={p.state}
data-routing={p.routing}
- className="block overflow-hidden rounded border border-[var(--color-line)] bg-[var(--color-panel)] transition-colors hover:border-[var(--color-sel)]"
+ className="block overflow-hidden rounded border border-[var(--color-line)] bg-[var(--color-panel)] transition-[color,background-color,border-color,text-decoration-color,fill,stroke] hover:border-[var(--color-sel)]"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx
@@ -0,0 +1,596 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import AppHeader from "@/components/shell/AppHeader";
+import { buttonVariants } from "@/components/ui/button";
+import { Dialog } from "@/components/ui/dialog";
+import { EmptyState } from "@/components/ui/empty-state";
+import { KeyHint } from "@/components/ui/kbd";
+import { LitList, type LitDetail } from "@/components/ui/lit-list";
+import { LitActions, LitLine } from "@/components/ui/lit-line";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { groupsOf, moveQuote, moveSection, placeQuote } from "@/lib/research/board.mjs";
+import type { BoardGroup, CaseView, Quote } from "@/lib/research/case-types";
+import {
+ researchCaseApi,
+ researchCaseExportApi,
+ researchCaseQuoteApi,
+ researchCaseVerifyApi,
+ researchFromCaseHref,
+ researchHref,
+} from "@/lib/research/hrefs";
+import HandoffDialog from "./HandoffDialog";
+import QuoteSlip, { quoteLineId } from "./QuoteSlip";
+
+// ---------------------------------------------------------------------------
+// THE RESEARCH BOARD (plans/umtool-redesign.md, R2; canvas "Research board",
+// `#view-board`): a case's quotes as snapshot slips in sections and order,
+// our claim line and note under each, the flags, and the side panel -- the
+// hand-offs, the scope, what was searched and read, where it is stored.
+//
+// One lit list: section heads and quotes are its lines. Keys (never while
+// typing): j/k lines · alt+j/alt+k move the lit quote (across sections) or
+// section · e claim · n note · s speaker checked · m section · x remove ·
+// a add section · r rename (the lit section, else the case) · v re-verify ·
+// c copy as cited markdown · / search more. Drag a quote by its grip.
+//
+// Every change is the API's (app/api/research/cases/route.ts); the board
+// redraws from what it answers.
+// ---------------------------------------------------------------------------
+
+const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
+const sectionLineId = (sid: string | null) => `s:${sid ?? "unsorted"}`;
+
+async function call<T>(url: string, method: string, body?: unknown): Promise<T> {
+ const r = await fetch(url, {
+ method,
+ headers: { "content-type": "application/json" },
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null;
+ if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`);
+ return j as T;
+}
+
+function SectionHead({ g, lit, busy, onRename, onRemove, onDropTop }: { g: BoardGroup; lit: boolean; busy: boolean; onRename: () => void; onRemove: () => void; onDropTop: () => void }) {
+ const [over, setOver] = useState(false);
+ return (
+ <LitLine
+ id={sectionLineId(g.id)}
+ initial={lit}
+ data-section={g.id ?? ""}
+ aria-label={`Section: ${g.title}`}
+ onDragOver={(e) => {
+ if (!e.dataTransfer.types.includes("application/x-umtool-quote")) return;
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ onDropTop();
+ }}
+ className={`mb-2 flex items-baseline gap-2.5 border-b-0 pb-1.5 pt-3 ${over ? "shadow-[0_2px_0_var(--signal)]" : ""}`}
+ >
+ <h2 className="m-0 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted">{g.title}</h2>
+ <span className="font-mono text-[11.5px] text-meter">{g.quotes.length}</span>
+ {g.id !== null && (
+ <LitActions className="ml-auto">
+ <button type="button" disabled={busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={onRename}>
+ Rename
+ </button>
+ <button type="button" disabled={busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={onRemove}>
+ Remove section
+ </button>
+ </LitActions>
+ )}
+ </LitLine>
+ );
+}
+
+type Ask =
+ | { kind: "add-section" }
+ | { kind: "rename-section"; sid: string; title: string }
+ | { kind: "remove-section"; sid: string; title: string; n: number }
+ | { kind: "rename-case" }
+ | { kind: "remove-quote"; q: Quote };
+
+export default function BoardView({ initial }: { initial: CaseView }) {
+ const router = useRouter();
+ const hydrated = useHydrated();
+ const [view, setView] = useState<CaseView>(initial);
+ const [busy, setBusy] = useState(false);
+ const [status, setStatus] = useState<{ text: string; href?: string; tone?: "error" } | null>(null);
+ const [litId, setLitId] = useState<string | null>(null);
+ const [listKey, setListKey] = useState(0);
+ const [ask, setAsk] = useState<Ask | null>(null);
+ const [askText, setAskText] = useState("");
+ const [handoff, setHandoff] = useState<"article" | "video" | null>(null);
+ const [notes, setNotes] = useState(initial.case.notes);
+ const dragging = useRef<string | null>(null);
+ const doc = view.case;
+ const groups = useMemo(() => groupsOf(doc) as unknown as BoardGroup[], [doc]);
+ const byId = useMemo(() => new Map(doc.quotes.map((q) => [q.id, q])), [doc]);
+ const litQuote = litId?.startsWith("q:") ? (byId.get(litId.slice(2)) ?? null) : null;
+ const litSection = litId?.startsWith("s:") && litId !== "s:unsorted" ? (doc.sections.find((s) => s.id === litId.slice(2)) ?? null) : null;
+
+ const say = (text: string, extra: { href?: string; tone?: "error" } = {}) => setStatus({ text, ...extra });
+ const fail = (e: unknown) => say((e as Error).message, { tone: "error" });
+
+ // After a move, the moved line keeps the light (the list is redrawn).
+ const refocus = useRef<string | null>(null);
+ useEffect(() => {
+ const id = refocus.current;
+ if (!id) return;
+ refocus.current = null;
+ const el = document.querySelector<HTMLElement>(`[data-lit-id="${CSS.escape(id)}"]`);
+ el?.focus({ preventScroll: true });
+ el?.scrollIntoView({ block: "nearest" });
+ }, [listKey]);
+
+ const arrange = useCallback(
+ async (next: { sections: unknown; order: unknown } | null, keep: string | null) => {
+ if (!next) return;
+ setBusy(true);
+ try {
+ const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", next);
+ refocus.current = keep;
+ if (keep) setLitId(keep);
+ setView(v);
+ setListKey((k) => k + 1);
+ } catch (e) {
+ fail(e);
+ } finally {
+ setBusy(false);
+ }
+ },
+ [doc.id],
+ );
+
+ const patchQuote = useCallback(
+ async (qid: string, body: Record<string, unknown>) => {
+ setBusy(true);
+ try {
+ const r = await call<{ case: CaseView }>(researchCaseQuoteApi(doc.id, qid), "PATCH", body);
+ setView(r.case);
+ if ("section" in body) {
+ refocus.current = quoteLineId(qid);
+ setListKey((k) => k + 1);
+ }
+ if (body.useCurrentWords) say("The quote now has the transcript's current words; the old ones are kept in its history.");
+ } catch (e) {
+ fail(e);
+ } finally {
+ setBusy(false);
+ }
+ },
+ [doc.id],
+ );
+
+ const patchCase = useCallback(
+ async (body: Record<string, unknown>, keep: string | null = null) => {
+ setBusy(true);
+ try {
+ const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", body);
+ setView(v);
+ if (body.sections) {
+ refocus.current = keep;
+ setListKey((k) => k + 1);
+ }
+ return v;
+ } catch (e) {
+ fail(e);
+ return null;
+ } finally {
+ setBusy(false);
+ }
+ },
+ [doc.id],
+ );
+
+ const verify = useCallback(async () => {
+ setBusy(true);
+ say("Re-reading every quote at its cite…");
+ try {
+ const r = await call<{ results: { id: string; verify: { status: string; enOrig?: unknown } }[]; case: CaseView }>(researchCaseVerifyApi(doc.id), "POST", {});
+ setView(r.case);
+ const n = (s: string) => r.results.filter((x) => x.verify.status === s).length;
+ const en = r.results.filter((x) => x.verify.enOrig).length;
+ say(
+ `Re-verified ${r.results.length}: ${n("ok")} as pinned, ${n("drifted")} drifted, ${n("missing")} missing` +
+ (n("unreadable") ? `, ${n("unreadable")} not readable` : "") +
+ (en ? `; en-orig differs at ${en}` : ""),
+ );
+ } catch (e) {
+ fail(e);
+ } finally {
+ setBusy(false);
+ }
+ }, [doc.id]);
+
+ const copyMarkdown = useCallback(async () => {
+ try {
+ const r = await fetch(researchCaseExportApi(doc.id), { cache: "no-store" });
+ if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `HTTP ${r.status}`);
+ const md = await r.text();
+ try {
+ await navigator.clipboard.writeText(md);
+ say(`Copied the board as cited markdown (${md.split("\n").length} lines)`);
+ } catch {
+ window.prompt("Copy the board's markdown", md);
+ }
+ } catch (e) {
+ fail(e);
+ }
+ }, [doc.id]);
+
+ const removeQuote = useCallback(
+ async (q: Quote) => {
+ setBusy(true);
+ try {
+ const r = await call<{ case: CaseView }>(researchCaseQuoteApi(doc.id, q.id), "DELETE");
+ setView(r.case);
+ setListKey((k) => k + 1);
+ say(`Removed “${q.text.slice(0, 60)}${q.text.length > 60 ? "…" : ""}”`);
+ } catch (e) {
+ fail(e);
+ } finally {
+ setBusy(false);
+ }
+ },
+ [doc.id],
+ );
+
+ const openAsk = (a: Ask) => {
+ setAsk(a);
+ setAskText(a.kind === "rename-section" ? a.title : a.kind === "rename-case" ? doc.title : "");
+ };
+
+ const submitAsk = async () => {
+ const a = ask;
+ if (!a) return;
+ const t = askText.trim();
+ setAsk(null);
+ if (a.kind === "add-section" && t) {
+ const v = await patchCase({ sections: [...doc.sections, { title: t }] });
+ const added = v?.case.sections.at(-1);
+ if (added) {
+ refocus.current = sectionLineId(added.id);
+ setLitId(sectionLineId(added.id));
+ setListKey((k) => k + 1);
+ }
+ } else if (a.kind === "rename-section" && t) {
+ await patchCase({ sections: doc.sections.map((s) => (s.id === a.sid ? { id: s.id, title: t } : s)) }, sectionLineId(a.sid));
+ } else if (a.kind === "remove-section") {
+ await patchCase({ sections: doc.sections.filter((s) => s.id !== a.sid) }, sectionLineId(null));
+ } else if (a.kind === "rename-case" && t) {
+ await patchCase({ title: t });
+ } else if (a.kind === "remove-quote") {
+ await removeQuote(a.q);
+ }
+ };
+
+ const onDropOn = (target: string, after: boolean) => {
+ const qid = dragging.current;
+ dragging.current = null;
+ if (!qid || qid === target) return;
+ const t = byId.get(target);
+ if (!t) return;
+ const g = groups.find((x) => x.quotes.some((q) => q.id === target))!;
+ const without = g.quotes.filter((q) => q.id !== qid);
+ const at = without.findIndex((q) => q.id === target) + (after ? 1 : 0);
+ void arrange(placeQuote(doc, qid, g.id, at), quoteLineId(qid));
+ };
+
+ // ── keys ──
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey) return;
+ if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return;
+ if (document.querySelector("dialog[open]")) return;
+ if (e.altKey) {
+ const dir = e.code === "KeyJ" || e.key === "ArrowDown" ? 1 : e.code === "KeyK" || e.key === "ArrowUp" ? -1 : 0;
+ if (!dir || busy) return;
+ e.preventDefault();
+ if (litQuote) void arrange(moveQuote(doc, litQuote.id, dir), quoteLineId(litQuote.id));
+ else if (litSection) void arrange(moveSection(doc, litSection.id, dir), sectionLineId(litSection.id));
+ return;
+ }
+ const focusField = (f: string) => {
+ if (!litQuote) return;
+ const el = document.querySelector<HTMLElement>(`[data-quote="${litQuote.id}"] [data-field="${f}"]`);
+ if (el) {
+ e.preventDefault();
+ el.focus();
+ }
+ };
+ switch (e.key) {
+ case "e":
+ focusField("claim");
+ break;
+ case "n":
+ focusField("note");
+ break;
+ case "m":
+ focusField("section");
+ break;
+ case "s":
+ if (litQuote && litQuote.cite.kind !== "post") void patchQuote(litQuote.id, { speakerChecked: !litQuote.speakerChecked });
+ break;
+ case "x":
+ case "Delete":
+ if (litQuote) openAsk({ kind: "remove-quote", q: litQuote });
+ break;
+ case "a":
+ e.preventDefault();
+ openAsk({ kind: "add-section" });
+ break;
+ case "r":
+ e.preventDefault();
+ if (litSection) openAsk({ kind: "rename-section", sid: litSection.id, title: litSection.title });
+ else openAsk({ kind: "rename-case" });
+ break;
+ case "v":
+ if (!busy) void verify();
+ break;
+ case "c":
+ void copyMarkdown();
+ break;
+ case "/":
+ e.preventDefault();
+ router.push(researchFromCaseHref(doc));
+ break;
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ });
+
+ const onLight = useCallback((d: LitDetail) => setLitId(d.id), []);
+
+ const s = doc.scope;
+ const where = view.sourceLabel ?? (s.source ? s.source.replace(/^(local|remote|hub):/, "") : "no source yet");
+ const scopeLine = [where, s.channels?.length ? `${s.channels.length} ${s.channels.length === 1 ? "channel" : "channels"}` : "all channels", s.dateFrom || s.dateTo ? `${s.dateFrom ?? "…"} – ${s.dateTo ?? "…"}` : ""].filter(Boolean).join(" · ");
+ const se = doc.search;
+ const meta = [
+ `${doc.quotes.length} ${doc.quotes.length === 1 ? "quote" : "quotes"}`,
+ `${doc.sections.length} ${doc.sections.length === 1 ? "section" : "sections"}`,
+ s.query ? `from “${s.query}”` : "",
+ view.sourceLabel ?? "",
+ ]
+ .filter(Boolean)
+ .join(" · ");
+ const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
+
+ return (
+ <>
+ <AppHeader
+ crumbs={[{ href: researchHref(), label: "research" }, { label: doc.title }]}
+ meta={
+ <>
+ <span className="micro mr-2">Research · case</span>
+ <span data-board-meta="">{meta}</span>
+ {drifted > 0 && <span className="ml-2 text-doubt-text">· {drifted} drifted or missing</span>}
+ </>
+ }
+ actions={
+ <>
+ <button type="button" disabled={!hydrated || busy || !doc.quotes.length} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={verify}>
+ Re-verify quotes <kbd>v</kbd>
+ </button>
+ <button type="button" disabled={!hydrated || !doc.quotes.length} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={copyMarkdown}>
+ Copy as cited markdown <kbd>c</kbd>
+ </button>
+ <a href={researchCaseExportApi(doc.id, { download: true })} download className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Download .md
+ </a>
+ </>
+ }
+ />
+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_300px]">
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2">
+ {doc.quotes.length === 0 && doc.sections.length === 0 ? (
+ <EmptyState title="No quotes on this board yet">
+ <Link prefetch={false} href={researchFromCaseHref(doc)} className="ink-link">
+ Search and pin to it
+ </Link>
+ </EmptyState>
+ ) : (
+ <LitList key={listKey} label="Board" global onLight={onLight}>
+ {groups.map((g) => (
+ <section key={g.id ?? "unsorted"} data-group={g.id ?? ""}>
+ <SectionHead
+ g={g}
+ lit={litId === sectionLineId(g.id)}
+ busy={busy}
+ onRename={() => g.id && openAsk({ kind: "rename-section", sid: g.id, title: g.title })}
+ onRemove={() => g.id && openAsk({ kind: "remove-section", sid: g.id, title: g.title, n: g.quotes.length })}
+ onDropTop={() => {
+ const qid = dragging.current;
+ dragging.current = null;
+ if (qid) void arrange(placeQuote(doc, qid, g.id, 0), quoteLineId(qid));
+ }}
+ />
+ {g.quotes.map((q) => (
+ <QuoteSlip
+ key={q.id}
+ q={q}
+ sections={doc.sections}
+ lit={litId === quoteLineId(q.id)}
+ busy={busy}
+ onPatch={(body) => void patchQuote(q.id, body)}
+ onRemove={() => openAsk({ kind: "remove-quote", q })}
+ onDragStart={(id) => (dragging.current = id)}
+ onDropOn={onDropOn}
+ />
+ ))}
+ {g.quotes.length === 0 && <p className="mb-3 pl-5 text-[12px] text-muted-2">Empty: move a quote here with alt+j/k, its Section menu, or a drag.</p>}
+ </section>
+ ))}
+ </LitList>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-seam px-7 py-2 text-[11.5px] text-muted-2">
+ <KeyHint keys={["j", "k"]}>line</KeyHint>
+ <KeyHint keys={["alt+j", "alt+k"]}>move</KeyHint>
+ <KeyHint keys={["e"]}>claim</KeyHint>
+ <KeyHint keys={["n"]}>note</KeyHint>
+ <KeyHint keys={["s"]}>speaker</KeyHint>
+ <KeyHint keys={["m"]}>section</KeyHint>
+ <KeyHint keys={["a"]}>add section</KeyHint>
+ <KeyHint keys={["r"]}>rename</KeyHint>
+ <KeyHint keys={["x"]}>remove</KeyHint>
+ <KeyHint keys={["/"]}>search more</KeyHint>
+ {status && (
+ <span role={status.tone === "error" ? "alert" : "status"} data-board-status="" className={`ml-auto text-[12px] ${status.tone === "error" ? "text-reject-text" : "text-text-2"}`}>
+ {status.text}
+ {status.href && (
+ <>
+ {" · "}
+ <Link prefetch={false} href={status.href} className="ink-link">
+ Open
+ </Link>
+ </>
+ )}
+ </span>
+ )}
+ </div>
+ </div>
+
+ <aside aria-label="Case" className="grid min-h-0 content-start gap-[18px] overflow-auto border-l border-seam bg-panel px-[22px] py-[18px]">
+ <div>
+ <span className="micro">Hand off</span>
+ <div className="mt-2 grid gap-2">
+ <button type="button" disabled={!hydrated || !doc.quotes.length} className={`${buttonVariants({ variant: "go" })} justify-start`} onClick={() => setHandoff("article")}>
+ Draft an article from this board
+ </button>
+ <button type="button" disabled={!hydrated || !doc.quotes.length} className={`${buttonVariants({ variant: "outline" })} justify-start`} onClick={() => setHandoff("video")}>
+ Start a video from this board
+ </button>
+ </div>
+ {view.localOnly > 0 && <p className="mt-2 text-[12px] text-doubt-text">{view.localOnly} local-only: no article (it could be published); a video stays local.</p>}
+ </div>
+ <dl data-case-facts="" className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3.5 gap-y-1.5 text-[12.5px]">
+ <dt className="text-muted">Scope</dt>
+ <dd className="m-0 text-text-2">{scopeLine}</dd>
+ <dt className="text-muted">Searched</dt>
+ <dd className="m-0 text-text-2" data-searched="">
+ {se ? `${se.total.toLocaleString("en-US")} ${se.total === 1 ? "recording" : "recordings"}, ${se.complete ? "complete" : "partial"}` : "nothing yet"}
+ </dd>
+ <dt className="text-muted">Read</dt>
+ <dd className="m-0 font-mono text-meter" data-read="">
+ {se && view.reading ? `${view.reading.read} of ${se.total.toLocaleString("en-US")}` : "—"}
+ </dd>
+ <dt className="text-muted">Stored</dt>
+ <dd className="m-0 break-all font-mono text-[11px] text-text-2">{view.stored}</dd>
+ <dt className="text-muted">Piece</dt>
+ <dd className="m-0 font-mono text-[11px] text-text-2">{view.piece}</dd>
+ </dl>
+ <div className="grid gap-1.5">
+ <Link prefetch={false} href={researchFromCaseHref(doc)} className={`${buttonVariants({ variant: "outline", size: "sm" })} justify-self-start`}>
+ Search and pin more <kbd>/</kbd>
+ </Link>
+ <button type="button" disabled={!hydrated || busy} className={`${buttonVariants({ variant: "quiet", size: "sm" })} justify-self-start`} onClick={() => openAsk({ kind: "add-section" })}>
+ + Section <kbd>a</kbd>
+ </button>
+ </div>
+ <label className="grid gap-1 text-[12px]">
+ <span className="micro">Notes</span>
+ <textarea
+ aria-label="Case notes"
+ value={notes}
+ rows={4}
+ onChange={(e) => setNotes(e.target.value)}
+ onBlur={() => notes !== doc.notes && void patchCase({ notes })}
+ placeholder="What this case is about; the export's summary"
+ className="resize-y rounded-[3px] border border-seam-2 bg-ground px-2 py-1.5 text-[12.5px] text-text outline-none placeholder:text-muted-2 focus:border-muted"
+ />
+ </label>
+ {doc.handoffs.length > 0 && (
+ <div className="grid gap-1 text-[12px]">
+ <span className="micro">Made from it</span>
+ {doc.handoffs.map((h, i) => (
+ <Link prefetch={false} key={`${h.href}-${i}`} href={h.href} className="ink-link">
+ {h.to === "article" ? "Article" : "Video"} · {h.what ?? h.href} · {h.at.slice(0, 10)}
+ </Link>
+ ))}
+ </div>
+ )}
+ <p className="m-0 text-[12px] text-muted">A board is umtool-side state; nothing here writes to the corpus.</p>
+ </aside>
+ </div>
+
+ <Dialog
+ open={ask !== null}
+ onClose={() => setAsk(null)}
+ title={
+ ask?.kind === "add-section"
+ ? "Add a section"
+ : ask?.kind === "rename-section"
+ ? "Rename the section"
+ : ask?.kind === "remove-section"
+ ? "Remove the section"
+ : ask?.kind === "rename-case"
+ ? "Rename the case"
+ : "Remove the quote"
+ }
+ >
+ <form
+ className="grid gap-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void submitAsk();
+ }}
+ >
+ {ask?.kind === "remove-quote" ? (
+ <p className="m-0 text-[13px] text-text-2">
+ Remove <span className="font-serif text-text">“{ask.q.text.slice(0, 140)}”</span> from the board? Its claim and note go with it; the transcript is not touched.
+ </p>
+ ) : ask?.kind === "remove-section" ? (
+ <p className="m-0 text-[13px] text-text-2">
+ Remove “{ask.title}”? {ask.n ? `Its ${ask.n} ${ask.n === 1 ? "quote goes" : "quotes go"} to Unsorted.` : "It holds no quotes."}
+ </p>
+ ) : (
+ <input
+ autoFocus
+ aria-label="Title"
+ value={askText}
+ maxLength={120}
+ onChange={(e) => setAskText(e.target.value)}
+ className="rounded-[3px] border border-seam-2 bg-ground px-2.5 py-1.5 text-[13.5px] text-text outline-none focus:border-muted"
+ />
+ )}
+ <div className="flex justify-end gap-2">
+ <button type="button" className={buttonVariants({ variant: "quiet" })} onClick={() => setAsk(null)}>
+ Cancel
+ </button>
+ <button
+ type="submit"
+ data-confirm=""
+ disabled={ask?.kind !== "remove-quote" && ask?.kind !== "remove-section" && !askText.trim()}
+ className={buttonVariants({ variant: ask?.kind === "remove-quote" || ask?.kind === "remove-section" ? "destructive" : "go" })}
+ >
+ {ask?.kind === "add-section" ? "Add section" : ask?.kind === "remove-quote" ? "Remove quote" : ask?.kind === "remove-section" ? "Remove section" : "Rename"}
+ </button>
+ </div>
+ </form>
+ </Dialog>
+
+ <HandoffDialog
+ caseId={doc.id}
+ to={handoff}
+ onClose={() => setHandoff(null)}
+ onDone={(href, what) => {
+ setHandoff(null);
+ say(what, { href });
+ void call<CaseView>(researchCaseApi(doc.id), "GET").then(setView, () => {});
+ }}
+ />
+ </>
+ );
+}
diff --git a/umtool/components/research/HandoffDialog.tsx b/umtool/components/research/HandoffDialog.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { Dialog } from "@/components/ui/dialog";
+import { researchCaseHandoffApi } from "@/lib/research/hrefs";
+import type { ArticlePlan, HandoffPlan, VideoPlan } from "@/lib/research/case-types";
+
+// ---------------------------------------------------------------------------
+// A HAND-OFF from the board, plan then confirm (lib/research/handoff.ts): the
+// plan is read when the dialog opens and nothing is written until the one
+// button that names what it does is pressed. An article spends money (the
+// model and its cap are on the plan); a video writes a project.
+// ---------------------------------------------------------------------------
+
+async function post<T>(url: string, body: unknown): Promise<T> {
+ const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null;
+ if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`);
+ return j as T;
+}
+
+function Row({ k, children }: { k: string; children: React.ReactNode }) {
+ return (
+ <>
+ <dt className="text-muted">{k}</dt>
+ <dd className="m-0 min-w-0 break-words text-text-2">{children}</dd>
+ </>
+ );
+}
+
+function ArticleBody({ p }: { p: ArticlePlan }) {
+ return (
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-[12.5px]">
+ <Row k="Article">
+ <span className="font-mono">{p.article}</span> {p.articleExists ? "(exists: a new iteration)" : "(new, in the making)"}
+ </Row>
+ <Row k="Question">{p.question}</Row>
+ <Row k="Channels">{p.channels.join(", ") || "—"}</Row>
+ {(p.dateFrom || p.dateTo) && (
+ <Row k="Dates">
+ {p.dateFrom ?? "…"} – {p.dateTo ?? "…"}
+ </Row>
+ )}
+ <Row k="Seed">
+ the board as cited markdown: {p.seed.quotes} {p.seed.quotes === 1 ? "quote" : "quotes"}, {p.seed.chars.toLocaleString("en-US")} characters
+ </Row>
+ <Row k="Runs on">
+ {p.model ? <span className="font-mono">{p.model}</span> : "the editor cannot be asked"}
+ {p.capUsd !== null ? (
+ <>
+ {" "}
+ · spends up to <span className="font-mono text-meter">${p.capUsd.toFixed(2)}</span>
+ </>
+ ) : null}
+ </Row>
+ </dl>
+ );
+}
+
+function VideoBody({ p }: { p: VideoPlan }) {
+ return (
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-[12.5px]">
+ <Row k="Project">
+ <span className="font-mono">{p.slug}</span>
+ </Row>
+ <Row k="Title">{p.title}</Row>
+ <Row k="Clips">
+ {p.clips.length} — each the cue span of a pinned quote
+ <ol className="mt-1 max-h-[160px] list-none overflow-auto p-0 font-mono text-[11px] text-muted-2">
+ {p.clips.map((c) => (
+ <li key={c.id} className="truncate">
+ {c.id} {c.channel}/{c.video} {c.start}–{c.end} “{c.quote}”
+ </li>
+ ))}
+ </ol>
+ </Row>
+ <Row k="Origin">{p.siteOrigin ? <span className="font-mono">{p.siteOrigin}</span> : "not set"}</Row>
+ <Row k="Writes">
+ <span className="font-mono">{p.writes}</span>
+ </Row>
+ </dl>
+ );
+}
+
+export default function HandoffDialog({
+ caseId,
+ to,
+ onClose,
+ onDone,
+}: {
+ caseId: string;
+ to: "article" | "video" | null;
+ onClose: () => void;
+ onDone: (href: string, what: string) => void;
+}) {
+ const [plan, setPlan] = useState<HandoffPlan | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [working, setWorking] = useState(false);
+ useEffect(() => {
+ setPlan(null);
+ setError(null);
+ if (!to) return;
+ let live = true;
+ post<{ plan: HandoffPlan }>(researchCaseHandoffApi(caseId), { to })
+ .then((r) => live && setPlan(r.plan))
+ .catch((e: Error) => live && setError(e.message));
+ return () => {
+ live = false;
+ };
+ }, [caseId, to]);
+
+ const confirm = async () => {
+ if (!plan) return;
+ setWorking(true);
+ setError(null);
+ try {
+ const r = await post<{ href: string }>(researchCaseHandoffApi(caseId), { to, confirm: true, ...(plan.to === "article" ? { article: plan.article } : { slug: plan.slug }) });
+ onDone(r.href, plan.to === "article" ? `The sweep for ${plan.article} is queued` : `Project ${plan.slug} written`);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setWorking(false);
+ }
+ };
+
+ const title = to === "article" ? "Draft an article from this board" : "Start a video from this board";
+ const blocked = !plan || plan.refusals.length > 0 || (plan.to === "article" && !!plan.policyError);
+ return (
+ <Dialog open={to !== null} onClose={onClose} title={title} data-handoff={to ?? ""}>
+ {!plan && !error && (
+ <p role="status" className="text-[12.5px] text-text-2">
+ Reading the plan…
+ </p>
+ )}
+ {plan && (plan.to === "article" ? <ArticleBody p={plan} /> : <VideoBody p={plan} />)}
+ {plan && plan.refusals.length > 0 && (
+ <ul data-refusals="" className="mt-3 grid list-none gap-1 p-0 text-[12.5px] text-reject-text">
+ {plan.refusals.map((r) => (
+ <li key={r}>{r}</li>
+ ))}
+ </ul>
+ )}
+ {plan && plan.to === "article" && plan.policyError && <p className="mt-3 text-[12.5px] text-reject-text">The editor: {plan.policyError}</p>}
+ {plan && plan.warnings.length > 0 && (
+ <ul data-warnings="" className="mt-3 grid list-none gap-1 p-0 text-[12px] text-doubt-text">
+ {plan.warnings.map((w) => (
+ <li key={w}>{w}</li>
+ ))}
+ </ul>
+ )}
+ {error && (
+ <p role="alert" className="mt-3 text-[12.5px] text-reject-text">
+ {error}
+ </p>
+ )}
+ <div className="mt-4 flex items-center justify-end gap-2">
+ <button type="button" className={buttonVariants({ variant: "quiet" })} onClick={onClose}>
+ Cancel
+ </button>
+ <button type="button" data-confirm="" disabled={blocked || working} className={buttonVariants({ variant: "go" })} onClick={confirm}>
+ {working ? "Working…" : plan?.to === "article" ? `Start the sweep${plan.capUsd !== null ? ` (up to $${plan.capUsd.toFixed(2)})` : ""}` : "Create the project"}
+ </button>
+ </div>
+ </Dialog>
+ );
+}
diff --git a/umtool/components/research/PinTarget.tsx b/umtool/components/research/PinTarget.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { Dialog } from "@/components/ui/dialog";
+import { LitGroup, LitLine } from "@/components/ui/lit-line";
+import { LitList } from "@/components/ui/lit-list";
+import { researchCaseHref } from "@/lib/research/hrefs";
+import type { CaseSummary } from "@/lib/research/case-types";
+
+// ---------------------------------------------------------------------------
+// WHERE A PIN GOES, on the Research page (R2): the board chooser beside the
+// ask bar, the dialog that asks when nothing is chosen (an existing case, or a
+// new one named for the query), and the Cases list the page shows before a
+// search.
+// ---------------------------------------------------------------------------
+
+export function BoardChooser({
+ cases,
+ value,
+ disabled,
+ onChange,
+ onNew,
+}: {
+ cases: CaseSummary[];
+ value: string | null;
+ disabled: boolean;
+ onChange: (id: string | null) => void;
+ onNew: () => void;
+}) {
+ const current = cases.find((c) => c.id === value);
+ return (
+ <span className="flex items-center gap-1.5">
+ <select
+ id="pin-board"
+ aria-label="Board"
+ title="The board a pin (p) goes to"
+ value={value ?? ""}
+ disabled={disabled}
+ onChange={(e) => {
+ if (e.target.value === "+new") onNew();
+ else onChange(e.target.value || null);
+ }}
+ className="max-w-[12rem] rounded-[3px] border border-seam-2 bg-panel px-2 py-[5px] text-[12.5px] text-text"
+ >
+ <option value="">Board: ask on pin</option>
+ {cases.map((c) => (
+ <option key={c.id} value={c.id}>
+ Board: {c.title} ({c.quotes})
+ </option>
+ ))}
+ <option value="+new">New case…</option>
+ </select>
+ {current && (
+ <Link href={researchCaseHref(current.id)} prefetch={false} className="ink-link text-[12px]">
+ Open
+ </Link>
+ )}
+ </span>
+ );
+}
+
+export function PinDialog({
+ open,
+ mode,
+ cases,
+ query,
+ error,
+ working,
+ onPick,
+ onCreate,
+ onClose,
+}: {
+ open: boolean;
+ /** "pin": a pin is waiting for its board; "new": only name a new case. */
+ mode: "pin" | "new";
+ cases: CaseSummary[];
+ query: string;
+ error: string | null;
+ working: boolean;
+ onPick: (id: string) => void;
+ onCreate: (title: string) => void;
+ onClose: () => void;
+}) {
+ const [title, setTitle] = useState(query);
+ useEffect(() => {
+ if (open) setTitle(query);
+ }, [open, query]);
+ return (
+ <Dialog open={open} onClose={onClose} title={mode === "pin" ? "Pin to which board?" : "New case"} data-pin-dialog="">
+ <form
+ className="flex items-center gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (title.trim()) onCreate(title.trim());
+ }}
+ >
+ <input
+ autoFocus
+ aria-label="New case title"
+ value={title}
+ maxLength={120}
+ onChange={(e) => setTitle(e.target.value)}
+ placeholder="A new case's title"
+ className="min-w-0 flex-1 rounded-[3px] border border-seam-2 bg-ground px-2.5 py-1.5 text-[13.5px] text-text outline-none focus:border-muted"
+ />
+ <button type="submit" disabled={working || !title.trim()} className={buttonVariants({ variant: "go" })}>
+ {mode === "pin" ? "New case and pin" : "Create case"}
+ </button>
+ </form>
+ {cases.length > 0 && (
+ <div className="mt-3 grid max-h-[40vh] gap-1 overflow-auto">
+ <span className="micro">Or an open case</span>
+ {cases.map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ disabled={working}
+ onClick={() => onPick(c.id)}
+ className="flex items-baseline gap-2.5 rounded-[3px] border border-seam px-2.5 py-1.5 text-left text-[13px] text-text hover:border-muted hover:bg-panel-2"
+ >
+ <span className="min-w-0 flex-1 truncate">{c.title}</span>
+ <span className="font-mono text-[11px] text-meter">{c.quotes}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ {error && (
+ <p role="alert" className="mt-3 text-[12.5px] text-reject-text">
+ {error}
+ </p>
+ )}
+ </Dialog>
+ );
+}
+
+/** The cases, before a search (canvas: Research's Cases). */
+export function CaseList({ cases }: { cases: CaseSummary[] }) {
+ if (!cases.length) return null;
+ return (
+ <LitList label="Cases" className="mt-6 max-w-[860px]">
+ <LitGroup title="Cases" count={cases.length} note="pin a hit with p to put it on the chosen board">
+ {cases.map((c) => (
+ <LitLine key={c.id} id={c.id} data-case={c.id} className="grid grid-cols-[minmax(0,1fr)_auto_auto] items-baseline gap-x-4 text-[13px]">
+ <Link href={researchCaseHref(c.id)} prefetch={false} className="min-w-0 truncate text-inherit hover:underline">
+ {c.title}
+ {c.error && <span className="ml-2 text-[12px] text-reject-text">{c.error}</span>}
+ </Link>
+ <span className="whitespace-nowrap font-mono text-[11.5px] text-meter">
+ {c.quotes} {c.quotes === 1 ? "quote" : "quotes"} · {c.sections} {c.sections === 1 ? "section" : "sections"}
+ {c.drifted ? <span className="text-doubt-text"> · {c.drifted} drifted</span> : null}
+ </span>
+ <span className="whitespace-nowrap font-mono text-[11px] text-muted-2">{c.updatedAt.slice(0, 10)}</span>
+ </LitLine>
+ ))}
+ </LitGroup>
+ </LitList>
+ );
+}
diff --git a/umtool/components/research/QuoteSlip.tsx b/umtool/components/research/QuoteSlip.tsx
@@ -0,0 +1,274 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { LitLine, LitOnly } from "@/components/ui/lit-line";
+import { isoDate } from "@/lib/research/facets.mjs";
+import type { CaseSection, Quote } from "@/lib/research/case-types";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// One QUOTE on the board (canvas `.quote`): the words on the reader surface
+// (a slip: verbatim, the source's), its cite in mono under them; then on the
+// desk what is OURS -- the claim line, the note, the flags (speaker not
+// checked; drifted, missing, en-orig differs) and what the last re-verify
+// read. Paper is the record, ink is our work: a quote is never styled as our
+// claim, nor our claim as a quote.
+//
+// The claim and the note are edited in place: Enter or leaving the field
+// saves, Escape puts it back. The line is a lit line of the board's list; its
+// grip drags it.
+// ---------------------------------------------------------------------------
+
+const TRACK: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "", post: "post" };
+
+export const quoteLineId = (qid: string) => `q:${qid}`;
+
+function InlineField({
+ label,
+ value,
+ placeholder,
+ onSave,
+ field,
+ className,
+ max,
+ tabbable,
+}: {
+ /** In the Tab order only on the lit quote (e and n reach it from the keys). */
+ tabbable: boolean;
+ label: string;
+ value: string;
+ placeholder: string;
+ onSave: (v: string) => void;
+ field: "claim" | "note";
+ className?: string;
+ max: number;
+}) {
+ const [v, setV] = useState(value);
+ const ref = useRef<HTMLInputElement>(null);
+ // Enter saved it already: the blur that follows (focus back to the line) does not again.
+ const done = useRef(false);
+ useEffect(() => setV(value), [value]);
+ const back = () => ref.current?.closest<HTMLElement>("[data-lit-line]")?.focus({ preventScroll: true });
+ return (
+ <input
+ ref={ref}
+ data-field={field}
+ aria-label={label}
+ tabIndex={tabbable ? 0 : -1}
+ value={v}
+ maxLength={max}
+ placeholder={placeholder}
+ spellCheck
+ onChange={(e) => setV(e.target.value)}
+ onFocus={() => (done.current = false)}
+ onBlur={() => {
+ if (!done.current && v.trim() !== value.trim()) onSave(v);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ if (v.trim() !== value.trim()) onSave(v);
+ done.current = true;
+ back();
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ e.stopPropagation();
+ setV(value);
+ done.current = true;
+ back();
+ }
+ }}
+ className={cn(
+ "min-w-0 rounded-[2px] border border-transparent bg-transparent px-1 py-0.5 outline-none placeholder:text-muted-2 hover:border-seam focus:border-seam-2 focus:bg-ground",
+ className,
+ )}
+ />
+ );
+}
+
+export default function QuoteSlip({
+ q,
+ sections,
+ lit,
+ busy,
+ onPatch,
+ onRemove,
+ onDragStart,
+ onDropOn,
+}: {
+ q: Quote;
+ sections: CaseSection[];
+ lit: boolean;
+ busy: boolean;
+ onPatch: (body: Record<string, unknown>) => void;
+ onRemove: () => void;
+ onDragStart: (qid: string) => void;
+ onDropOn: (qid: string, after: boolean) => void;
+}) {
+ const [over, setOver] = useState<"before" | "after" | null>(null);
+ const c = q.cite;
+ const v = q.verify;
+ const where = [
+ c.title,
+ c.channelName ?? c.channel,
+ c.date ? isoDate(c.date) : "",
+ c.kind === "post" ? "" : c.clock,
+ c.trackId ? `${c.trackId} track` : TRACK[c.track ?? ""] ?? "",
+ c.localOnly ? "local only" : "",
+ ].filter(Boolean);
+ const drifted = v?.status === "drifted";
+ return (
+ <LitLine
+ id={quoteLineId(q.id)}
+ initial={lit}
+ data-quote={q.id}
+ data-verify={v?.status ?? "never"}
+ aria-label={`Quote: ${q.text.slice(0, 80)}`}
+ onDragOver={(e) => {
+ if (!e.dataTransfer.types.includes("application/x-umtool-quote")) return;
+ e.preventDefault();
+ const r = e.currentTarget.getBoundingClientRect();
+ setOver(e.clientY > r.top + r.height / 2 ? "after" : "before");
+ }}
+ onDragLeave={() => setOver(null)}
+ onDrop={(e) => {
+ e.preventDefault();
+ const after = over === "after";
+ setOver(null);
+ onDropOn(q.id, after);
+ }}
+ className={cn(
+ "mb-3 grid grid-cols-[22px_minmax(0,1fr)] rounded-[3px] border border-seam bg-panel p-0 last:border-b",
+ over === "before" && "shadow-[0_-2px_0_var(--signal)]",
+ over === "after" && "shadow-[0_2px_0_var(--signal)]",
+ )}
+ >
+ <span
+ draggable
+ aria-hidden="true"
+ title="Drag to move"
+ onDragStart={(e) => {
+ e.dataTransfer.setData("application/x-umtool-quote", q.id);
+ e.dataTransfer.effectAllowed = "move";
+ onDragStart(q.id);
+ }}
+ className="cursor-grab select-none pt-3.5 text-center font-mono text-[12px] text-muted-2"
+ >
+ ⋮⋮
+ </span>
+ <div className="min-w-0">
+ <div data-slip="" className="mr-2.5 mt-2.5 rounded-[2px] bg-reader px-3.5 py-2.5 text-reader-ink shadow-[inset_0_0_0_1px_var(--reader-edge)]">
+ <p className="m-0 font-serif text-[16px] leading-[1.45]">“{q.text}”</p>
+ <div className="mt-1.5 truncate font-mono text-[11px] text-reader-dim" data-cite="">
+ {c.url ? (
+ <a href={c.url} target="_blank" rel="noreferrer" className="hover:text-reader-ink hover:underline" tabIndex={lit ? 0 : -1}>
+ {where.join(" · ")}
+ </a>
+ ) : (
+ where.join(" · ")
+ )}
+ </div>
+ </div>
+ <div className="grid gap-1 py-2 pr-3 text-[13px]">
+ <div className="flex items-baseline gap-1.5">
+ <span className="micro shrink-0">Claim</span>
+ <InlineField
+ field="claim"
+ tabbable={lit}
+ label="Claim"
+ value={q.claim}
+ placeholder="No claim line yet"
+ max={400}
+ onSave={(claim) => onPatch({ claim })}
+ className="flex-1 text-text"
+ />
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-2">
+ {c.kind !== "post" &&
+ (q.speakerChecked ? (
+ <span data-speaker="checked" className="text-muted">Speaker checked</span>
+ ) : (
+ <span data-speaker="unchecked" className="text-doubt-text before:mr-1 before:font-mono before:text-doubt before:content-['?']">
+ Speaker not checked
+ </span>
+ ))}
+ {drifted && (
+ <span data-flag="drifted" className="text-doubt-text before:mr-1 before:font-mono before:text-doubt before:content-['≠']">
+ Drifted
+ </span>
+ )}
+ {v?.status === "missing" && <span data-flag="missing" className="text-reject-text">Missing</span>}
+ {v?.enOrig && (
+ <span data-flag="en-orig" className="text-doubt-text before:mr-1 before:font-mono before:text-doubt before:content-['≠']">
+ en-orig differs
+ </span>
+ )}
+ <span className="flex min-w-[12rem] flex-1 items-baseline gap-1">
+ <span className="shrink-0">note:</span>
+ <InlineField field="note" tabbable={lit} label="Note" value={q.note} placeholder="Add note" max={2000} onSave={(note) => onPatch({ note })} className="flex-1 text-text-2" />
+ </span>
+ {v?.status === "ok" && <span className="font-mono text-[11px]">verified {v.at.slice(0, 10)}</span>}
+ {!v && <span className="font-mono text-[11px]">not re-verified</span>}
+ </div>
+ <LitOnly>
+ <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
+ <label className="sr-only" htmlFor={`sec-${q.id}`}>
+ Section
+ </label>
+ <select
+ id={`sec-${q.id}`}
+ data-field="section"
+ value={q.section ?? ""}
+ disabled={busy}
+ onChange={(e) => onPatch({ section: e.target.value || null })}
+ className="max-w-[11rem] rounded-[3px] border border-seam-2 bg-panel px-1.5 py-[3px] text-[11.5px] text-text"
+ >
+ <option value="">Unsorted</option>
+ {sections.map((s) => (
+ <option key={s.id} value={s.id}>
+ {s.title}
+ </option>
+ ))}
+ </select>
+ <button type="button" disabled={busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => onPatch({ speakerChecked: !q.speakerChecked })}>
+ {q.speakerChecked ? "Mark speaker not checked" : "Mark speaker checked"}
+ </button>
+ <button type="button" disabled={busy} className={buttonVariants({ variant: "destructive", size: "sm" })} onClick={onRemove}>
+ Remove
+ </button>
+ </div>
+ </LitOnly>
+ {drifted && (
+ <div data-drift="" className="grid gap-1 rounded-[2px] border border-seam-2 px-2.5 py-1.5 text-[12px] text-text-2">
+ <span>
+ Re-verified {v.at.slice(0, 10)}: the transcript at {c.clock} now reads
+ </span>
+ <span data-now="" className="font-serif text-[14px] text-text">
+ {v.now ? `“${v.now}”` : <em className="not-italic text-muted-2">(no words there now)</em>}
+ </span>
+ <span className="flex items-center gap-2">
+ <span className="text-muted-2">The quote above keeps the words as pinned.</span>
+ {v.now ? (
+ <button type="button" disabled={busy} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => onPatch({ useCurrentWords: true })}>
+ Use the current words
+ </button>
+ ) : null}
+ </span>
+ </div>
+ )}
+ {v?.status === "missing" && <div className="text-[12px] text-reject-text">{v.message ?? "The recording was not found at its cite."}</div>}
+ {v?.status === "unreadable" && <div className="text-[12px] text-doubt-text">Not re-verified: {v.message}</div>}
+ {v?.message && v.status === "ok" && <div className="text-[12px] text-muted-2">{v.message}</div>}
+ {v?.enOrig && (
+ <div data-en-orig="" className="text-[12px] text-text-2">
+ {v.enOrig.quoted === "en" ? "Quoted from the served en track; en-orig, the words as spoken, says " : "The served en track says otherwise here; en-orig says "}
+ <span className="font-serif text-[13.5px] text-text">“{v.enOrig.text}”</span>
+ {v.enOrig.quoted === "en" ? " — check the audio before using it." : ""}
+ </div>
+ )}
+ </div>
+ </div>
+ </LitLine>
+ );
+}
diff --git a/umtool/components/research/Reader.tsx b/umtool/components/research/Reader.tsx
@@ -1,5 +1,6 @@
"use client";
+import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
import { clock } from "@/components/ui/clock";
@@ -14,6 +15,7 @@ import type { FetchAnswer, LocalMedia, WindowResponse } from "@/lib/research/typ
// lit hit, on the pale surface, the hit's cue lit among dim ones; ± widens or
// narrows the window; the footer's actions name what they do.
//
+// Pin to board the cited cue to the chosen case, as a snapshot quote (R2)
// Copy citation the house format: "quote" [title @ m:ss](moment link)
// Play from m:ss a file umtool can play from this machine (a fetched
// window, a kept source or its audio), from the cite
@@ -30,6 +32,31 @@ export function playable(media: LocalMedia[], at: number): LocalMedia | null {
return windows[0] ?? media.find((m) => m.kind === "source") ?? media.find((m) => m.kind === "audio") ?? null;
}
+function PinButton({ onPin, pinning, board }: { onPin: () => void; pinning: boolean; board: string | null }) {
+ return (
+ <button type="button" data-pin="" title={board ? `Pin to “${board}”` : "Pin to a board (asks which)"} className={paperButtonVariants({ variant: "go" })} disabled={pinning} onClick={onPin}>
+ {pinning ? "Pinning…" : "Pin to board"}
+ </button>
+ );
+}
+
+function PinNote({ pinned }: { pinned: { text: string; href?: string; tone?: "error" } | null }) {
+ if (!pinned) return null;
+ return (
+ <span data-pinned="" role={pinned.tone === "error" ? "alert" : "status"} className="basis-full text-[12px] text-reader-2">
+ {pinned.text}
+ {pinned.href && (
+ <>
+ {" · "}
+ <Link prefetch={false} href={pinned.href} className="underline underline-offset-2 hover:text-reader-ink">
+ Open board
+ </Link>
+ </>
+ )}
+ </span>
+ );
+}
+
export default function Reader({
source,
win,
@@ -41,7 +68,16 @@ export default function Reader({
onCopy,
fetchState,
onFetch,
+ onPin,
+ pinning,
+ pinned,
+ board,
}: {
+ onPin: () => void;
+ pinning: boolean;
+ pinned: { text: string; href?: string; tone?: "error" } | null;
+ /** The chosen case's title, or null: a pin asks which. */
+ board: string | null;
source: string;
win: WindowResponse | null;
error: string | null;
@@ -91,9 +127,13 @@ export default function Reader({
source={win.title}
byline={[win.channelName, isoDate(win.uploadDate), win.localOnly ? "local only" : null]}
footer={
- <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}>
- {copied ? "Copied" : "Copy citation"}
- </button>
+ <>
+ <PinButton onPin={onPin} pinning={pinning} board={board} />
+ <button type="button" className={paperButtonVariants()} onClick={onCopy}>
+ {copied ? "Copied" : "Copy citation"}
+ </button>
+ <PinNote pinned={pinned} />
+ </>
}
fine={win.citation.text}
>
@@ -137,7 +177,8 @@ export default function Reader({
}}
/>
)}
- <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}>
+ <PinButton onPin={onPin} pinning={pinning} board={board} />
+ <button type="button" className={paperButtonVariants()} onClick={onCopy}>
{copied ? "Copied" : "Copy citation"}
</button>
{file && (
@@ -158,6 +199,7 @@ export default function Reader({
+
</button>
</span>
+ <PinNote pinned={pinned} />
{fetchState && fetchState.state !== "asking" && (
<span data-fetch-state={fetchState.state} role={fetchState.state === "failed" ? "alert" : "status"} className="basis-full text-[12px] text-reader-2">
{fetchState.state === "ready"
diff --git a/umtool/components/research/ResearchView.tsx b/umtool/components/research/ResearchView.tsx
@@ -8,13 +8,15 @@ import { KeyHint } from "@/components/ui/kbd";
import type { LitDetail } from "@/components/ui/lit-list";
import { useHydrated } from "@/components/ui/use-hydrated";
import { yearOf } from "@/lib/research/facets.mjs";
-import { researchArchiveHref, researchHref, researchScopeApi, researchWindowApi } from "@/lib/research/hrefs";
+import { researchArchiveHref, researchCaseHref, researchCaseQuotesApi, researchCasesApi, researchHref, researchScopeApi, researchWindowApi } from "@/lib/research/hrefs";
import { parseAsk } from "@/lib/research/query.mjs";
import type { FetchAnswer, LogMarks, ResultHit, Scope, ScopeSummary, SearchResponse, SourceOption, WindowResponse } from "@/lib/research/types";
+import type { CaseDoc, CaseSummary, CaseView, Quote } from "@/lib/research/case-types";
import Facets, { type FacetPick } from "./Facets";
import Reader from "./Reader";
import Results, { parseLineId } from "./Results";
import ScopeBar from "./ScopeBar";
+import { BoardChooser, CaseList, PinDialog } from "./PinTarget";
// ---------------------------------------------------------------------------
// RESEARCH (plans/umtool-redesign.md, "Research, first-class"; canvas
@@ -28,11 +30,36 @@ import ScopeBar from "./ScopeBar";
// the scope live in the URL (replaceState), so a search is a link.
//
// Keys: j/k lines (the list), r read · s skip · u unread (the lit recording,
-// then the next), c copy citation, / the ask bar.
+// then the next), c copy citation, p pin to the board (R2), / the ask bar.
+//
+// PINS (R2): the lit hit -- its cited cue, read again by the server -- goes to
+// the chosen case as a snapshot quote, with this search's session, so the
+// case takes its reading log. With no case chosen, the pin asks which (or
+// names a new one for the query). The choice is in the URL (`case=`) and
+// remembered in this browser.
// ---------------------------------------------------------------------------
const PAGE = 200;
const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
+const BOARD_KEY = "umtool:research-board";
+
+const summaryOf = (d: CaseDoc): CaseSummary => ({
+ id: d.id,
+ piece: `c:${d.id}`,
+ title: d.title,
+ quotes: d.quotes.length,
+ sections: d.sections.length,
+ updatedAt: d.updatedAt,
+ scope: d.scope,
+ drifted: d.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length,
+});
+
+function setUrlCase(id: string | null) {
+ const u = new URL(window.location.href);
+ if (id) u.searchParams.set("case", id);
+ else u.searchParams.delete("case");
+ window.history.replaceState(null, "", `${u.pathname}${u.search}`);
+}
type Lit = { key: string; i: number };
@@ -54,7 +81,11 @@ export default function ResearchView({
initialScope,
initialSummary,
initialSummaryError,
+ initialCases,
+ initialCase,
}: {
+ initialCases: CaseSummary[];
+ initialCase: string | null;
sources: SourceOption[];
initialQuery: string;
initialScope: Scope;
@@ -84,6 +115,35 @@ export default function ResearchView({
const [winLoading, setWinLoading] = useState(false);
const [copied, setCopied] = useState(false);
const [fetchState, setFetchState] = useState<FetchAnswer | { state: "asking" } | null>(null);
+ const [cases, setCases] = useState<CaseSummary[]>(initialCases);
+ const [board, setBoard] = useState<string | null>(initialCase && initialCases.some((c) => c.id === initialCase) ? initialCase : null);
+ const [pinAsk, setPinAsk] = useState<"pin" | "new" | null>(null);
+ const [pinWorking, setPinWorking] = useState(false);
+ const [pinError, setPinError] = useState<string | null>(null);
+ const [pinned, setPinned] = useState<{ text: string; href?: string; tone?: "error" } | null>(null);
+
+ // The board chosen last time, when the URL names none.
+ useEffect(() => {
+ if (board) return;
+ try {
+ const was = window.localStorage.getItem(BOARD_KEY);
+ if (was && initialCases.some((c) => c.id === was)) setBoard(was);
+ } catch {
+ /* no storage: nothing remembered */
+ }
+ // once, on arrival
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ const chooseBoard = useCallback((id: string | null) => {
+ setBoard(id);
+ setUrlCase(id);
+ try {
+ if (id) window.localStorage.setItem(BOARD_KEY, id);
+ else window.localStorage.removeItem(BOARD_KEY);
+ } catch {
+ /* the URL still says it */
+ }
+ }, []);
// ── the scope preview, re-read when the scope changes ──
const firstScope = useRef(true);
@@ -148,7 +208,7 @@ export default function ResearchView({
setShown(PAGE);
setLit(null);
setWin(null);
- window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle }));
+ window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle, case: new URL(window.location.href).searchParams.get("case") ?? undefined }));
// The search counted the scope's tracks: the preview can say so now.
fetch(researchScopeApi(s), { cache: "no-store" })
.then((x) => json<ScopeSummary>(x))
@@ -337,6 +397,91 @@ export default function ResearchView({
}
}, [res, litHit, win]);
+ // ── pin to a board (R2) ──
+ const pinTo = useCallback(
+ async (caseId: string) => {
+ if (!res || !litHit || !litSnip) return;
+ if (litHit.kind !== "post" && litSnip.scope) {
+ setPinned({ text: `A hit in the ${litSnip.scope} has no moment to pin`, tone: "error" });
+ return;
+ }
+ // The reader's cited cue when it is this hit's window; else the snippet's second.
+ const cue = win && win.videoId === litHit.videoId && win.lit >= 0 ? win.cues[win.lit] : null;
+ setPinWorking(true);
+ try {
+ const r = await json<{ quote: Quote; duplicate: boolean; case: CaseView }>(
+ await fetch(researchCaseQuotesApi(caseId), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ source: res.source.handle,
+ channel: litHit.channelKey,
+ video: litHit.videoId,
+ t: litHit.kind === "post" ? 0 : (cue?.t ?? litSnip.t),
+ ...(litSnip.track ? { track: litSnip.track } : {}),
+ kind: litHit.kind,
+ search: { session: res.session, query: res.query, total: res.total, complete: res.complete, notReached: res.notReached, sourceLabel: res.source.label },
+ scope: { ...(ranScope ?? {}), source: res.source.handle, query: res.query, ...(res.regex ? { regex: true } : {}) },
+ }),
+ }),
+ );
+ const sum = summaryOf(r.case.case);
+ setCases((cs) => [sum, ...cs.filter((c) => c.id !== sum.id)]);
+ setPinned({
+ text: r.duplicate ? `Already on “${sum.title}” (${r.quote.id})` : `Pinned to “${sum.title}” · ${sum.quotes} ${sum.quotes === 1 ? "quote" : "quotes"}`,
+ href: researchCaseHref(caseId),
+ });
+ setPinAsk(null);
+ setPinError(null);
+ } catch (e) {
+ if (pinAsk) setPinError((e as Error).message);
+ else setPinned({ text: `Pin: ${(e as Error).message}`, tone: "error" });
+ } finally {
+ setPinWorking(false);
+ }
+ },
+ [res, litHit, litSnip, win, ranScope, pinAsk],
+ );
+
+ const pin = useCallback(() => {
+ if (!res || !litHit) return;
+ if (board && cases.some((c) => c.id === board)) void pinTo(board);
+ else {
+ setPinError(null);
+ setPinAsk("pin");
+ }
+ }, [res, litHit, board, cases, pinTo]);
+
+ const createCase = useCallback(
+ async (title: string) => {
+ setPinWorking(true);
+ setPinError(null);
+ try {
+ const r = await json<{ case: CaseDoc }>(
+ await fetch(researchCasesApi(), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ title, query: res?.query ?? ask, scope: { ...(ranScope ?? scope), ...(res ? { source: res.source.handle } : {}) } }),
+ }),
+ );
+ const sum = summaryOf(r.case);
+ setCases((cs) => [sum, ...cs]);
+ chooseBoard(sum.id);
+ if (pinAsk === "pin" && res && litHit) await pinTo(sum.id);
+ else {
+ setPinAsk(null);
+ setPinned({ text: `New case “${sum.title}”: pins go to it`, href: researchCaseHref(sum.id) });
+ }
+ } catch (e) {
+ setPinError((e as Error).message);
+ } finally {
+ setPinWorking(false);
+ }
+ },
+ [res, ask, ranScope, scope, chooseBoard, pinAsk, litHit, pinTo],
+ );
+ useEffect(() => setPinned(null), [lit?.key, lit?.i]);
+
// ── keys ──
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -350,10 +495,14 @@ export default function ResearchView({
else if (e.key === "s") void markLit("skipped");
else if (e.key === "u") void markLit("unread");
else if (e.key === "c") void copy();
+ else if (e.key === "p") {
+ e.preventDefault();
+ pin();
+ }
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
- }, [markLit, copy]);
+ }, [markLit, copy, pin]);
const stale = !!res && !!ranScope && !sameScope(ranScope, scope);
const filtered = visible.length !== (res?.hits.length ?? 0);
@@ -389,9 +538,21 @@ export default function ResearchView({
{ask.trim() && parsedAsk.kind !== "phrase" ? (parsedAsk.kind === "near" ? `near: ${parsedAsk.near?.n} words, one line` : "regex") : "phrase · regex /…/ · a near:8 b"}
</span>
</label>
- <button type="submit" disabled={!hydrated || searching} className={buttonVariants({ variant: "outline", size: "md" })}>
- {searching ? "Searching…" : "Search"} <kbd>↵</kbd>
- </button>
+ <span className="flex items-center gap-3">
+ <button type="submit" disabled={!hydrated || searching} className={buttonVariants({ variant: "outline", size: "md" })}>
+ {searching ? "Searching…" : "Search"} <kbd>↵</kbd>
+ </button>
+ <BoardChooser
+ cases={cases}
+ value={board}
+ disabled={!hydrated}
+ onChange={chooseBoard}
+ onNew={() => {
+ setPinError(null);
+ setPinAsk("new");
+ }}
+ />
+ </span>
</form>
<ScopeBar
@@ -468,6 +629,7 @@ export default function ResearchView({
<KeyHint keys={["s"]}>skip</KeyHint>
<KeyHint keys={["u"]}>unread</KeyHint>
<KeyHint keys={["c"]}>copy citation</KeyHint>
+ <KeyHint keys={["p"]}>pin to board</KeyHint>
<KeyHint keys={["/"]}>ask</KeyHint>
<span className="ml-auto">
{res.batches} {res.batches === 1 ? "batch" : "batches"} of 8 for a sweep
@@ -493,6 +655,7 @@ export default function ResearchView({
</Link>
</div>
)}
+ {!searching && <CaseList cases={cases} />}
</div>
)}
</div>
@@ -508,6 +671,24 @@ export default function ResearchView({
onCopy={copy}
fetchState={fetchState}
onFetch={fetchClip}
+ onPin={pin}
+ pinning={pinWorking}
+ pinned={pinned}
+ board={cases.find((c) => c.id === board)?.title ?? null}
+ />
+ <PinDialog
+ open={pinAsk !== null}
+ mode={pinAsk ?? "pin"}
+ cases={pinAsk === "pin" ? cases : []}
+ query={res?.query ?? ask}
+ error={pinError}
+ working={pinWorking}
+ onPick={(id) => {
+ chooseBoard(id);
+ void pinTo(id);
+ }}
+ onCreate={(title) => void createCase(title)}
+ onClose={() => setPinAsk(null)}
/>
</div>
);
diff --git a/umtool/components/ui/badge.tsx b/umtool/components/ui/badge.tsx
@@ -20,7 +20,7 @@ import { cn } from "@/lib/utils";
// ---------------------------------------------------------------------------
export const badgeVariants = cva(
- "inline-flex items-center gap-1.5 whitespace-nowrap rounded-[3px] border transition-colors",
+ "inline-flex items-center gap-1.5 whitespace-nowrap rounded-[3px] border transition-[color,background-color,border-color,text-decoration-color,fill,stroke]",
{
variants: {
variant: {
diff --git a/umtool/components/ui/button.tsx b/umtool/components/ui/button.tsx
@@ -20,8 +20,12 @@ import { cn } from "@/lib/utils";
// with for hours, so nothing here is smaller than what the existing controls
// are, and dense is the point.
+// The colours ease on hover; the focus ring does NOT: Tailwind's
+// `transition-colors` includes outline-color, which faded the ring in from
+// currentColor over 150 ms. The lit line's glide is the app's one motion, so
+// every control lists the colour properties it eases and leaves the outline out.
export const buttonVariants = cva(
- "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border font-medium transition-colors disabled:pointer-events-none disabled:opacity-50",
+ "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border font-medium transition-[color,background-color,border-color,text-decoration-color,fill,stroke] disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
diff --git a/umtool/components/ui/reader-pane.tsx b/umtool/components/ui/reader-pane.tsx
@@ -24,7 +24,7 @@ import { LitLine } from "./lit-line";
export type Cue = { t: number; text: React.ReactNode; turn?: boolean; lit?: boolean; id?: string };
export const paperButtonVariants = cva(
- "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border px-[11px] py-[5px] text-[12.5px] font-medium transition-colors disabled:pointer-events-none disabled:opacity-50",
+ "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border px-[11px] py-[5px] text-[12.5px] font-medium transition-[color,background-color,border-color,text-decoration-color,fill,stroke] disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
diff --git a/umtool/e2e/board.spec.ts b/umtool/e2e/board.spec.ts
@@ -0,0 +1,254 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { BOARD_CASE, DRIFTED_QUOTE, EN_REWRITE, RESEARCH_PHRASE } from "./fixtures/research-fixture.mjs";
+import { researchCaseHref, researchHref } from "../lib/research/hrefs";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Research boards (plans/umtool-redesign.md, R2) on the research fixture
+// corpus (e2e/fixtures/research-fixture.mjs) and its board, `fixture-board`
+// (a drifted quote, an intact one, one quoted from the served `en` track):
+// a case made from a pin, pins from the results (p) and from the reader,
+// sections and order by the keys, the claim and the note, the export, the
+// re-verify, and the hand-offs' plans.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const caseJson = (id: string) => JSON.parse(readFileSync(path.join(FIXTURE, ".umtool", "research", id, "case.json"), "utf8"));
+
+const results = (page: Page) => page.getByRole("group", { name: "Results" });
+const reader = (page: Page) => page.getByRole("complementary", { name: "Reader" });
+const board = (page: Page) => page.getByRole("group", { name: "Board" });
+const litId = (page: Page) => board(page).locator("[data-lit-line][data-lit]");
+const status = (page: Page) => page.locator("[data-board-status]");
+
+async function searched(page: Page) {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(page.locator("[data-honest]")).toBeVisible({ timeout: 30_000 });
+}
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, [researchHref(), researchCaseHref(BOARD_CASE), "/api/research/cases"]);
+});
+
+test("Research lists the cases; a board shows its slips, flags and side panel", async ({ page }) => {
+ await page.goto(researchHref());
+ const cases = page.getByRole("group", { name: "Cases" });
+ await expect(cases.locator(`[data-case="${BOARD_CASE}"]`)).toContainText("Fixture board");
+ await expect(cases.locator(`[data-case="${BOARD_CASE}"]`)).toContainText("3 quotes · 1 section");
+ await cases.getByRole("link", { name: "Fixture board" }).click();
+ await expect(page).toHaveURL(new RegExp(`/research/${BOARD_CASE}$`));
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("Fixture board");
+ await expect(page.locator("[data-board-meta]")).toHaveText("3 quotes · 1 section · from “lighthouse budget” · Local corpus");
+ // The rail lights Research.
+ await expect(page.locator('a[aria-current][href="/research"]')).toBeVisible();
+ const b = board(page);
+ await expect(b.locator("[data-quote]")).toHaveCount(3);
+ await expect(b.locator('[data-quote="q1"] [data-slip]')).toContainText(`“${DRIFTED_QUOTE.was}”`);
+ await expect(b.locator('[data-quote="q1"] [data-cite]')).toContainText("Harbor Radio 80: the council vote · Harbor Radio · 2022-02-11 · 34:04");
+ await expect(b.locator('[data-section="s1"]')).toContainText("The vote");
+ await expect(b.locator('[data-quote="q2"] [data-speaker]')).toHaveAttribute("data-speaker", "checked");
+ await expect(b.locator('[data-quote="q1"] [data-speaker]')).toHaveText("Speaker not checked");
+ const facts = page.locator("[data-case-facts]");
+ await expect(facts).toContainText(`.umtool/research/${BOARD_CASE}/`);
+ await expect(facts).toContainText(`c:${BOARD_CASE}`);
+ await expect(page.locator("[data-searched]")).toHaveText("nothing yet");
+});
+
+test("pin from the results with p (a new case, named on the way) and from the reader; the search becomes the case's", async ({ page }) => {
+ await searched(page);
+ const first = results(page).locator("[data-lit-line][data-lit]");
+ await expect(first).toHaveAttribute("data-lit-id", "harbor-radio/hr-2019a|0");
+ await expect(reader(page).locator("[data-citation]")).toContainText("Harbor Radio 1: the old pier");
+ await page.keyboard.press("p");
+ const dialog = page.locator("dialog[data-pin-dialog]");
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole("textbox", { name: "New case title" }).fill("Lighthouse case");
+ await dialog.getByRole("button", { name: "New case and pin" }).click();
+ await expect(dialog).toBeHidden();
+ await expect(reader(page).locator("[data-pinned]")).toContainText("Pinned to “Lighthouse case” · 1 quote");
+ await expect(page.getByRole("combobox", { name: "Board" })).toHaveValue("lighthouse-case");
+ expect(new URL(page.url()).searchParams.get("case")).toBe("lighthouse-case");
+
+ // From the reader: another hit, the reader's Pin to board.
+ await results(page).locator('[data-lit-id="night-desk/nd-2023|0"]').click();
+ await expect(reader(page).locator("[data-citation]")).toContainText("Night Desk: the keeper @ 6:40");
+ await reader(page).getByRole("button", { name: "Pin to board" }).click();
+ await expect(reader(page).locator("[data-pinned]")).toContainText("Pinned to “Lighthouse case” · 2 quotes");
+ // The same cite again is not a second quote.
+ await page.keyboard.press("p");
+ await expect(reader(page).locator("[data-pinned]")).toContainText("Already on “Lighthouse case” (q2)");
+
+ const doc = caseJson("lighthouse-case");
+ expect(doc.quotes.map((q: { text: string }) => q.text)).toEqual(["the lighthouse budget was never approved", "the keeper never saw the lighthouse budget"]);
+ expect(doc.quotes[1].cite).toMatchObject({ channel: "night-desk", video: "nd-2023", t: 400, url: "https://archive.example/?v=night-desk%2Fnd-2023&t=400" });
+ expect(doc.search).toMatchObject({ query: RESEARCH_PHRASE, total: 8, complete: true });
+ expect(doc.sessions).toEqual([doc.search.session]);
+ expect(doc.scope).toMatchObject({ query: RESEARCH_PHRASE });
+ // A third, for the board's moves below.
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2021a|0"]').click();
+ await page.keyboard.press("p");
+ await expect(reader(page).locator("[data-pinned]")).toContainText("3 quotes");
+ await reader(page).getByRole("link", { name: "Open board" }).click();
+ await expect(page).toHaveURL(/\/research\/lighthouse-case$/);
+ await expect(page.locator("[data-searched]")).toHaveText("8 recordings, complete");
+ await expect(page.locator("[data-read]")).toHaveText("0 of 8");
+});
+
+test("sections and order: a, alt+j/k across sections, the section menu; claim, note and speaker saved", async ({ page }) => {
+ await page.goto(researchCaseHref("lighthouse-case"));
+ const b = board(page);
+ await expect(b.locator("[data-quote]")).toHaveCount(3);
+ await page.locator("body").click();
+ for (const title of ["Approval", "The keeper"]) {
+ await page.keyboard.press("a");
+ await page.getByRole("textbox", { name: "Title" }).fill(title);
+ await page.getByRole("button", { name: "Add section" }).click();
+ await expect(b.locator("[data-section]", { hasText: title })).toBeVisible();
+ }
+ expect(caseJson("lighthouse-case").sections).toEqual([{ id: "s1", title: "Approval" }, { id: "s2", title: "The keeper" }]);
+
+ // Light q1 and move it: down past q2, then on into the top of Approval.
+ await b.locator('[data-quote="q1"]').click({ position: { x: 8, y: 8 } });
+ await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+ await page.keyboard.press("Alt+j");
+ await expect.poll(() => caseJson("lighthouse-case").quotes.map((q: { id: string }) => q.id).join(" ")).toBe("q2 q1 q3");
+ await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+ await page.keyboard.press("Alt+j");
+ await expect.poll(() => caseJson("lighthouse-case").quotes.map((q: { id: string }) => q.id).join(" ")).toBe("q2 q3 q1");
+ await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+ await page.keyboard.press("Alt+j");
+ await expect.poll(() => caseJson("lighthouse-case").quotes.find((q: { id: string }) => q.id === "q1").section).toBe("s1");
+ await expect(b.locator('[data-group="s1"] [data-quote="q1"]')).toBeVisible();
+ await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+ // And back up: alt+k.
+ await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+ await page.keyboard.press("Alt+k");
+ await expect.poll(() => caseJson("lighthouse-case").quotes.find((q: { id: string }) => q.id === "q1").section).toBe(null);
+ await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+
+ // The claim (e) and the note (n), saved on Enter; the speaker check (s).
+ await page.keyboard.press("e");
+ await expect(b.locator('[data-quote="q1"] [data-field="claim"]')).toBeFocused();
+ await page.keyboard.type("The budget was never approved");
+ await page.keyboard.press("Enter");
+ await expect(litId(page)).toBeFocused();
+ await page.keyboard.press("n");
+ await page.keyboard.type("Harbor Radio's host");
+ await page.keyboard.press("Enter");
+ await page.keyboard.press("s");
+ await expect(b.locator('[data-quote="q1"] [data-speaker]')).toHaveAttribute("data-speaker", "checked");
+ await expect.poll(() => caseJson("lighthouse-case").quotes.find((q: { id: string }) => q.id === "q1")).toMatchObject({
+ claim: "The budget was never approved",
+ note: "Harbor Radio's host",
+ speakerChecked: true,
+ });
+
+ // The section menu (m) puts the keeper's quote under The keeper.
+ await b.locator('[data-quote="q2"]').click({ position: { x: 8, y: 8 } });
+ await page.keyboard.press("m");
+ await expect(b.locator('[data-quote="q2"] [data-field="section"]')).toBeFocused();
+ await b.locator('[data-quote="q2"] [data-field="section"]').selectOption({ label: "The keeper" });
+ await expect(b.locator('[data-group="s2"] [data-quote="q2"]')).toBeVisible();
+ // A section moves too: The keeper above Approval.
+ await b.locator('[data-section="s2"]').click();
+ await page.keyboard.press("Alt+k");
+ await expect.poll(() => caseJson("lighthouse-case").sections.map((s: { id: string }) => s.id).join(" ")).toBe("s2 s1");
+});
+
+test("the export: cited markdown in the house format, copied and downloadable", async ({ page, context, request }) => {
+ const md = await (await request.get("/api/research/cases/lighthouse-case/export.md")).text();
+ const heads = md.split("\n").filter((l) => l.startsWith("#"));
+ expect(heads[0]).toBe("# Lighthouse case");
+ expect(heads.at(-1)).toBe("## Coverage");
+ expect(heads).toContain("## The keeper");
+ expect(md).toContain(
+ '- The budget was never approved: "the lighthouse budget was never approved" — [Harbor Radio 1: the old pier @ 10:00](https://archive.example/?v=harbor-radio%2Fhr-2019a&t=600)\n Note: Harbor Radio\'s host.',
+ );
+ expect(md).toContain("Searched for “lighthouse budget”: 8 recordings, complete. Read 0 of 8. 3 pinned.");
+ const dl = await request.get("/api/research/cases/lighthouse-case/export.md?download=1");
+ expect(dl.headers()["content-disposition"]).toBe('attachment; filename="lighthouse-case.md"');
+
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.goto(researchCaseHref("lighthouse-case"));
+ await expect(board(page).locator("[data-quote]")).toHaveCount(3);
+ await page.locator("body").click();
+ await page.keyboard.press("c");
+ await expect(status(page)).toContainText("Copied the board as cited markdown");
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(md);
+});
+
+test("hand-offs: an article's plan (the model and cap, a seeded sweep) and a video's (the cue spans); local-only refused", async ({ page, request }) => {
+ await page.goto(researchCaseHref("lighthouse-case"));
+ await page.getByRole("button", { name: "Draft an article from this board" }).click();
+ const art = page.locator('dialog[data-handoff="article"]');
+ await expect(art).toContainText("lighthouse-case");
+ await expect(art).toContainText("the board as cited markdown: 3 quotes");
+ await expect(art).toContainText(/Runs on\s*claude-/);
+ await expect(art.getByRole("button", { name: /^Start the sweep/ })).toBeEnabled();
+ await art.getByRole("button", { name: "Cancel" }).click();
+ await expect(art).toBeHidden();
+
+ await page.getByRole("button", { name: "Start a video from this board" }).click();
+ const vid = page.locator('dialog[data-handoff="video"]');
+ await expect(vid).toContainText("3 — each the cue span of a pinned quote");
+ // Board order: Unsorted (q3, q1), then The keeper (q2).
+ await expect(vid).toContainText("c00 harbor-radio/hr-2021a 1212–1215.8");
+ await expect(vid).toContainText("c01 harbor-radio/hr-2019a 600–603.8");
+ await expect(vid).toContainText("https://archive.example");
+ await expect(vid.getByRole("button", { name: "Create the project" })).toBeEnabled();
+ await page.keyboard.press("Escape");
+ await expect(vid).toBeHidden();
+ // Nothing was written by a plan.
+ expect(caseJson("lighthouse-case").handoffs).toEqual([]);
+
+ // A board with a local-only quote never becomes an article.
+ const made = await (await request.post("/api/research/cases", { data: { title: "Local only board" } })).json();
+ const source = caseJson(BOARD_CASE).scope.source;
+ const pinned = await request.post(`/api/research/cases/${made.case.id}/quotes`, { data: { source, channel: "candace-owens", video: "lo-2025", t: 12 } });
+ expect(pinned.ok()).toBe(true);
+ const plan = (await (await request.post(`/api/research/cases/${made.case.id}/handoff`, { data: { to: "article" } })).json()).plan;
+ expect(plan.refusals.join(" ")).toContain("local-only channel");
+ const refused = await request.post(`/api/research/cases/${made.case.id}/handoff`, { data: { to: "article", confirm: true } });
+ expect(refused.status()).toBe(409);
+});
+
+test("re-verify: the drifted quote shows the old and the new words, en vs en-orig is flagged, and nothing changes by itself", async ({ page }) => {
+ await page.goto(researchCaseHref(BOARD_CASE));
+ const b = board(page);
+ await expect(b.locator("[data-quote]")).toHaveCount(3);
+ await page.locator("body").click();
+ await page.keyboard.press("v");
+ await expect(status(page)).toHaveText("Re-verified 3: 2 as pinned, 1 drifted, 0 missing; en-orig differs at 1", { timeout: 30_000 });
+ const q1 = b.locator('[data-quote="q1"]');
+ await expect(q1).toHaveAttribute("data-verify", "drifted");
+ await expect(q1.locator('[data-flag="drifted"]')).toBeVisible();
+ await expect(q1.locator("[data-slip]")).toContainText(DRIFTED_QUOTE.was);
+ await expect(q1.locator("[data-now]")).toHaveText(`“${DRIFTED_QUOTE.now}”`);
+ await expect(b.locator('[data-quote="q2"]')).toHaveAttribute("data-verify", "ok");
+ const q3 = b.locator('[data-quote="q3"]');
+ await expect(q3.locator('[data-flag="en-orig"]')).toBeVisible();
+ await expect(q3.locator("[data-en-orig]")).toContainText(`“${EN_REWRITE.orig}”`);
+ expect(caseJson(BOARD_CASE).quotes[0].text).toBe(DRIFTED_QUOTE.was);
+ await expect(page.locator("[data-board-meta]").locator("..")).toContainText("1 drifted or missing");
+
+ // Only the operator's word takes the current words; the old are kept.
+ await q1.getByRole("button", { name: "Use the current words" }).click();
+ await expect(q1.locator("[data-slip]")).toContainText(DRIFTED_QUOTE.now);
+ await expect(q1).toHaveAttribute("data-verify", "ok");
+ const q = caseJson(BOARD_CASE).quotes[0];
+ expect(q.text).toBe(DRIFTED_QUOTE.now);
+ expect(q.history[0].text).toBe(DRIFTED_QUOTE.was);
+});
+
+test("the board fits 1366×768: the side panel and the first quote are on screen, the page does not scroll sideways", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.goto(researchCaseHref("lighthouse-case"));
+ await expect(page.getByRole("button", { name: "Draft an article from this board" })).toBeInViewport();
+ await expect(board(page).locator("[data-quote]").first()).toBeInViewport();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -29,7 +29,7 @@ import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
-import { makeResearchFixture } from "./research-fixture.mjs";
+import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1933,6 +1933,8 @@ makeDeleteFixture({ dest, articles: ARTICLES, reports });
// R1: Research's local corpus (research-public/, TRANSCRIPT_LOCAL_DIR) and the
// held channels its inventory reads on disk.
const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS });
+// R2: a research board with a drifted quote and an `en`-track one (REPORTS_ROOT is dest).
+makeBoardFixture({ reportsRoot: dest, pub: RESEARCH_PUBLIC });
console.log(`fixture at ${dest}`);
console.log(` SITES_DIR=${SITES}`);
diff --git a/umtool/e2e/fixtures/research-fixture.mjs b/umtool/e2e/fixtures/research-fixture.mjs
@@ -21,6 +21,12 @@
// harbor-radio-rumble v1abcd mirrors hr-2024a (folded); v2efgh matches
// night-desk 3 recordings, transcribed; nd-2023 matches
// candace-owens a LOCAL-ONLY slug (lib/research/rules.mjs): 1 match
+//
+// R2 (boards): hr-2022b's primary track is `en-orig` and it carries a served
+// `en` alternate that rewrites one line (EN_REWRITE, at 900 s) -- the hazard
+// re-verify checks for. makeBoardFixture writes a case whose quotes are a
+// drifted one (the words changed since it was pinned), an intact one, and
+// one quoted from the `en` track.
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
@@ -118,6 +124,15 @@ export const RESEARCH_CHANNELS = [
},
];
+// The served `en` track's rewrite of hr-2022b's line at 900 s (its en-orig
+// says "the lighthouse keeper called in").
+export const EN_REWRITE = { at: 900, orig: "the lighthouse keeper called in", en: "the lighthouse keeper rang in" };
+{
+ const r = RESEARCH_CHANNELS[0].records.find((x) => x.id === "hr-2022b");
+ r.track = "en-orig";
+ r.altTracks = [{ track: "en", cues: r.cues.map((c) => (c.start === EN_REWRITE.at ? { ...c, text: EN_REWRITE.en } : { ...c })) }];
+}
+
const STATES = { "harbor-radio/hr-2024a": "deleted", "harbor-radio/hr-2026a": "unlisted" };
// The editor's disk for the "held" column: harbor-radio holds five of its six
@@ -221,3 +236,59 @@ export function makeResearchFixture({ dest, channels }) {
}
return { pub };
}
+
+// The words a drifted quote was pinned with: hr-2022a says "eight to one" now.
+export const DRIFTED_QUOTE = { video: "hr-2022a", at: 2044, was: `they voted the ${P} down nine to one`, now: `they voted the ${P} down eight to one` };
+export const BOARD_CASE = "fixture-board";
+
+/**
+ * R2: a research case under `reportsRoot` (REPORTS_ROOT/.umtool/research/),
+ * as the board store writes one: three quotes pinned from the local corpus at
+ * `pub` -- one whose words have drifted since, one intact, one quoted from the
+ * served `en` track where en-orig says otherwise.
+ */
+export function makeBoardFixture({ reportsRoot, pub }) {
+ const source = `local:${pub}`;
+ const cite = (channel, channelName, id, title, date, t, extra = {}) => ({
+ kind: "video",
+ source,
+ channel,
+ channelKey: channel,
+ channelName,
+ video: id,
+ title,
+ date,
+ t,
+ end: t + 3.8,
+ clock: `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`,
+ track: "captions",
+ url: `${ARCHIVE}/?v=${channel}%2F${id}&t=${t}`,
+ ...extra,
+ });
+ const at = "2026-10-13T12:00:00.000Z";
+ write(path.join(reportsRoot, ".umtool", "research", BOARD_CASE, "case.json"), `${JSON.stringify(
+ {
+ format: "umtool-research-case",
+ version: 1,
+ id: BOARD_CASE,
+ title: "Fixture board",
+ scope: { source, query: P },
+ search: null,
+ sessions: [],
+ sections: [{ id: "s1", title: "The vote" }],
+ quotes: [
+ { id: "q1", section: "s1", text: DRIFTED_QUOTE.was, cite: cite("harbor-radio", "Harbor Radio", "hr-2022a", "Harbor Radio 80: the council vote", "20220211", DRIFTED_QUOTE.at, { track: "transcript" }), claim: "The council vote on the budget", note: "", speakerChecked: false, pinnedAt: at },
+ { id: "q2", section: null, text: `the keeper never saw the ${P}`, cite: cite("night-desk", "Night Desk", "nd-2023", "Night Desk: the keeper", "20230901", 400, { track: "transcript" }), claim: "", note: "the keeper's side", speakerChecked: true, pinnedAt: at },
+ { id: "q3", section: null, text: EN_REWRITE.en, cite: cite("harbor-radio", "Harbor Radio", "hr-2022b", "Harbor Radio 91: call-in night", "20221103", EN_REWRITE.at, { trackId: "en" }), claim: "", note: "", speakerChecked: false, pinnedAt: at },
+ ],
+ notes: "",
+ handoffs: [],
+ counters: { quote: 3, section: 1 },
+ createdAt: at,
+ updatedAt: at,
+ },
+ null,
+ 2,
+ )}\n`);
+ return { id: BOARD_CASE };
+}
diff --git a/umtool/e2e/shell.spec.ts b/umtool/e2e/shell.spec.ts
@@ -207,6 +207,28 @@ test("j and k move the lit line, and focus goes with it", async ({ page }) => {
await expect.poll(async () => Math.round((await list.locator(".lit-head").boundingBox())?.y ?? -1)).toBe(Math.round(line!.y));
});
+test("a control's focus ring is Signal at once: it does not fade in (the lit line's glide is the one motion)", async ({ page }) => {
+ await page.goto(researchHref());
+ const search = page.getByRole("button", { name: /^Search/ });
+ await expect(search).toBeEnabled();
+ await page.getByRole("textbox", { name: "Ask" }).focus();
+ await page.keyboard.press("Tab");
+ // Read in the same task as the Tab lands: no wait, no poll.
+ const seen = await page.evaluate(() => {
+ const el = document.activeElement as HTMLElement;
+ const probe = document.createElement("i");
+ probe.style.color = "var(--signal)";
+ document.body.append(probe);
+ const signal = getComputedStyle(probe).color;
+ probe.remove();
+ const cs = getComputedStyle(el);
+ return { label: el.textContent?.trim().slice(0, 6), outline: `${cs.outlineStyle} ${cs.outlineWidth} ${cs.outlineColor}`, signal, props: cs.transitionProperty };
+ });
+ expect(seen.label).toBe("Search");
+ expect(seen.outline).toBe(`solid 2px ${seen.signal}`);
+ expect(seen.props).not.toMatch(/outline|all/);
+});
+
test("the head glides, and does not under reduced motion", async ({ page }) => {
const duration = () =>
page.locator("[data-lit-list] .lit-head").first().evaluate((el) => getComputedStyle(el).transitionDuration);
diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts
@@ -296,8 +296,10 @@ export async function cancelDraftJob(id: string): Promise<void> {
}
// The body umtool sends to `report-draft`: the action's own keys, nothing else
-// (the editor refuses an unknown key; this refuses it first, by name).
-const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy"];
+// (the editor refuses an unknown key; this refuses it first, by name). `source`
+// and `seed` are a research board's hand-off (R2, lib/research/handoff.ts): the
+// corpus the board was read through, and the board as the sweep's seed.md.
+const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy", "source", "seed"];
export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> {
const out: Record<string, unknown> = {};
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -22,7 +22,10 @@ export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
* look finished and be wrong, and every clip would have to be opened anyway.
*
* (`--seed chapters` is the one exception, and it invents nothing: the windows
- * it writes are the digest's own chapter boundaries.)
+ * it writes are the digest's own chapter boundaries. So is a research board's
+ * `timeline` (lib/research/handoff.ts): each window is the cue span of a quote
+ * a person pinned after reading it in its transcript -- a start AND an end the
+ * transcript gave, never a guess from one second.)
*/
export function skeleton(slug, title, provenance, { brand = null } = {}) {
const doc = {
@@ -105,6 +108,19 @@ export function citationsIn(text) {
return out;
}
+const isBoardClip = (c) =>
+ c &&
+ c.type === "clip" &&
+ typeof c.id === "string" &&
+ /^[A-Za-z0-9_-]+$/.test(c.id) &&
+ typeof c.channel === "string" &&
+ c.channel !== "" &&
+ typeof c.video === "string" &&
+ c.video !== "" &&
+ Number.isFinite(c.start) &&
+ Number.isFinite(c.end) &&
+ c.end > c.start;
+
const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
/**
@@ -158,9 +174,13 @@ export async function chaptersAsClips({ channelsDir, channel, video }) {
* Write the project. Refuses an existing directory and a slug that will not
* route; everything else it cannot know is written EMPTY so `check` blocks.
*
- * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string }} args
+ * `timeline` is a research board's clips (`{ type: "clip", id, channel, video,
+ * start, end, cite, quote, … }`, in board order), written as they are and
+ * unlocked; `timelineFrom` names the board in the README.
+ *
+ * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null }} args
*/
-export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR() }) {
+export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null }) {
if (!SLUG_RE.test(String(slug ?? ""))) {
throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
}
@@ -178,6 +198,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
}
if (seed && seed !== "chapters") throw new Error(`--seed must be "chapters", not "${seed}"`);
if (seed && src?.kind !== "video") throw new Error("--seed chapters needs --from to be a video ref");
+ if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed");
+ if (timeline && (!Array.isArray(timeline) || !timeline.every(isBoardClip))) {
+ throw new Error("a timeline is a list of clips, each { type: \"clip\", id, channel, video, start, end }");
+ }
if (brand && !BRAND_IDS.includes(brand)) {
throw new Error(`--brand must be one of ${BRAND_IDS.join(", ")}, not "${brand}"`);
}
@@ -215,6 +239,13 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
if (!clips.length) notes.push("the digest has no enabled chapters, so the timeline is empty");
}
+ if (timeline) {
+ doc.timeline = timeline.map((c) => ({ ...c }));
+ seeded = doc.timeline.length;
+ const channels = [...new Set(doc.timeline.map((c) => c.channel))];
+ if (channels.length === 1 && !doc.provenance.channelSlug) doc.provenance.channelSlug = channels[0];
+ }
+
await mkdir(dir, { recursive: true });
await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n", "utf8");
if (reportText !== null) await writeFile(path.join(dir, "sweep-report.md"), reportText, "utf8");
@@ -226,7 +257,18 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
"purpose (with why — that is what a `lock` in the manifest means).",
"",
];
- if (seeded) {
+ if (seeded && timeline) {
+ lines.push(
+ `## Clips from the research board${timelineFrom ? ` ${timelineFrom}` : ""} — review each`,
+ "",
+ "Every window below is the cue span of a quote pinned on the board: what the",
+ "transcript said there, not an edit. A cue ends where the caption line",
+ "wrapped, so a window can stop mid-thought. Open each in the bench, cut it",
+ "to the sentence that matters, and lock what you meant.",
+ "",
+ ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.channel}/${c.video} ${c.start}–${c.end} ${String(c.quote ?? "").slice(0, 80)}`),
+ );
+ } else if (seeded) {
lines.push(
"## Clips seeded from digest chapters — review each",
"",
diff --git a/umtool/lib/research/board.mjs b/umtool/lib/research/board.mjs
@@ -0,0 +1,194 @@
+// THE BOARD, as data: its groups and order, the moves the keys and drag make,
+// the export in the house format, and the words compare re-verify uses.
+// Pure and browser-safe (no node built-ins), so the page, the routes and the
+// tests agree. The store is cases.mjs.
+import { isoDate } from "./facets.mjs";
+import { isLocalOnly } from "./rules.mjs";
+
+/** The name of the group of quotes in no section. */
+export const UNSORTED = "Unsorted";
+
+/**
+ * The board in order: Unsorted first (when it holds anything, or when there
+ * are no sections at all), then each section with its quotes.
+ *
+ * @param {{ sections: { id: string, title: string }[], quotes: { id: string, section: string | null }[] }} doc
+ */
+export function groupsOf(doc) {
+ const byId = new Map(doc.sections.map((s) => [s.id, { id: s.id, title: s.title, quotes: [] }]));
+ const unsorted = { id: null, title: UNSORTED, quotes: [] };
+ for (const q of doc.quotes) (q.section && byId.get(q.section) ? byId.get(q.section) : unsorted).quotes.push(q);
+ const out = [...byId.values()];
+ return unsorted.quotes.length || out.length === 0 ? [unsorted, ...out] : out;
+}
+
+/** Every group, Unsorted included even when empty (the moves walk it). */
+function allGroups(doc) {
+ const g = groupsOf(doc);
+ return g[0]?.id === null ? g : [{ id: null, title: UNSORTED, quotes: [] }, ...g];
+}
+
+const arrangement = (doc, groups) => ({
+ sections: doc.sections.map((s) => ({ id: s.id, title: s.title })),
+ order: groups.flatMap((g) => g.quotes.map((q) => ({ id: q.id, section: g.id }))),
+});
+
+/**
+ * Move a quote one place down (+1) or up (-1) in board order; past the end of
+ * its section it goes into the next (or the previous) one. Answers the new
+ * arrangement for PATCH, or null when it cannot move.
+ */
+export function moveQuote(doc, qid, dir) {
+ const groups = allGroups(doc).map((g) => ({ ...g, quotes: [...g.quotes] }));
+ const gi = groups.findIndex((g) => g.quotes.some((q) => q.id === qid));
+ if (gi < 0) return null;
+ const g = groups[gi];
+ const i = g.quotes.findIndex((q) => q.id === qid);
+ const [q] = g.quotes.splice(i, 1);
+ if (dir > 0) {
+ if (i < g.quotes.length) g.quotes.splice(i + 1, 0, q);
+ else if (gi < groups.length - 1) groups[gi + 1].quotes.unshift(q);
+ else return null;
+ } else {
+ if (i > 0) g.quotes.splice(i - 1, 0, q);
+ else if (gi > 0) groups[gi - 1].quotes.push(q);
+ else return null;
+ }
+ return arrangement(doc, groups);
+}
+
+/** Put a quote in a section (null = Unsorted) at an index of it (drag and drop). */
+export function placeQuote(doc, qid, section, index) {
+ const groups = allGroups(doc).map((g) => ({ ...g, quotes: g.quotes.filter((q) => q.id !== qid) }));
+ const q = doc.quotes.find((x) => x.id === qid);
+ const to = groups.find((g) => g.id === (section ?? null));
+ if (!q || !to) return null;
+ const at = Math.max(0, Math.min(to.quotes.length, Number.isInteger(index) ? index : to.quotes.length));
+ to.quotes.splice(at, 0, q);
+ return arrangement(doc, groups);
+}
+
+/** Move a section one place down (+1) or up (-1); null when it cannot. */
+export function moveSection(doc, sid, dir) {
+ const i = doc.sections.findIndex((s) => s.id === sid);
+ const j = i + (dir > 0 ? 1 : -1);
+ if (i < 0 || j < 0 || j >= doc.sections.length) return null;
+ const sections = doc.sections.map((s) => ({ id: s.id, title: s.title }));
+ [sections[i], sections[j]] = [sections[j], sections[i]];
+ return { sections, order: doc.quotes.map((q) => ({ id: q.id, section: q.section })) };
+}
+
+// ── the words ──
+
+/** Words as a re-verify compares them: case, punctuation and spacing aside. */
+export function wordsOf(text) {
+ return String(text ?? "")
+ .toLowerCase()
+ .replace(/[‘’ʼ`]/g, "'")
+ .replace(/[^\p{L}\p{N}' ]+/gu, " ")
+ .replace(/'+/g, "'")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+/** Do `inside`'s words hold `quote`'s, in order and whole? */
+export function holdsWords(inside, quote) {
+ const q = wordsOf(quote);
+ if (!q) return false;
+ return ` ${wordsOf(inside)} `.includes(` ${q} `);
+}
+
+// ── the export: cited markdown in the house format ──
+
+const clean = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
+// A claim never carries quotation marks (common's CLAIM_QUOTES_RULE): every
+// quoted span before a link becomes THAT link's quote.
+const claimText = (s) => clean(s).replace(/["“”]/g, "").replace(/[.:;,\s]+$/, "");
+// Inside the quote, a double quote would end it early for the converter.
+const quoteText = (s) => clean(s).replace(/["“”]/g, "'");
+
+/** The citation link of a quote, in the house format (facets.mjs citationText's label). */
+export function citeLink(q) {
+ const c = q.cite;
+ const label = c.kind === "post" ? `post by ${clean(c.author || c.channelName)}, ${isoDate(c.date)}` : `${clean(c.title).replace(/[[\]]/g, "")} @ ${c.clock || "0:00"}`;
+ return c.url ? `[${label}](${c.url})` : label;
+}
+
+/** One finding: the claim in plain words, the quote, its link; our note under it. */
+export function findingOf(q) {
+ const claim = claimText(q.claim);
+ const lines = [`- ${claim ? `${claim}: ` : ""}"${quoteText(q.text)}" — ${citeLink(q)}`];
+ const asides = [];
+ if (clean(q.note)) asides.push(clean(q.note).replace(/["“”]/g, "'"));
+ if (!q.speakerChecked && q.cite.kind !== "post") asides.push("Speaker not checked");
+ if (q.verify?.status === "drifted") asides.push(`Drifted: the transcript read differently at the last re-verify (${(q.verify.at || "").slice(0, 10)})`);
+ if (q.verify?.status === "missing") asides.push("Missing: the recording was not found at the last re-verify");
+ if (q.verify?.enOrig) asides.push(`The en-orig track differs here: check the audio`);
+ if (asides.length) lines.push(` Note: ${asides.join(". ")}.`);
+ return lines.join("\n");
+}
+
+/**
+ * The board as cited markdown, the shape a /sweep report has (it converts as
+ * one: common's convertSweep): `# title`, the summary, a `##` per section with
+ * one finding per quote, and `## Coverage`.
+ *
+ * @param {object} doc the case
+ * @param {{ sourceLabel?: string, read?: number }} [ctx]
+ */
+export function exportMarkdown(doc, ctx = {}) {
+ const out = [`# ${clean(doc.title)}`, ""];
+ const notes = String(doc.notes ?? "").trim();
+ if (notes) out.push(notes.replace(/^#+\s*/gm, ""), "");
+ const recordings = new Set(doc.quotes.map((q) => `${q.cite.channel}/${q.cite.video}`));
+ out.push(
+ `${doc.quotes.length} ${doc.quotes.length === 1 ? "quote" : "quotes"} from ${recordings.size} ${recordings.size === 1 ? "source" : "sources"}, pinned on a research board${doc.scope.query ? ` from the search “${clean(doc.scope.query).replace(/["“”]/g, "'")}”` : ""}. The quotes are verbatim snapshots; the claims and notes are ours.`,
+ "",
+ );
+ const groups = groupsOf(doc).filter((g) => g.quotes.length);
+ const named = doc.sections.length > 0;
+ for (const g of groups) {
+ out.push(`## ${g.id === null ? (named ? UNSORTED : "Findings") : clean(g.title)}`, "");
+ for (const q of g.quotes) out.push(findingOf(q));
+ out.push("");
+ }
+ out.push("## Coverage", "", coverageLine(doc, ctx), "");
+ return out.join("\n");
+}
+
+/** The coverage paragraph: the scope, what was searched and read, what is pinned. */
+export function coverageLine(doc, ctx = {}) {
+ const s = doc.scope;
+ const where = ctx.sourceLabel || doc.search?.sourceLabel || (s.source ? s.source.replace(/^(local|remote|hub):/, "") : "an unrecorded source");
+ const scope = [
+ s.channels?.length ? `channels ${s.channels.join(", ")}` : "every channel",
+ s.dateFrom || s.dateTo ? `${s.dateFrom ? `from ${s.dateFrom}` : ""}${s.dateFrom && s.dateTo ? " " : ""}${s.dateTo ? `to ${s.dateTo}` : ""}` : "",
+ s.states?.length ? `states ${s.states.join(", ")}` : "",
+ s.mediaType ? `${s.mediaType}s only` : "",
+ s.posts ? "posts included" : "",
+ ].filter(Boolean);
+ const parts = [`Scope: ${where}, ${scope.join(", ")}.`];
+ const se = doc.search;
+ if (se && se.total >= 0 && se.session) {
+ parts.push(
+ `Searched for ${se.query ? `“${se.query}”` : "the question"}: ${se.total} ${se.total === 1 ? "recording" : "recordings"}, ${se.complete ? "complete" : `PARTIAL (not reached: ${se.notReached.join(", ") || "unknown"})`}.`,
+ );
+ if (Number.isFinite(ctx.read)) parts.push(`Read ${ctx.read} of ${se.total}.`);
+ } else {
+ parts.push("No search is recorded for this board.");
+ }
+ const drift = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
+ const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length;
+ parts.push(
+ `${doc.quotes.length} pinned.` +
+ (drift ? ` ${drift} drifted or missing at the last re-verify.` : "") +
+ (unchecked ? ` ${unchecked} with the speaker not checked.` : ""),
+ );
+ return parts.join(" ");
+}
+
+/** Quotes from a local-only channel (Candace's): never in anything published. */
+export const localOnlyQuotes = (doc) => doc.quotes.filter((q) => q.cite.localOnly || isLocalOnly(q.cite.channel));
+
+/** A safe file name for the download. */
+export const exportFileName = (doc) => `${doc.id}.md`;
diff --git a/umtool/lib/research/board.test.mjs b/umtool/lib/research/board.test.mjs
@@ -0,0 +1,83 @@
+// The board as data (board.mjs): its groups, the moves the keys and drag
+// make, the words compare, and the export in the house format.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { coverageLine, exportMarkdown, findingOf, groupsOf, holdsWords, moveQuote, moveSection, placeQuote, wordsOf } from "./board.mjs";
+
+const q = (id, section, extra = {}) => ({
+ id,
+ section,
+ text: `words of ${id}`,
+ cite: { kind: "video", source: "remote:https://a.example", channel: "harbor-radio", video: `v-${id}`, title: `Episode ${id}`, date: "20240520", t: 10, end: 13.8, clock: "0:10", url: `https://a.example/?v=harbor-radio%2Fv-${id}&t=10` },
+ claim: "",
+ note: "",
+ speakerChecked: false,
+ pinnedAt: "",
+ ...extra,
+});
+const doc = (quotes, sections = [{ id: "s1", title: "First" }, { id: "s2", title: "Second" }]) => ({
+ id: "board",
+ title: "Employee count",
+ scope: { source: "remote:https://a.example", query: "how many employees" },
+ search: null,
+ sections,
+ quotes,
+ notes: "",
+});
+const ids = (a) => a.order.map((o) => `${o.id}:${o.section ?? "-"}`).join(" ");
+
+test("groups: Unsorted first only when it holds anything (or there are no sections), then each section", () => {
+ assert.deepEqual(groupsOf(doc([q("q1", "s2"), q("q2", "s1")])).map((g) => [g.id, g.quotes.map((x) => x.id)]), [["s1", ["q2"]], ["s2", ["q1"]]]);
+ assert.deepEqual(groupsOf(doc([q("q1", null), q("q2", "s1")])).map((g) => g.id), [null, "s1", "s2"]);
+ assert.deepEqual(groupsOf(doc([], [])).map((g) => g.title), ["Unsorted"]);
+});
+
+test("alt+j/k: a quote moves within its section, then across into the next or the previous", () => {
+ const d = doc([q("q1", null), q("q2", "s1"), q("q3", "s1"), q("q4", "s2")]);
+ assert.equal(ids(moveQuote(d, "q2", 1)), "q1:- q3:s1 q2:s1 q4:s2");
+ assert.equal(ids(moveQuote(d, "q3", 1)), "q1:- q2:s1 q3:s2 q4:s2", "past the end of s1 into the top of s2");
+ assert.equal(ids(moveQuote(d, "q2", -1)), "q1:- q2:- q3:s1 q4:s2", "past the top of s1 into Unsorted's end");
+ assert.equal(moveQuote(d, "q1", -1), null);
+ assert.equal(moveQuote(d, "q4", 1), null);
+ const noUnsorted = doc([q("q2", "s1")]);
+ assert.equal(ids(moveQuote(noUnsorted, "q2", -1)), "q2:-", "Unsorted is above the first section even when empty");
+});
+
+test("drag: a quote placed in a section at an index; a section moved", () => {
+ const d = doc([q("q1", null), q("q2", "s1"), q("q3", "s1")]);
+ assert.equal(ids(placeQuote(d, "q1", "s1", 1)), "q2:s1 q1:s1 q3:s1");
+ assert.equal(ids(placeQuote(d, "q3", "s2", 0)), "q1:- q2:s1 q3:s2");
+ assert.deepEqual(moveSection(d, "s1", 1).sections.map((s) => s.id), ["s2", "s1"]);
+ assert.equal(moveSection(d, "s1", -1), null);
+});
+
+test("words: case, punctuation and spacing aside; whole words, in order", () => {
+ assert.equal(wordsOf(" How many EMPLOYEES? You fired them all, "), "how many employees you fired them all");
+ assert.equal(holdsWords("okay so — How many employees? You fired them all, right", "how many employees you fired them all"), true);
+ assert.equal(holdsWords("they voted the budget down eight to one", "they voted the budget down nine to one"), false);
+ assert.equal(holdsWords("the budgets", "the budget"), false, "a word is whole");
+ assert.equal(holdsWords("it’s fine", "it's fine"), true);
+});
+
+test("a finding: the claim (no quotation marks), the quote, its link; our notes after it", () => {
+ const f = findingOf(q("q1", null, { claim: 'He said "no".', note: "Panel, not Jeremy", text: 'a "quoted" word' }));
+ assert.equal(
+ f,
+ '- He said no: "a \'quoted\' word" — [Episode q1 @ 0:10](https://a.example/?v=harbor-radio%2Fv-q1&t=10)\n Note: Panel, not Jeremy. Speaker not checked.',
+ );
+ assert.equal(findingOf(q("q2", null, { speakerChecked: true })), '- "words of q2" — [Episode q2 @ 0:10](https://a.example/?v=harbor-radio%2Fv-q2&t=10)');
+ const post = findingOf(q("q3", null, { cite: { kind: "post", channel: "x", video: "p1", author: "Ann", date: "20250101", url: "https://a.example/?v=x%2Fp1&vm=post" } }));
+ assert.match(post, /^- "words of q3" — \[post by Ann, 2025-01-01\]\(https:\/\/a\.example\/\?v=x%2Fp1&vm=post\)$/);
+ assert.match(findingOf(q("q4", null, { verify: { status: "drifted", at: "2026-10-14T00:00:00Z" } })), /Drifted: the transcript read differently at the last re-verify \(2026-10-14\)/);
+});
+
+test("the export: title, summary, a heading per section (Findings when there are none), Coverage", () => {
+ const md = exportMarkdown(doc([q("q1", "s2"), q("q2", null, { speakerChecked: true }), q("q3", "s2")]), { sourceLabel: "Jeralyzer", read: 2 });
+ const heads = md.split("\n").filter((l) => l.startsWith("#"));
+ assert.deepEqual(heads, ["# Employee count", "## Unsorted", "## Second", "## Coverage"]);
+ assert.match(md, /3 quotes from 3 sources, pinned on a research board from the search “how many employees”/);
+ assert.ok(md.indexOf("words of q1") < md.indexOf("words of q3"), "board order");
+ const bare = exportMarkdown(doc([q("q1", null)], []));
+ assert.ok(bare.includes("\n## Findings\n"));
+ assert.match(coverageLine({ ...doc([q("q1", null)]), search: { session: "FAKE-TEST-VALUE", query: "q", total: 27, complete: false, notReached: ["a"], at: "" } }, { read: 5 }), /27 recordings, PARTIAL \(not reached: a\)\. Read 5 of 27\. 1 pinned\. 1 with the speaker not checked\./);
+});
diff --git a/umtool/lib/research/boards.test.ts b/umtool/lib/research/boards.test.ts
@@ -0,0 +1,180 @@
+// Research boards (R2) over the e2e fixture corpus, as the routes run them: a
+// pin reads the cite from the corpus and keeps it as a snapshot; re-verify
+// reads it again and says what drifted (and where `en` and `en-orig`
+// differ); the export converts as a /sweep report (common's converter); the
+// hand-offs plan, and confirm -- an article as a seeded report-draft sweep
+// the editor is asked for, a video as a scaffolded project.
+//
+// Run with: pnpm --filter umtool exec tsx --test lib/research/boards.test.ts
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+
+let tmp: string;
+let pub: string;
+let source: string;
+let editor: http.Server;
+const asked: { url: string; body: Record<string, unknown> }[] = [];
+// The modules read their env at import, so they are imported after it is set.
+let lib: {
+ boards: typeof import("./boards");
+ handoff: typeof import("./handoff");
+ fixture: typeof import("../../e2e/fixtures/research-fixture.mjs");
+ sweepToReport: typeof import("yt-dlp-transcript-common/lib/report/convertSweep").sweepToReport;
+};
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-boards-"));
+ const fixture = await import("../../e2e/fixtures/research-fixture.mjs");
+ pub = fixture.makeResearchFixture({ dest: tmp, channels: path.join(tmp, "channels") }).pub;
+ source = `local:${pub}`;
+ fixture.makeBoardFixture({ reportsRoot: path.join(tmp, "reports"), pub });
+ // A stand-in editor: the policy, and report-draft (it records what it was asked).
+ editor = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ asked.push({ url: req.url ?? "", body: raw ? JSON.parse(raw) : {} });
+ res.setHeader("content-type", "application/json");
+ if (req.url?.startsWith("/api/ops/settings")) {
+ res.end(JSON.stringify({ ok: true, value: { routes: { sweep: "code" }, models: { api: "claude-sonnet-5-5" }, caps: { sweep: 4, max: 10 } } }));
+ } else if (req.url === "/api/ops/report-draft") {
+ res.end(JSON.stringify({ ok: true, jobId: "job-1", iteration: 1 }));
+ } else {
+ res.statusCode = 404;
+ res.end(JSON.stringify({ error: "no route" }));
+ }
+ });
+ });
+ await new Promise<void>((r) => editor.listen(0, "127.0.0.1", r));
+ process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${(editor.address() as AddressInfo).port}`;
+ process.env.WORKER_TOKEN = "t";
+ process.env.TRANSCRIPT_LOCAL_DIR = pub;
+ process.env.CHANNELS_DIR = path.join(tmp, "channels");
+ process.env.SITES_DIR = path.join(tmp, "sites");
+ process.env.ARTICLES_DIR = path.join(tmp, "articles");
+ process.env.REPORTS_DIR = path.join(tmp, "reports");
+ process.env.SETTINGS_FILE = path.join(tmp, "settings.json");
+ delete process.env.TRANSCRIPT_HUB_URL;
+ lib = {
+ boards: await import("./boards"),
+ handoff: await import("./handoff"),
+ fixture,
+ sweepToReport: (await import("yt-dlp-transcript-common/lib/report/convertSweep")).sweepToReport,
+ };
+});
+
+after(async () => {
+ editor.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+test("a pin reads the cue from the corpus: the words, the cite, the house citation; twice is one quote", async () => {
+ const { boards } = lib;
+ const c = await boards.createCase({ query: "lighthouse budget", scope: { source } });
+ assert.equal(c.id, "lighthouse-budget");
+ const search = { session: "00112233aabbccdd", query: "lighthouse budget", total: 8, complete: true, notReached: [] };
+ // 1213 s: the nearest cue starts at 1212 (a snippet's second is its cue's).
+ const r = await boards.pinQuote(c.id, { source, channel: "harbor-radio", video: "hr-2021a", t: 1213, search });
+ assert.equal(r.duplicate, false);
+ assert.equal(r.quote.text, "who signed off on the lighthouse budget");
+ assert.equal(r.quote.cite.t, 1212);
+ assert.equal(r.quote.cite.end, 1215.8);
+ assert.equal(r.quote.cite.url, "https://archive.example/?v=harbor-radio%2Fhr-2021a&t=1212");
+ assert.equal(r.quote.cite.citation, '"who signed off on the lighthouse budget" [Harbor Radio 52: storm season @ 20:12](https://archive.example/?v=harbor-radio%2Fhr-2021a&t=1212)');
+ assert.equal(r.case.search?.session, search.session);
+ const again = await boards.pinQuote(c.id, { source, channel: "harbor-radio", video: "hr-2021a", t: 1212 });
+ assert.equal(again.duplicate, true);
+ // Several cues as one quote.
+ const two = await boards.pinQuote(c.id, { source, channel: "night-desk", video: "nd-2023", t: 400, until: 404 });
+ assert.match(two.quote.text, /^the keeper never saw the lighthouse budget \S/);
+ // A Rumble mirror keeps the editor's directory id beside the archive's.
+ const rumble = await boards.pinQuote(c.id, { source, channel: "harbor-radio-rumble", video: "v2efgh", t: 32 });
+ assert.equal(rumble.quote.cite.dirVideo, undefined, "the fixture's URL slug is the title, not an id: nothing mapped");
+ // A local-only channel is marked.
+ const lo = await boards.pinQuote(c.id, { source, channel: "candace-owens", video: "lo-2025", t: 12 });
+ assert.equal(lo.quote.cite.localOnly, true);
+ await assert.rejects(boards.pinQuote(c.id, { source, channel: "night-desk", video: "nope", t: 1 }), /no recording nope/);
+ await assert.rejects(boards.pinQuote(c.id, { source: "local:/elsewhere", channel: "night-desk", video: "nd-2023", t: 1 }), (e: Error & { status?: number }) => e.status === 400 || e.status === 404);
+});
+
+test("re-verify: an intact quote is ok, a changed one drifted with old and new, en vs en-orig flagged", async () => {
+ const { boards, fixture } = lib;
+ const { case: doc, results } = await boards.verifyCase(fixture.BOARD_CASE);
+ const by = Object.fromEntries(results.map((r) => [r.id, r.verify]));
+ assert.equal(by.q1.status, "drifted");
+ assert.equal(by.q1.now, fixture.DRIFTED_QUOTE.now);
+ assert.equal(doc.quotes.find((q) => q.id === "q1")!.text, fixture.DRIFTED_QUOTE.was, "never silently updated");
+ assert.equal(by.q2.status, "ok");
+ assert.equal(by.q2.nowAt, undefined, "where it was pinned");
+ assert.equal(by.q2.message, undefined);
+ assert.equal(by.q2.enOrig, undefined);
+ assert.equal(by.q3.status, "ok", "the en words are what the en track says");
+ assert.deepEqual(by.q3.enOrig, { text: fixture.EN_REWRITE.orig, quoted: "en", other: fixture.EN_REWRITE.en });
+ // The operator takes the current words: the old kept.
+ const took = await boards.patchQuote(fixture.BOARD_CASE, "q1", { useCurrentWords: true });
+ assert.equal(took.quote.text, fixture.DRIFTED_QUOTE.now);
+ assert.equal(took.quote.history?.[0].text, fixture.DRIFTED_QUOTE.was);
+});
+
+test("the export is cited markdown that converts as a /sweep report: one citation per quote, verbatim", async () => {
+ const { boards, sweepToReport } = lib;
+ const { markdown } = await boards.exportCase("lighthouse-budget");
+ assert.match(markdown, /^# lighthouse budget\n/);
+ assert.match(markdown, /## Coverage\n\nScope: Local corpus, every channel\. Searched for “lighthouse budget”: 8 recordings, complete\. Read 0 of 8\. 4 pinned\./);
+ const converted = await sweepToReport(markdown, { id: "lighthouse-budget" });
+ assert.deepEqual(converted.problems, [], JSON.stringify(converted.problems));
+ const cites = Object.values((converted.report as { citations: Record<string, { quote: string; id: string }> }).citations);
+ assert.equal(cites.length, 4);
+ assert.ok(cites.some((c) => c.quote === "who signed off on the lighthouse budget" && c.id === "hr-2021a"), JSON.stringify(cites));
+});
+
+test("hand-off to an article: refused for a local-only board; else a plan, then a seeded sweep the editor is asked for", async () => {
+ const { boards, handoff } = lib;
+ const refused = await handoff.planArticle("lighthouse-budget");
+ assert.match(refused.plan.refusals.join(" "), /local-only channel/);
+ await assert.rejects(handoff.confirmArticle("lighthouse-budget", {}), /local-only/);
+
+ const doc = await boards.readCase("lighthouse-budget");
+ const lo = doc.quotes.find((q) => q.cite.localOnly)!;
+ await boards.deleteQuote("lighthouse-budget", lo.id);
+ const { plan, seed } = await handoff.planArticle("lighthouse-budget");
+ assert.deepEqual(plan.refusals, []);
+ assert.equal(plan.article, "lighthouse-budget");
+ assert.equal(plan.question, "lighthouse budget");
+ assert.deepEqual(plan.channels.sort(), ["harbor-radio", "harbor-radio-rumble", "night-desk"]);
+ assert.equal(plan.model, "claude-sonnet-5-5");
+ assert.equal(plan.capUsd, 4);
+ assert.match(plan.warnings.join(" "), /routes sweeps to Claude Code; a seeded sweep runs the API agent/);
+ const before = asked.length;
+ const out = await handoff.confirmArticle("lighthouse-budget", {});
+ assert.deepEqual(out, { href: "/articles/lighthouse-budget", jobId: "job-1", iteration: 1 });
+ const sent = asked.slice(before).find((a) => a.url === "/api/ops/report-draft")!.body;
+ assert.equal(sent.task, "sweep");
+ assert.equal(sent.seed, seed);
+ assert.equal(sent.source, source);
+ assert.equal((await boards.readCase("lighthouse-budget")).handoffs[0].href, "/articles/lighthouse-budget");
+});
+
+test("hand-off to a video: a plan, then a project whose timeline is the board's cue spans", async () => {
+ const { boards, handoff } = lib;
+ const plan = await handoff.planVideo("lighthouse-budget");
+ assert.deepEqual(plan.refusals, []);
+ assert.equal(plan.siteOrigin, "https://archive.example");
+ assert.equal(plan.clips.length, 3);
+ assert.deepEqual(plan.clips[0], { id: "c00", channel: "harbor-radio", video: "hr-2021a", start: 1212, end: 1215.8, quote: "who signed off on the lighthouse budget" });
+ const out = await handoff.confirmVideo("lighthouse-budget", {});
+ assert.equal(out.href, "/projects/lighthouse-budget");
+ const manifest = JSON.parse(await readFile(path.join(tmp, "reports", "lighthouse-budget", "video.manifest.json"), "utf8"));
+ assert.equal(manifest.provenance.siteOrigin, "https://archive.example");
+ assert.deepEqual(manifest.timeline.map((c: { id: string; cite: number }) => [c.id, c.cite]), [["c00", 1212], ["c01", 400], ["c02", 32]]);
+ const readme = await readFile(path.join(tmp, "reports", "lighthouse-budget", "README.md"), "utf8");
+ assert.match(readme, /## Clips from the research board “lighthouse budget” \(c:lighthouse-budget\) — review each/);
+ const again = await handoff.planVideo("lighthouse-budget");
+ assert.match(again.refusals.join(" "), /already exists/);
+ assert.equal((await boards.readCase("lighthouse-budget")).handoffs.length, 2);
+});
diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts
@@ -0,0 +1,341 @@
+import { findPost, findVideo } from "yt-dlp-transcript-mcp/research";
+import { cuesOfTrack, trackKind } from "yt-dlp-transcript-common/lib/captionTracks";
+import { momentUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl";
+import { clock } from "yt-dlp-transcript-common/lib/search/window";
+import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { REPORTS_ROOT } from "../paths.mjs";
+import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes, wordsOf } from "./board.mjs";
+import {
+ CaseError,
+ addQuote,
+ arrangeCase,
+ createCase as createAt,
+ listCases as listAt,
+ mutateCase,
+ patchCaseFields,
+ patchQuote as patchQuoteIn,
+ readCase as readAt,
+ recordVerify,
+ removeQuote,
+ storedPath,
+} from "./cases.mjs";
+import { windowOf } from "./corpus";
+import { citationText, isoDate, trackOf } from "./facets.mjs";
+import { readLog } from "./log.mjs";
+import { isLocalOnly } from "./rules.mjs";
+import { listSources, openSource, SourceError } from "./sources";
+import type { BoardGroup, CaseDoc, CaseScope, CaseSummary, CaseView, Quote, QuoteCite, QuoteVerify } from "./case-types";
+
+// ---------------------------------------------------------------------------
+// RESEARCH BOARDS, server side (plans/umtool-redesign.md, R2): the case store
+// (cases.mjs) bound to REPORTS_ROOT and typed; a PIN, which reads the cited
+// moment from the corpus and keeps it as a snapshot; RE-VERIFY, which reads
+// it again; the board's view and its export.
+//
+// Read-only on the corpus, as all of Research: every read is the MCP engine's
+// (findVideo, findPost, R1's windowOf). A case is umtool's own state.
+// ---------------------------------------------------------------------------
+
+export { CaseError };
+
+export const listCases = (): Promise<CaseSummary[]> => listAt(REPORTS_ROOT) as Promise<CaseSummary[]>;
+export const readCase = (id: string): Promise<CaseDoc> => readAt(REPORTS_ROOT, id) as Promise<CaseDoc>;
+
+export type CreateCaseInput = { title?: string; id?: string; scope?: Partial<CaseScope>; query?: string; notes?: string };
+export const createCase = (input: CreateCaseInput): Promise<CaseDoc> => createAt(REPORTS_ROOT, input) as unknown as Promise<CaseDoc>;
+
+/** One change to a case, read and written inside the store's lock (cases.mjs mutateCase). */
+export async function mutateBoard<T>(id: string, fn: (doc: CaseDoc) => T | Promise<T>): Promise<{ case: CaseDoc; result: T }> {
+ return (await mutateCase(REPORTS_ROOT, id, fn as never)) as unknown as { case: CaseDoc; result: T };
+}
+const mutate = mutateBoard;
+
+/** The board's groups in order (board.mjs groupsOf), typed. */
+export const boardGroups = (doc: CaseDoc): BoardGroup[] => groupsOf(doc) as unknown as BoardGroup[];
+
+/** PATCH a case: title, notes, scope, and the board's arrangement (sections, order). */
+export async function patchCase(id: string, body: Record<string, unknown>): Promise<CaseDoc> {
+ const known = ["title", "notes", "scope", "sections", "order"];
+ const unknown = Object.keys(body).filter((k) => !known.includes(k));
+ if (unknown.length) throw new CaseError(`not a case field: ${unknown.join(", ")} (a case takes ${known.join(", ")})`);
+ return (
+ await mutate(id, (doc) => {
+ patchCaseFields(doc, body);
+ if (body.sections !== undefined || body.order !== undefined) arrangeCase(doc, { sections: body.sections, order: body.order });
+ })
+ ).case;
+}
+
+export async function patchQuote(id: string, qid: string, body: Record<string, unknown>): Promise<{ case: CaseDoc; quote: Quote }> {
+ const known = ["claim", "note", "section", "speakerChecked", "useCurrentWords"];
+ const unknown = Object.keys(body).filter((k) => !known.includes(k));
+ if (unknown.length) throw new CaseError(`not a quote field: ${unknown.join(", ")} (a quote takes ${known.join(", ")})`);
+ const r = await mutate(id, (doc) => patchQuoteIn(doc, qid, body) as Quote);
+ return { case: r.case, quote: r.result };
+}
+
+export async function deleteQuote(id: string, qid: string): Promise<{ case: CaseDoc; quote: Quote; index: number }> {
+ const r = await mutate(id, (doc) => removeQuote(doc, qid) as { quote: Quote; index: number });
+ return { case: r.case, ...r.result };
+}
+
+// ── a pin: the cited moment, read from the corpus, kept as a snapshot ──
+
+export type PinRequest = {
+ source: string;
+ /** The channel's key in the source (a hub's `<site>:<slug>`), or its slug. */
+ channel: string;
+ video: string;
+ /** The cited second (a snippet's, or the reader's lit cue's). */
+ t: number;
+ /** The last cue's second, to pin several cues as one quote. */
+ until?: number;
+ /** An alternate caption track, when the hit was in one. */
+ track?: string;
+ kind?: "video" | "post";
+};
+
+const VIDEO_ID = /^[\w-]{1,128}$/;
+const MAX_PIN_CUES = 12;
+
+/** The words at a cite, and everything a citation needs, read now from the corpus. */
+export async function snapshotOf(req: PinRequest): Promise<{ text: string; cite: QuoteCite }> {
+ const opened = await openSource(req.source);
+ const { source, option } = opened;
+ if (req.kind === "post") {
+ const found = await findPost(source, req.video, req.channel);
+ if (!found) throw new SourceError(`no post ${req.video} in ${option.label}`, 404);
+ const { ch, post } = found;
+ const author = post.authorName || post.author;
+ const url = viewerPostUrl(ch.siteUrl ?? source.publicOrigin(), post.slug) ?? post.url ?? null;
+ return {
+ text: String(post.text ?? "").slice(0, 3000),
+ cite: {
+ kind: "post",
+ source: option.handle,
+ channel: ch.slug,
+ channelKey: ch.key,
+ channelName: ch.name,
+ ...(ch.siteTitle ? { site: ch.siteTitle } : {}),
+ video: post.id,
+ title: `Post by ${author}`,
+ date: post.uploadDate,
+ t: 0,
+ end: 0,
+ track: "post",
+ url,
+ citation: citationText({ quote: post.text, title: "", post: { author, date: isoDate(post.uploadDate) }, url }),
+ author,
+ ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}),
+ },
+ };
+ }
+ const found = await findVideo(source, req.video, req.channel);
+ if (!found) throw new SourceError(`no recording ${req.video} in ${option.label}`, 404);
+ const { ch, record } = found;
+ const cues = (cuesOfTrack(record, req.track) ?? []).filter((c) => c && typeof c.start === "number");
+ if (!cues.length) throw new SourceError(`${record.title} has no cues${req.track ? ` on the ${req.track} track` : ""} to quote`, 404);
+ const nearest = (t: number) => {
+ let best = 0;
+ for (let i = 1; i < cues.length; i++) if (Math.abs(cues[i].start - t) < Math.abs(cues[best].start - t)) best = i;
+ return best;
+ };
+ const a = nearest(req.t);
+ const b = req.until !== undefined && Number.isFinite(req.until) ? Math.max(a, Math.min(nearest(req.until), a + MAX_PIN_CUES - 1)) : a;
+ const span = cues.slice(a, b + 1);
+ const text = span.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" ").trim();
+ const start = span[0].start;
+ const end = Math.max(span[span.length - 1].end ?? start, start);
+ const url = momentUrl({ siteOrigin: ch.siteUrl ?? source.publicOrigin(), slug: record.slug, seconds: start, webpageUrl: record.webpageUrl, platform: record.platform });
+ const mapped = record.webpageUrl ? extractVideoId(record.webpageUrl) : null;
+ const alt = req.track && req.track !== record.track ? req.track : undefined;
+ return {
+ text,
+ cite: {
+ kind: "video",
+ source: option.handle,
+ channel: ch.slug,
+ channelKey: ch.key,
+ channelName: ch.name,
+ ...(ch.siteTitle ? { site: ch.siteTitle } : {}),
+ video: record.id,
+ ...(mapped && mapped !== record.id && VIDEO_ID.test(mapped) ? { dirVideo: mapped } : {}),
+ title: record.title,
+ date: record.uploadDate,
+ t: start,
+ end,
+ clock: clock(start),
+ track: trackOf((record as { transcriptFormat?: unknown }).transcriptFormat),
+ ...(alt ? { trackId: alt } : {}),
+ url,
+ citation: citationText({ quote: text, title: record.title, clock: clock(start), url }),
+ ...(record.duration ? { duration: record.duration } : {}),
+ ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}),
+ },
+ };
+}
+
+export type PinBody = PinRequest & {
+ claim?: string;
+ note?: string;
+ section?: string | null;
+ /** The search the pin came from (its session, counts): the case takes its reading log. */
+ search?: { session: string; query?: string; total?: number; complete?: boolean; notReached?: string[]; sourceLabel?: string };
+ /** The search's scope: the case's, when it has none yet. */
+ scope?: Partial<CaseScope>;
+ /** Where in the board order (an undo puts a quote back where it was). */
+ at?: number;
+};
+
+/** Pin a cite to a case. A cite already on the board answers that quote, `duplicate`. */
+export async function pinQuote(id: string, body: PinBody): Promise<{ case: CaseDoc; quote: Quote; duplicate: boolean }> {
+ await readCase(id); // a missing case is a 404 before the corpus is read
+ const snap = await snapshotOf(body);
+ const r = await mutate(id, (doc) =>
+ addQuote(
+ doc,
+ { ...snap, claim: body.claim, note: body.note, section: body.section ?? null, at: body.at },
+ { search: body.search, scope: body.scope ? { ...body.scope, source: body.scope.source ?? body.source } : { source: body.source } },
+ ) as { quote: Quote; duplicate: boolean },
+ );
+ return { case: r.case, ...r.result };
+}
+
+// ── re-verify ──
+
+export type VerifyResult = { id: string; verify: QuoteVerify };
+
+const joined = (cs: { text: string }[]) => cs.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" ");
+
+/**
+ * One quote against the CURRENT transcript at its cite: R1's window (±30 s)
+ * on the quote's track. The words found there -> ok (and where, when they
+ * moved); else drifted, with what the transcript says now. A record with
+ * both `en` and `en-orig` is read on both: the served `en` track can rewrite
+ * what was said (en-track-rewrites-content), so a difference is flagged.
+ */
+export async function verifyQuote(q: Quote, now = new Date()): Promise<QuoteVerify> {
+ const at = now.toISOString();
+ const c = q.cite;
+ try {
+ const opened = await openSource(c.source);
+ if (c.kind === "post") {
+ const found = await findPost(opened.source, c.video, c.channelKey ?? c.channel);
+ if (!found) return { status: "missing", at, message: `no post ${c.video} in ${opened.option.label} now` };
+ const text = String(found.post.text ?? "");
+ return holdsWords(text, q.text) ? { status: "ok", at } : { status: "drifted", at, now: text.slice(0, 3000) };
+ }
+ let win;
+ try {
+ win = await windowOf({ source: c.source, channel: c.channelKey ?? c.channel, video: c.video, t: c.t, span: 30, ...(c.trackId ? { track: c.trackId } : {}), kind: "video" });
+ } catch (e) {
+ if (e instanceof SourceError && e.status === 404) return { status: "missing", at, message: e.message };
+ throw e;
+ }
+ const cues = win.cues;
+ let status: QuoteVerify = { status: "ok", at };
+ if (!cues.length) {
+ status = { status: "drifted", at, now: "", message: `no cues within 30 s of ${clock(c.t)}${c.trackId ? ` on the ${c.trackId} track` : ""} now` };
+ } else if (holdsWords(joined(cues), q.text)) {
+ // Where the words start now: the cue the shortest run holding them
+ // starts with -- a run that still holds them without its first cue
+ // started too early.
+ let nowAt: number | null = null;
+ for (let i = 0; i < cues.length && nowAt === null; i++) {
+ for (let k = i; k < Math.min(cues.length, i + MAX_PIN_CUES); k++) {
+ if (!holdsWords(joined(cues.slice(i, k + 1)), q.text)) continue;
+ if (k === i || !holdsWords(joined(cues.slice(i + 1, k + 1)), q.text)) nowAt = cues[i].t;
+ break;
+ }
+ }
+ if (nowAt !== null && Math.abs(nowAt - c.t) >= 1) status = { status: "ok", at, nowAt, message: `the words now start at ${clock(nowAt)} (pinned at ${clock(c.t)})` };
+ } else {
+ // What the transcript says over the quote's own seconds now.
+ const lit = win.lit >= 0 ? win.lit : 0;
+ const length = Math.max(0, c.end - c.t);
+ const over = cues.slice(lit).filter((x, i) => i === 0 || x.t <= cues[lit].t + length - 0.25);
+ status = { status: "drifted", at, now: joined(over).slice(0, 3000), nowAt: cues[lit].t };
+ }
+ const enOrig = await enOrigCheck(opened.source, q);
+ return enOrig ? { ...status, enOrig } : status;
+ } catch (e) {
+ return { status: "unreadable", at, message: (e as Error).message };
+ }
+}
+
+async function enOrigCheck(source: Awaited<ReturnType<typeof openSource>>["source"], q: Quote): Promise<QuoteVerify["enOrig"] | undefined> {
+ const c = q.cite;
+ const found = await findVideo(source, c.video, c.channelKey ?? c.channel).catch(() => null);
+ if (!found) return undefined;
+ const rec = found.record as { track?: string; altTracks?: { track: string }[]; cues?: { start: number; end: number; text: string }[] };
+ if (!rec.track) return undefined; // the primary's id unknown: nothing to say which is which
+ const ids = [rec.track, ...(rec.altTracks ?? []).map((t) => t.track)];
+ const enId = ids.find((t) => t === "en");
+ const origId = ids.find((t) => trackKind(t) === "original");
+ if (!enId || !origId) return undefined;
+ const textOn = (track: string) => {
+ const cues = (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[];
+ return joined(cues.filter((x) => x.end > c.t + 0.25 && x.start < Math.max(c.end, c.t + 1) - 0.25));
+ };
+ const en = textOn(enId);
+ const orig = textOn(origId);
+ if (wordsOf(en) === wordsOf(orig)) return undefined;
+ const quoted = c.trackId ?? rec.track;
+ return { text: orig, quoted, other: en };
+}
+
+/** Re-verify every quote (or the ones named), record what was found, answer it. */
+export async function verifyCase(id: string, only?: string[]): Promise<{ case: CaseDoc; results: VerifyResult[] }> {
+ const doc = await readCase(id);
+ const quotes = only?.length ? doc.quotes.filter((q) => only.includes(q.id)) : doc.quotes;
+ const results: VerifyResult[] = [];
+ const now = new Date();
+ // A few at a time: each is a shard read, cached by the source.
+ for (let i = 0; i < quotes.length; i += 4) {
+ const batch = quotes.slice(i, i + 4);
+ results.push(...(await Promise.all(batch.map(async (q) => ({ id: q.id, verify: await verifyQuote(q, now) })))));
+ }
+ const r = await mutate(id, (d) => recordVerify(d, results));
+ return { case: r.case, results };
+}
+
+// ── the board's view, and its export ──
+
+export async function sourceLabelOf(handle: string): Promise<string | null> {
+ if (!handle) return null;
+ const sources = await listSources().catch(() => []);
+ return sources.find((s) => s.handle === handle)?.label ?? null;
+}
+
+async function readingOf(doc: CaseDoc): Promise<CaseView["reading"]> {
+ if (!doc.search) return null;
+ const log = await readLog(REPORTS_ROOT, doc.search.session);
+ let read = 0;
+ let skipped = 0;
+ for (const m of Object.values(log.marks)) {
+ if (m.state === "read") read++;
+ else if (m.state === "skipped") skipped++;
+ }
+ return { read, skipped, ...(log.error ? { error: log.error } : {}) };
+}
+
+export async function caseView(id: string): Promise<CaseView> {
+ const doc = await readCase(id);
+ return {
+ case: doc,
+ piece: `c:${doc.id}`,
+ stored: storedPath(doc.id),
+ sourceLabel: (await sourceLabelOf(doc.scope.source)) ?? doc.search?.sourceLabel ?? null,
+ reading: await readingOf(doc),
+ localOnly: localOnlyQuotes(doc).length,
+ };
+}
+
+/** The board as cited markdown (house format; it converts as a /sweep report). */
+export async function exportCase(id: string): Promise<{ doc: CaseDoc; markdown: string }> {
+ const view = await caseView(id);
+ return {
+ doc: view.case,
+ markdown: exportMarkdown(view.case, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }),
+ };
+}
diff --git a/umtool/lib/research/case-types.ts b/umtool/lib/research/case-types.ts
@@ -0,0 +1,189 @@
+// The research CASE's shapes (lib/research/cases.mjs is the store), shared by
+// the routes, the board page and P5's Create. Types only: safe for a client
+// component.
+
+/** A case's scope: the R1 source handle and filters, and the query that found its quotes. */
+export type CaseScope = {
+ source: string;
+ channels?: string[];
+ dateFrom?: string;
+ dateTo?: string;
+ states?: string[];
+ mediaType?: "video" | "livestream";
+ posts?: boolean;
+ query?: string;
+ regex?: boolean;
+};
+
+/** Where a quote was read: enough to cite it, re-read it, and clip it. */
+export type QuoteCite = {
+ kind: "video" | "post";
+ /** The R1 source handle it was read through. */
+ source: string;
+ /** The channel's slug (the corpus's directory name). */
+ channel: string;
+ /** The source's channel key (a hub's is `<site>:<slug>`). */
+ channelKey?: string;
+ channelName?: string;
+ site?: string;
+ /** The recording's id in the archive (Rumble: the embed id). */
+ video: string;
+ /** The editor's directory id when it is not `video` (Rumble: the URL slug). */
+ dirVideo?: string;
+ title?: string;
+ /** YYYYMMDD. */
+ date?: string;
+ /** The first cue's start, seconds. */
+ t: number;
+ /** The last cue's end, seconds. */
+ end: number;
+ clock?: string;
+ /** transcript | captions | unknown | post. */
+ track?: string;
+ /** An alternate caption track's id (`en`, `en-GB`, …) when not the primary. */
+ trackId?: string;
+ /** The moment link (a viewer link on the source's origin), or null. */
+ url: string | null;
+ /** The citation in the house format, as R1's Copy citation writes it. */
+ citation?: string;
+ duration?: number;
+ author?: string;
+ localOnly?: boolean;
+};
+
+export type VerifyState = "ok" | "drifted" | "missing" | "unreadable";
+
+/** What the last re-verify read at a quote's cite. Never applied to the quote by itself. */
+export type QuoteVerify = {
+ status: VerifyState;
+ at: string;
+ /** The words the transcript has there now (drifted). */
+ now?: string;
+ /** Where those words start now, seconds. */
+ nowAt?: number;
+ message?: string;
+ /** The record has both `en` and `en-orig` and they differ at the cite. */
+ enOrig?: { text: string; quoted: string; other: string };
+};
+
+export type Quote = {
+ /** `q<n>`. */
+ id: string;
+ /** `s<n>`, or null: Unsorted. */
+ section: string | null;
+ /** The words, verbatim, as the transcript had them when pinned. */
+ text: string;
+ cite: QuoteCite;
+ /** Ours: what the quote shows, in plain words. */
+ claim: string;
+ /** Ours. */
+ note: string;
+ /** False until the operator checked who is speaking (co-hosts, panels). */
+ speakerChecked: boolean;
+ pinnedAt: string;
+ query?: string;
+ verify?: QuoteVerify;
+ /** Earlier words, kept when the operator took the current ones. */
+ history?: { text: string; at: string; why: string }[];
+};
+
+export type CaseSection = { id: string; title: string };
+
+/** A group of the board, in order (lib/research/board.mjs groupsOf): a section, or Unsorted (id null). */
+export type BoardGroup = { id: string | null; title: string; quotes: Quote[] };
+
+/** The search a case's quotes were pinned from: its counts and its reading log. */
+export type CaseSearch = {
+ session: string;
+ query: string;
+ total: number;
+ complete: boolean;
+ notReached: string[];
+ sourceLabel?: string;
+ at: string;
+};
+
+export type CaseHandoff = { to: "article" | "video"; href: string; at: string; what?: string };
+
+export type CaseDoc = {
+ format: "umtool-research-case";
+ version: 1;
+ id: string;
+ title: string;
+ scope: CaseScope;
+ search: CaseSearch | null;
+ sessions: string[];
+ sections: CaseSection[];
+ quotes: Quote[];
+ notes: string;
+ handoffs: CaseHandoff[];
+ counters: { quote: number; section: number };
+ createdAt: string;
+ updatedAt: string;
+};
+
+/** GET /api/research/cases: one row. */
+export type CaseSummary = {
+ id: string;
+ /** `c:<case>`. */
+ piece: string;
+ title: string;
+ quotes: number;
+ sections: number;
+ updatedAt: string;
+ scope: CaseScope;
+ /** Quotes the last re-verify found drifted or missing. */
+ drifted: number;
+ /** A case.json that cannot be read: listed, never overwritten. */
+ error?: string;
+};
+
+/** GET /api/research/cases/<id>: the case and what the board shows beside it. */
+export type CaseView = {
+ case: CaseDoc;
+ piece: string;
+ /** Relative to REPORTS_ROOT. */
+ stored: string;
+ /** The source's label, when it is still offered. */
+ sourceLabel: string | null;
+ /** The reading log of the case's search: read and skipped of `search.total`. */
+ reading: { read: number; skipped: number; error?: string } | null;
+ /** Quotes from a local-only channel: no hand-off may target a public site. */
+ localOnly: number;
+};
+
+export type ArticlePlan = {
+ to: "article";
+ /** The article the sweep writes (the case id, unless the confirm names another). */
+ article: string;
+ articleExists: boolean;
+ question: string;
+ channels: string[];
+ dateFrom?: string;
+ dateTo?: string;
+ source: string;
+ model: string | null;
+ route: string | null;
+ capUsd: number | null;
+ /** The board as cited markdown: the sweep's report starts from it (seed.md). */
+ seed: { chars: number; quotes: number };
+ spends: true;
+ refusals: string[];
+ warnings: string[];
+ policyError?: string;
+};
+
+export type VideoPlan = {
+ to: "video";
+ /** The project folder under REPORTS_ROOT. */
+ slug: string;
+ title: string;
+ siteOrigin: string;
+ clips: { id: string; channel: string; video: string; start: number; end: number; quote: string }[];
+ writes: string;
+ spends: false;
+ refusals: string[];
+ warnings: string[];
+};
+
+export type HandoffPlan = ArticlePlan | VideoPlan;
diff --git a/umtool/lib/research/cases.mjs b/umtool/lib/research/cases.mjs
@@ -0,0 +1,582 @@
+// RESEARCH CASES -- the boards (plans/umtool-redesign.md, "Research,
+// first-class" 5; phase R2). A case is a question being researched: its scope
+// (the R1 source handle and filters, and the query), the quotes pinned from
+// the results or the reader as SNAPSHOTS, their sections and order, the
+// operator's claim line and note on each, and notes on the whole.
+//
+// REPORTS_ROOT/.umtool/research/<case>/case.json
+// { format: "umtool-research-case", version: 1, id, title, scope, search,
+// sessions, sections: [{ id, title }], quotes: [Quote], notes, handoffs,
+// counters: { quote, section }, createdAt, updatedAt }
+//
+// A case's piece id is `c:<case>` (lib/pieces/ids.mjs). Umtool-side, NEVER in
+// the corpus: REPORTS_ROOT's dot-dirs are state the project walk skips. The
+// reading logs (sessions/) and the census (census/) live beside the cases, so
+// their names are reserved, as are the pages under /research.
+//
+// A QUOTE IS A SNAPSHOT (lib/shortlist-types.ts `Pick`'s reasoning): the words
+// as the transcript had them when pinned, and the cite they were read at. A
+// re-transcription can change the words under a cite; re-verify (verify.ts)
+// says so, with the old and the new, and never changes the quote by itself.
+// Only the operator's explicit "use the current words" does, and the old text
+// is kept in the quote's `history`.
+//
+// The lifecycle store's discipline (lib/lifecycle.mjs): one writer, serialised
+// in-process; every write a whole file to a temp name and a rename; a file
+// that does not parse is never overwritten (a write refuses with 409 until
+// somebody fixes it; a list shows it with its error).
+//
+// Plain ESM: a unit test reads it the way the app does.
+import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { PIECE_SEGMENT_RE, casePieceId } from "../pieces/ids.mjs";
+
+export const CASE_FORMAT = "umtool-research-case";
+export const CASE_VERSION = 1;
+export const CASE_FILE = "case.json";
+
+/** Names under .umtool/research/ that are not cases, and the pages under /research. */
+export const RESERVED_CASE_IDS = Object.freeze(["sessions", "census", "archive", "runs", "cases", "new"]);
+
+export const TITLE_LIMIT = 120;
+export const CLAIM_LIMIT = 400;
+export const NOTE_LIMIT = 2000;
+export const NOTES_LIMIT = 20_000;
+export const QUOTE_LIMIT = 3000;
+export const MAX_QUOTES = 500;
+export const MAX_SECTIONS = 60;
+
+export class CaseError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.name = "CaseError";
+ this.status = status;
+ }
+}
+
+/** A case id: a piece segment (lowercase slug, ≤ 64) that is not reserved. */
+export const isCaseId = (id) => typeof id === "string" && PIECE_SEGMENT_RE.test(id) && !RESERVED_CASE_IDS.includes(id);
+
+/** A title's slug, cut to a piece segment ("" when nothing in it slugs). */
+export function slugOf(title) {
+ return String(title ?? "")
+ .toLowerCase()
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 56)
+ .replace(/-+$/, "");
+}
+
+export function researchDir(reportsRoot) {
+ return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "research");
+}
+
+export function caseDir(reportsRoot, id) {
+ return path.join(/* turbopackIgnore: true */ researchDir(reportsRoot), id);
+}
+
+export function caseFile(reportsRoot, id) {
+ return path.join(/* turbopackIgnore: true */ caseDir(reportsRoot, id), CASE_FILE);
+}
+
+/** Where a case is stored, as the board's side panel says it (relative to REPORTS_ROOT). */
+export const storedPath = (id) => `.umtool/research/${id}/`;
+
+const str = (v, limit) => (typeof v === "string" ? v.slice(0, limit) : "");
+const trimmed = (v, limit) => str(v, limit * 2).replace(/\s+/g, " ").trim().slice(0, limit);
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+/**
+ * A scope as a case keeps it: the R1 handle and filters, and the query that
+ * found the quotes. Unknown keys dropped.
+ */
+export function cleanScope(raw) {
+ const s = raw && typeof raw === "object" ? raw : {};
+ const list = (v) =>
+ (Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : [])
+ .filter((x) => typeof x === "string" && x.trim())
+ .map((x) => x.trim().slice(0, 200))
+ .slice(0, 200);
+ const out = { source: str(s.source, 2000).trim() };
+ const channels = list(s.channels);
+ if (channels.length) out.channels = channels;
+ if (typeof s.dateFrom === "string" && DATE.test(s.dateFrom)) out.dateFrom = s.dateFrom;
+ if (typeof s.dateTo === "string" && DATE.test(s.dateTo)) out.dateTo = s.dateTo;
+ const states = list(s.states);
+ if (states.length) out.states = states;
+ if (s.mediaType === "video" || s.mediaType === "livestream") out.mediaType = s.mediaType;
+ if (s.posts === true) out.posts = true;
+ const q = trimmed(s.query, 500);
+ if (q) out.query = q;
+ if (s.regex === true) out.regex = true;
+ return out;
+}
+
+const CITE_KEYS = {
+ kind: (v) => (v === "post" ? "post" : "video"),
+ source: (v) => str(v, 2000),
+ channel: (v) => str(v, 128),
+ channelKey: (v) => str(v, 200),
+ channelName: (v) => str(v, 200),
+ site: (v) => str(v, 200),
+ video: (v) => str(v, 128),
+ dirVideo: (v) => str(v, 128),
+ title: (v) => str(v, 500),
+ date: (v) => str(v, 8),
+ t: (v) => (Number.isFinite(v) && v >= 0 ? v : 0),
+ end: (v) => (Number.isFinite(v) && v >= 0 ? v : 0),
+ clock: (v) => str(v, 16),
+ track: (v) => str(v, 32),
+ trackId: (v) => str(v, 64),
+ url: (v) => (typeof v === "string" ? v.slice(0, 2000) : null),
+ citation: (v) => str(v, QUOTE_LIMIT + 2600),
+ duration: (v) => (Number.isFinite(v) && v > 0 ? v : 0),
+ author: (v) => str(v, 200),
+ localOnly: (v) => v === true,
+};
+
+function cleanCite(raw) {
+ const c = raw && typeof raw === "object" ? raw : {};
+ const out = {};
+ for (const [k, f] of Object.entries(CITE_KEYS)) {
+ if (c[k] === undefined) continue;
+ const v = f(c[k]);
+ if (v === "" || v === 0 || v === false || v === null) {
+ if (k === "t" || k === "end" || k === "url") out[k] = v;
+ continue;
+ }
+ out[k] = v;
+ }
+ out.kind ??= "video";
+ out.t ??= 0;
+ out.end ??= out.t;
+ out.url ??= null;
+ return out;
+}
+
+const VERIFY_STATES = ["ok", "drifted", "missing", "unreadable"];
+
+function cleanVerify(v) {
+ if (!v || typeof v !== "object" || !VERIFY_STATES.includes(v.status)) return undefined;
+ return {
+ status: v.status,
+ at: str(v.at, 40),
+ ...(typeof v.now === "string" ? { now: v.now.slice(0, QUOTE_LIMIT) } : {}),
+ ...(Number.isFinite(v.nowAt) ? { nowAt: v.nowAt } : {}),
+ ...(typeof v.message === "string" ? { message: v.message.slice(0, 500) } : {}),
+ ...(v.enOrig && typeof v.enOrig === "object" && typeof v.enOrig.text === "string"
+ ? { enOrig: { text: v.enOrig.text.slice(0, QUOTE_LIMIT), quoted: str(v.enOrig.quoted, 64), other: str(v.enOrig.other, QUOTE_LIMIT) } }
+ : {}),
+ };
+}
+
+function cleanQuote(q, sectionIds) {
+ const history = (Array.isArray(q.history) ? q.history : [])
+ .filter((h) => h && typeof h.text === "string")
+ .slice(-20)
+ .map((h) => ({ text: h.text.slice(0, QUOTE_LIMIT), at: str(h.at, 40), why: str(h.why, 200) }));
+ const verify = cleanVerify(q.verify);
+ return {
+ id: str(q.id, 16),
+ section: typeof q.section === "string" && sectionIds.has(q.section) ? q.section : null,
+ text: str(q.text, QUOTE_LIMIT),
+ cite: cleanCite(q.cite),
+ claim: str(q.claim, CLAIM_LIMIT),
+ note: str(q.note, NOTE_LIMIT),
+ speakerChecked: q.speakerChecked === true,
+ pinnedAt: str(q.pinnedAt, 40),
+ ...(typeof q.query === "string" && q.query ? { query: q.query.slice(0, 500) } : {}),
+ ...(verify ? { verify } : {}),
+ ...(history.length ? { history } : {}),
+ };
+}
+
+function cleanSearch(s) {
+ if (!s || typeof s !== "object" || typeof s.session !== "string" || !/^[0-9a-f]{16}$/.test(s.session)) return null;
+ const n = (v) => (Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
+ return {
+ session: s.session,
+ query: str(s.query, 500),
+ total: n(s.total),
+ complete: s.complete !== false,
+ notReached: (Array.isArray(s.notReached) ? s.notReached : []).filter((x) => typeof x === "string").slice(0, 200),
+ ...(typeof s.sourceLabel === "string" && s.sourceLabel ? { sourceLabel: s.sourceLabel.slice(0, 200) } : {}),
+ at: str(s.at, 40),
+ };
+}
+
+/**
+ * A case document from what was read, every field checked and cut to size.
+ * Throws a CaseError when it is not a case at all.
+ */
+export function normaliseCase(raw, id) {
+ if (!raw || typeof raw !== "object" || raw.format !== CASE_FORMAT) throw new CaseError(`not a ${CASE_FORMAT} file`, 409);
+ if (raw.id !== id) throw new CaseError(`case.json names "${raw.id}" but is filed under "${id}"`, 409);
+ const sections = (Array.isArray(raw.sections) ? raw.sections : [])
+ .filter((s) => s && typeof s.id === "string" && /^s\d{1,6}$/.test(s.id))
+ .slice(0, MAX_SECTIONS)
+ .map((s) => ({ id: s.id, title: trimmed(s.title, TITLE_LIMIT) || "Untitled section" }));
+ const ids = new Set(sections.map((s) => s.id));
+ const seen = new Set();
+ const quotes = [];
+ for (const q of Array.isArray(raw.quotes) ? raw.quotes : []) {
+ if (!q || typeof q.id !== "string" || !/^q\d{1,6}$/.test(q.id) || seen.has(q.id)) continue;
+ seen.add(q.id);
+ quotes.push(cleanQuote(q, ids));
+ if (quotes.length >= MAX_QUOTES) break;
+ }
+ const counter = (v, floor) => Math.max(Number.isInteger(v) && v >= 0 ? v : 0, floor);
+ const maxOf = (arr, re) => arr.reduce((m, x) => Math.max(m, Number(re.exec(x.id)?.[1] ?? 0)), 0);
+ const handoffs = (Array.isArray(raw.handoffs) ? raw.handoffs : [])
+ .filter((h) => h && (h.to === "article" || h.to === "video") && typeof h.href === "string")
+ .slice(-50)
+ .map((h) => ({ to: h.to, href: h.href.slice(0, 500), at: str(h.at, 40), ...(typeof h.what === "string" ? { what: h.what.slice(0, 300) } : {}) }));
+ return {
+ format: CASE_FORMAT,
+ version: CASE_VERSION,
+ id,
+ title: trimmed(raw.title, TITLE_LIMIT) || id,
+ scope: cleanScope(raw.scope),
+ search: cleanSearch(raw.search),
+ sessions: (Array.isArray(raw.sessions) ? raw.sessions : []).filter((s) => typeof s === "string" && /^[0-9a-f]{16}$/.test(s)).slice(-50),
+ sections,
+ quotes,
+ notes: str(raw.notes, NOTES_LIMIT),
+ handoffs,
+ counters: {
+ quote: counter(raw.counters?.quote, maxOf(quotes, /^q(\d+)$/)),
+ section: counter(raw.counters?.section, maxOf(sections, /^s(\d+)$/)),
+ },
+ createdAt: str(raw.createdAt, 40),
+ updatedAt: str(raw.updatedAt, 40),
+ };
+}
+
+/** What a list shows of a case (GET /api/research/cases). */
+export function summariseCase(c) {
+ return {
+ id: c.id,
+ piece: casePieceId(c.id),
+ title: c.title,
+ quotes: c.quotes.length,
+ sections: c.sections.length,
+ updatedAt: c.updatedAt,
+ scope: c.scope,
+ drifted: c.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length,
+ };
+}
+
+/**
+ * One case. A missing case is a 404; a file that does not parse is a 409
+ * (fix or remove it: it is never overwritten).
+ */
+export async function readCase(reportsRoot, id) {
+ if (!isCaseId(id)) throw new CaseError(`not a case id: ${JSON.stringify(id)}`, 400);
+ let text;
+ try {
+ text = await readFile(/* turbopackIgnore: true */ caseFile(reportsRoot, id), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") throw new CaseError(`no case "${id}"`, 404);
+ throw new CaseError(`${storedPath(id)}${CASE_FILE} cannot be read: ${err?.message ?? err}`, 409);
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ throw new CaseError(`${storedPath(id)}${CASE_FILE} is not JSON: ${err.message}`, 409);
+ }
+ return normaliseCase(raw, id);
+}
+
+/**
+ * Every case, newest change first. A case that cannot be read is listed with
+ * its error, never dropped (and never overwritten).
+ */
+export async function listCases(reportsRoot) {
+ const names = await readdir(/* turbopackIgnore: true */ researchDir(reportsRoot), { withFileTypes: true }).catch(() => []);
+ const out = [];
+ for (const d of names) {
+ if (!d.isDirectory() || !isCaseId(d.name)) continue;
+ try {
+ out.push(summariseCase(await readCase(reportsRoot, d.name)));
+ } catch (e) {
+ if (e?.status === 404) continue; // a directory with no case.json (a half-made one): not a case
+ out.push({ id: d.name, piece: casePieceId(d.name), title: d.name, quotes: 0, sections: 0, updatedAt: "", scope: { source: "" }, drifted: 0, error: e.message });
+ }
+ }
+ return out.sort((a, b) => (b.updatedAt || "").localeCompare(a.updatedAt || "") || a.id.localeCompare(b.id));
+}
+
+let chain = Promise.resolve();
+
+function serialised(fn) {
+ const run = chain.then(fn);
+ chain = run.catch(() => {});
+ return run;
+}
+
+async function writeCase(reportsRoot, doc) {
+ const file = caseFile(reportsRoot, doc.id);
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+}
+
+/**
+ * Create a case. `id` when given must be free (409); else the title's slug,
+ * with -2, -3 … when taken.
+ *
+ * @param {string} reportsRoot
+ * @param {{ title?: string, id?: string, scope?: object, query?: string, notes?: string, now?: Date }} input
+ */
+export function createCase(reportsRoot, input = {}) {
+ return serialised(async () => {
+ const query = trimmed(input.query ?? input.scope?.query, 500);
+ const title = trimmed(input.title, TITLE_LIMIT) || query;
+ if (!title) throw new CaseError("a case needs a title or a query");
+ let id;
+ if (input.id !== undefined) {
+ if (!isCaseId(input.id)) throw new CaseError(`not a case id: ${JSON.stringify(input.id)} (lowercase letters, digits and dashes${RESERVED_CASE_IDS.includes(input.id) ? `; "${input.id}" is reserved` : ""})`);
+ if (await exists(caseFile(reportsRoot, input.id))) throw new CaseError(`a case "${input.id}" already exists`, 409);
+ id = input.id;
+ } else {
+ const base = slugOf(title) || "case";
+ const stem = RESERVED_CASE_IDS.includes(base) ? `${base}-case` : base;
+ for (let n = 1; n < 100 && !id; n++) {
+ const cand = n === 1 ? stem : `${stem}-${n}`;
+ if (isCaseId(cand) && !(await exists(caseDir(reportsRoot, cand)))) id = cand;
+ }
+ if (!id) throw new CaseError(`every id from "${stem}" to "${stem}-99" is taken: name the case`, 409);
+ }
+ const at = (input.now ?? new Date()).toISOString();
+ const doc = normaliseCase(
+ {
+ format: CASE_FORMAT,
+ id,
+ title,
+ scope: { ...cleanScope(input.scope), ...(query ? { query } : {}) },
+ sections: [],
+ quotes: [],
+ notes: str(input.notes, NOTES_LIMIT),
+ createdAt: at,
+ updatedAt: at,
+ },
+ id,
+ );
+ await writeCase(reportsRoot, doc);
+ return doc;
+ });
+}
+
+async function exists(p) {
+ try {
+ await readFile(/* turbopackIgnore: true */ p);
+ return true;
+ } catch (e) {
+ if (e?.code === "EISDIR") return true;
+ if (e?.code === "ENOENT") return false;
+ return true;
+ }
+}
+
+/**
+ * One change to a case, read and written inside the lock. `fn(doc)` mutates
+ * the document it is given and answers what the caller returns; the result
+ * is checked again before it is written.
+ *
+ * @template T
+ * @param {string} reportsRoot
+ * @param {string} id
+ * @param {(doc: ReturnType<typeof normaliseCase>) => T | Promise<T>} fn
+ * @param {{ now?: Date }} [opts]
+ * @returns {Promise<{ case: ReturnType<typeof normaliseCase>, result: T }>}
+ */
+export function mutateCase(reportsRoot, id, fn, opts = {}) {
+ return serialised(async () => {
+ const doc = await readCase(reportsRoot, id);
+ const result = await fn(doc);
+ doc.updatedAt = (opts.now ?? new Date()).toISOString();
+ const clean = normaliseCase(doc, id);
+ await writeCase(reportsRoot, clean);
+ return { case: clean, result };
+ });
+}
+
+// ── the changes a route makes ──
+
+/** Title, notes, scope. */
+export function patchCaseFields(doc, body) {
+ if (body.title !== undefined) {
+ const t = trimmed(body.title, TITLE_LIMIT);
+ if (!t) throw new CaseError("a case's title is text");
+ doc.title = t;
+ }
+ if (body.notes !== undefined) {
+ if (typeof body.notes !== "string") throw new CaseError("notes is text");
+ doc.notes = body.notes.slice(0, NOTES_LIMIT);
+ }
+ if (body.scope !== undefined) {
+ if (!body.scope || typeof body.scope !== "object") throw new CaseError("scope is an object: { source, channels?, dateFrom?, dateTo?, states?, mediaType?, posts?, query? }");
+ doc.scope = cleanScope(body.scope);
+ }
+}
+
+/**
+ * The board's arrangement: `sections` is the whole ordered list (an entry
+ * without an id is a new section; a section left out is removed and its
+ * quotes go to Unsorted); `order` is every quote id, in board order, each
+ * with its section (null = Unsorted).
+ */
+export function arrangeCase(doc, { sections, order }) {
+ if (sections !== undefined) {
+ if (!Array.isArray(sections) || sections.length > MAX_SECTIONS) throw new CaseError(`sections is a list of up to ${MAX_SECTIONS} { id?, title }`);
+ const known = new Set(doc.sections.map((s) => s.id));
+ const seen = new Set();
+ const next = [];
+ for (const s of sections) {
+ if (!s || typeof s !== "object") throw new CaseError("a section is { id?, title }");
+ const title = trimmed(s.title, TITLE_LIMIT);
+ if (!title) throw new CaseError("a section needs a title");
+ let sid = s.id;
+ if (sid === undefined || sid === null || sid === "") sid = `s${++doc.counters.section}`;
+ else if (typeof sid !== "string" || !known.has(sid)) throw new CaseError(`no section ${JSON.stringify(sid)} in this case`);
+ if (seen.has(sid)) throw new CaseError(`section ${sid} is listed twice`);
+ seen.add(sid);
+ next.push({ id: sid, title });
+ }
+ doc.sections = next;
+ for (const q of doc.quotes) if (q.section && !seen.has(q.section)) q.section = null;
+ }
+ if (order !== undefined) {
+ if (!Array.isArray(order)) throw new CaseError("order is every quote, in board order: [{ id, section }]");
+ const byId = new Map(doc.quotes.map((q) => [q.id, q]));
+ const sids = new Set(doc.sections.map((s) => s.id));
+ const ids = order.map((o) => (typeof o === "string" ? o : o?.id));
+ if (ids.length !== byId.size || new Set(ids).size !== ids.length || ids.some((i) => !byId.has(i))) {
+ throw new CaseError("order must list every quote of the case exactly once");
+ }
+ doc.quotes = order.map((o) => {
+ const q = byId.get(typeof o === "string" ? o : o.id);
+ if (typeof o === "object" && o && "section" in o) {
+ if (o.section !== null && !sids.has(o.section)) throw new CaseError(`no section ${JSON.stringify(o.section)} in this case`);
+ q.section = o.section;
+ }
+ return q;
+ });
+ }
+}
+
+/** Claim, note, section, speaker check, or the operator's "use the current words". */
+export function patchQuote(doc, qid, body, now = new Date()) {
+ const q = doc.quotes.find((x) => x.id === qid);
+ if (!q) throw new CaseError(`no quote ${JSON.stringify(qid)} in this case`, 404);
+ if (body.claim !== undefined) {
+ if (typeof body.claim !== "string") throw new CaseError("claim is text");
+ q.claim = body.claim.replace(/\s+/g, " ").trim().slice(0, CLAIM_LIMIT);
+ }
+ if (body.note !== undefined) {
+ if (typeof body.note !== "string") throw new CaseError("note is text");
+ q.note = body.note.trim().slice(0, NOTE_LIMIT);
+ }
+ if (body.section !== undefined) {
+ if (body.section !== null && !doc.sections.some((s) => s.id === body.section)) throw new CaseError(`no section ${JSON.stringify(body.section)} in this case`);
+ q.section = body.section;
+ }
+ if (body.speakerChecked !== undefined) {
+ if (typeof body.speakerChecked !== "boolean") throw new CaseError("speakerChecked is true or false");
+ q.speakerChecked = body.speakerChecked;
+ }
+ if (body.useCurrentWords !== undefined) {
+ // Never silent: only when the operator asks, only to the words the last
+ // re-verify read, and the old words are kept.
+ if (body.useCurrentWords !== true) throw new CaseError("useCurrentWords is true");
+ const v = q.verify;
+ if (v?.status !== "drifted" || typeof v.now !== "string" || !v.now.trim()) throw new CaseError("only a quote re-verify found drifted takes the current words", 409);
+ q.history = [...(q.history ?? []), { text: q.text, at: now.toISOString(), why: `replaced by the transcript's words read ${v.at}` }];
+ q.text = v.now;
+ if (Number.isFinite(v.nowAt)) q.cite.t = v.nowAt;
+ q.verify = { status: "ok", at: v.at, message: "the current words, taken by the operator" };
+ }
+ return q;
+}
+
+/** Remove a quote; answers it (for an undo). */
+export function removeQuote(doc, qid) {
+ const i = doc.quotes.findIndex((x) => x.id === qid);
+ if (i < 0) throw new CaseError(`no quote ${JSON.stringify(qid)} in this case`, 404);
+ const [q] = doc.quotes.splice(i, 1);
+ return { quote: q, index: i };
+}
+
+/** Two pins of the same words: same recording, same second, same track. */
+export const sameCite = (a, b) =>
+ a.kind === b.kind && a.channel === b.channel && a.video === b.video && Math.abs((a.t ?? 0) - (b.t ?? 0)) < 0.5 && (a.trackId ?? "") === (b.trackId ?? "");
+
+/**
+ * Pin a snapshot. A cite already on the board is not added twice: the quote
+ * there is answered with `duplicate`. `at` (an index into the quotes) puts it
+ * back where an undo took it from.
+ *
+ * @param {ReturnType<typeof normaliseCase>} doc
+ * @param {{ text: string, cite: object, claim?: string, note?: string, section?: string | null, query?: string, at?: number }} snap
+ * @param {{ search?: object, scope?: object, now?: Date }} [ctx]
+ */
+export function addQuote(doc, snap, ctx = {}) {
+ const now = (ctx.now ?? new Date()).toISOString();
+ const cite = cleanCite(snap.cite);
+ if (!cite.channel || !cite.video) throw new CaseError("a quote's cite names its channel and recording");
+ if (typeof snap.text !== "string" || !snap.text.trim()) throw new CaseError("a quote has words");
+ const dup = doc.quotes.find((q) => sameCite(q.cite, cite));
+ // A search this pin came from becomes the case's: its reading log, its
+ // counts (searched N, read N of M) -- and its scope, when the case has none.
+ const search = cleanSearch(ctx.search);
+ if (search) {
+ doc.search = { ...search, at: search.at || now };
+ if (!doc.sessions.includes(search.session)) doc.sessions.push(search.session);
+ }
+ if (!doc.scope.source && ctx.scope) {
+ doc.scope = cleanScope({ ...ctx.scope, query: ctx.scope.query ?? search?.query });
+ }
+ if (dup) return { quote: dup, duplicate: true };
+ if (doc.quotes.length >= MAX_QUOTES) throw new CaseError(`a case holds up to ${MAX_QUOTES} quotes`, 409);
+ const section = typeof snap.section === "string" && doc.sections.some((s) => s.id === snap.section) ? snap.section : null;
+ const q = cleanQuote(
+ {
+ id: `q${++doc.counters.quote}`,
+ section,
+ text: snap.text.trim(),
+ cite,
+ claim: snap.claim ?? "",
+ note: snap.note ?? "",
+ speakerChecked: false,
+ pinnedAt: now,
+ query: snap.query ?? search?.query ?? doc.scope.query,
+ },
+ new Set(doc.sections.map((s) => s.id)),
+ );
+ const at = Number.isInteger(snap.at) && snap.at >= 0 && snap.at <= doc.quotes.length ? snap.at : doc.quotes.length;
+ doc.quotes.splice(at, 0, q);
+ return { quote: q, duplicate: false };
+}
+
+/** Record what a re-verify found, per quote (never the quote's own words). */
+export function recordVerify(doc, results) {
+ const byId = new Map(results.map((r) => [r.id, r]));
+ for (const q of doc.quotes) {
+ const r = byId.get(q.id);
+ if (r) q.verify = cleanVerify(r.verify);
+ }
+}
+
+/** A hand-off made from the case (an article's sweep, a video project). */
+export function recordHandoff(doc, h, now = new Date()) {
+ doc.handoffs.push({ to: h.to, href: h.href, at: now.toISOString(), ...(h.what ? { what: h.what } : {}) });
+}
diff --git a/umtool/lib/research/cases.test.mjs b/umtool/lib/research/cases.test.mjs
@@ -0,0 +1,133 @@
+// The research case store (cases.mjs): ids, the snapshot discipline, the
+// arrangement, and the lifecycle store's rules -- serialised, atomic, an
+// unreadable file never overwritten.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ CaseError,
+ addQuote,
+ arrangeCase,
+ caseFile,
+ createCase,
+ isCaseId,
+ listCases,
+ mutateCase,
+ patchQuote,
+ readCase,
+ removeQuote,
+ slugOf,
+} from "./cases.mjs";
+
+const root = () => mkdtemp(path.join(os.tmpdir(), "umtool-cases-"));
+const cite = (video, t, extra = {}) => ({ kind: "video", source: "local:/x", channel: "harbor-radio", video, t, end: t + 3.8, url: `https://a.example/?v=harbor-radio%2F${video}&t=${t}`, title: "Ep", ...extra });
+
+test("ids: a piece segment that is not reserved; a title's slug", () => {
+ assert.equal(isCaseId("employee-count"), true);
+ for (const bad of ["archive", "sessions", "census", "runs", "Bad", "-x", "", "a/b"]) assert.equal(isCaseId(bad), false, bad);
+ assert.equal(slugOf(" Employee count: “how many?” "), "employee-count-how-many");
+ assert.equal(slugOf("Café déjà vu"), "cafe-deja-vu");
+});
+
+test("create: from a query (the title), from a title; a taken slug gets -2; a named id must be free", async () => {
+ const r = await root();
+ const a = await createCase(r, { query: "how many employees", scope: { source: "remote:https://j.example", channels: ["x"], dateFrom: "2024-01-01", junk: 1 } });
+ assert.equal(a.id, "how-many-employees");
+ assert.equal(a.title, "how many employees");
+ assert.deepEqual(a.scope, { source: "remote:https://j.example", channels: ["x"], dateFrom: "2024-01-01", query: "how many employees" });
+ const b = await createCase(r, { title: "How many employees" });
+ assert.equal(b.id, "how-many-employees-2");
+ await assert.rejects(createCase(r, { title: "x", id: "how-many-employees" }), /already exists/);
+ await assert.rejects(createCase(r, { title: "x", id: "archive" }), /reserved/);
+ await assert.rejects(createCase(r, {}), /needs a title or a query/);
+ const c = await createCase(r, { title: "Archive" });
+ assert.equal(c.id, "archive-case", "a reserved slug is not a case id");
+ const list = await listCases(r);
+ assert.deepEqual(list.map((x) => x.id).sort(), ["archive-case", "how-many-employees", "how-many-employees-2"]);
+ assert.equal(list.find((x) => x.id === "how-many-employees").piece, "c:how-many-employees");
+});
+
+test("a pin is a snapshot; the same cite twice is one quote; a search's log becomes the case's", async () => {
+ const r = await root();
+ await createCase(r, { title: "Board" });
+ const search = { session: "FAKE-TEST-VALUE", query: "budget", total: 8, complete: true, notReached: [] };
+ const one = await mutateCase(r, "board", (d) => addQuote(d, { text: "the budget was never approved", cite: cite("v1", 600) }, { search, scope: { source: "local:/x", channels: ["harbor-radio"] } }));
+ assert.equal(one.result.duplicate, false);
+ assert.equal(one.result.quote.id, "q1");
+ assert.equal(one.case.search.session, search.session);
+ assert.deepEqual(one.case.sessions, [search.session]);
+ assert.deepEqual(one.case.scope, { source: "local:/x", channels: ["harbor-radio"], query: "budget" }, "the first pin's search scope becomes the case's");
+ const again = await mutateCase(r, "board", (d) => addQuote(d, { text: "other words", cite: cite("v1", 600.2) }));
+ assert.equal(again.result.duplicate, true);
+ assert.equal(again.case.quotes.length, 1);
+ assert.equal(again.case.quotes[0].text, "the budget was never approved", "a duplicate pin never rewrites the snapshot");
+ const alt = await mutateCase(r, "board", (d) => addQuote(d, { text: "on en", cite: cite("v1", 600, { trackId: "en" }) }));
+ assert.equal(alt.result.duplicate, false, "another track is another quote");
+ await assert.rejects(mutateCase(r, "board", (d) => addQuote(d, { text: "", cite: cite("v2", 1) })), /has words/);
+});
+
+test("arrange: sections as a whole list, every quote in order; a removed section's quotes go to Unsorted", async () => {
+ const r = await root();
+ await createCase(r, { title: "Board" });
+ for (const t of [1, 2, 3]) await mutateCase(r, "board", (d) => addQuote(d, { text: `line ${t}`, cite: cite(`v${t}`, t) }));
+ const s = await mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ title: "First" }, { title: "Second" }] }));
+ assert.deepEqual(s.case.sections, [{ id: "s1", title: "First" }, { id: "s2", title: "Second" }]);
+ const o = await mutateCase(r, "board", (d) =>
+ arrangeCase(d, { order: [{ id: "q3", section: "s1" }, { id: "q1", section: "s2" }, { id: "q2", section: null }] }),
+ );
+ assert.deepEqual(o.case.quotes.map((q) => [q.id, q.section]), [["q3", "s1"], ["q1", "s2"], ["q2", null]]);
+ await assert.rejects(mutateCase(r, "board", (d) => arrangeCase(d, { order: ["q1", "q2"] })), /every quote/);
+ await assert.rejects(mutateCase(r, "board", (d) => arrangeCase(d, { order: [{ id: "q1", section: "s9" }, { id: "q2", section: null }, { id: "q3", section: null }] })), /no section/);
+ await assert.rejects(mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ id: "s9", title: "x" }] })), /no section/);
+ const gone = await mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ id: "s2", title: "Second, renamed" }] }));
+ assert.deepEqual(gone.case.sections, [{ id: "s2", title: "Second, renamed" }]);
+ assert.equal(gone.case.quotes.find((q) => q.id === "q3").section, null);
+ const added = await mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ id: "s2", title: "Second" }, { title: "Third" }] }));
+ assert.equal(added.case.sections[1].id, "s3", "a new section never reuses a removed one's id");
+});
+
+test("a quote's claim, note, speaker check; the current words only on the operator's word, the old kept", async () => {
+ const r = await root();
+ await createCase(r, { title: "Board" });
+ await mutateCase(r, "board", (d) => addQuote(d, { text: "nine to one", cite: cite("v1", 10) }));
+ const p = await mutateCase(r, "board", (d) => patchQuote(d, "q1", { claim: " The vote ", note: "panel", speakerChecked: true }));
+ assert.deepEqual([p.result.claim, p.result.note, p.result.speakerChecked], ["The vote", "panel", true]);
+ await assert.rejects(mutateCase(r, "board", (d) => patchQuote(d, "q1", { useCurrentWords: true })), /only a quote re-verify found drifted/);
+ await mutateCase(r, "board", (d) => {
+ d.quotes[0].verify = { status: "drifted", at: "2026-10-14T00:00:00.000Z", now: "eight to one", nowAt: 11 };
+ });
+ const took = await mutateCase(r, "board", (d) => patchQuote(d, "q1", { useCurrentWords: true }));
+ assert.equal(took.result.text, "eight to one");
+ assert.equal(took.result.cite.t, 11);
+ assert.equal(took.result.history[0].text, "nine to one");
+ assert.equal(took.result.verify.status, "ok");
+ const rm = await mutateCase(r, "board", (d) => removeQuote(d, "q1"));
+ assert.equal(rm.case.quotes.length, 0);
+ await assert.rejects(mutateCase(r, "board", (d) => patchQuote(d, "q1", { claim: "x" })), /no quote/);
+});
+
+test("a case.json that does not parse is never overwritten; a missing case is a 404", async () => {
+ const r = await root();
+ await assert.rejects(readCase(r, "nope"), (e) => e instanceof CaseError && e.status === 404);
+ await mkdir(path.dirname(caseFile(r, "broken")), { recursive: true });
+ await writeFile(caseFile(r, "broken"), "{ not json");
+ await assert.rejects(mutateCase(r, "broken", () => {}), (e) => e.status === 409);
+ assert.equal(await readFile(caseFile(r, "broken"), "utf8"), "{ not json");
+ const list = await listCases(r);
+ assert.equal(list.length, 1);
+ assert.match(list[0].error, /not JSON/);
+ // A directory with no case.json is not a case (a half-made one).
+ await mkdir(path.join(r, ".umtool", "research", "half"), { recursive: true });
+ assert.equal((await listCases(r)).length, 1);
+});
+
+test("writes are serialised: concurrent pins all land", async () => {
+ const r = await root();
+ await createCase(r, { title: "Board" });
+ await Promise.all(Array.from({ length: 12 }, (_, i) => mutateCase(r, "board", (d) => addQuote(d, { text: `w${i}`, cite: cite(`v${i}`, i) }))));
+ const d = await readCase(r, "board");
+ assert.equal(d.quotes.length, 12);
+ assert.equal(new Set(d.quotes.map((q) => q.id)).size, 12);
+});
diff --git a/umtool/lib/research/handoff.ts b/umtool/lib/research/handoff.ts
@@ -0,0 +1,237 @@
+import { stat } from "node:fs/promises";
+import path from "node:path";
+import { articleDir } from "yt-dlp-transcript-common/lib/report/registry";
+import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
+import { articleHref, ARTICLES_KEY } from "@/lib/articles/href";
+import { projectHref } from "@/lib/hrefs";
+import { enqueueDraft, readPolicy } from "@/lib/articles/generation";
+import { sitesPaths } from "@/lib/articles/sites";
+import { REPORTS_ROOT } from "../paths.mjs";
+import { invalidateProjects } from "../projects";
+import { scaffoldReportVideo, SLUG_RE } from "../projects/scaffold.mjs";
+import { exportMarkdown, localOnlyQuotes } from "./board.mjs";
+import { CaseError, recordHandoff } from "./cases.mjs";
+import { boardGroups, caseView, mutateBoard } from "./boards";
+import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types";
+
+// ---------------------------------------------------------------------------
+// HAND-OFFS from a board (plans/umtool-redesign.md, R2), both PLAN THEN
+// CONFIRM: POST without `confirm` answers the plan and writes nothing; POST
+// with `confirm: true` (and anything the plan let the operator change) does it
+// and answers `{ href }`.
+//
+// "Draft an article from this board" is a `report-draft` SWEEP (the editor's
+// job, POST /api/ops/report-draft -- umtool writes nothing of the article
+// store) over the board's question and channels, SEEDED with the board as
+// cited markdown (through enqueueDraft, the one door): the editor keeps it as the iteration's seed.md and the
+// sweep's report starts from it (common/controller/reportDraft.ts `seed`,
+// added for this hand-off -- the editor had no way to take a board's cites).
+// A seeded sweep runs the API agent (the local pipeline writes its report from
+// scratch), so the model is the policy's API model, whatever the sweep route.
+// It spends money: the plan says on what, and under which cap.
+//
+// "Start a video from this board" scaffolds a report-video project under
+// REPORTS_ROOT (lib/projects/scaffold.mjs, its `timeline`): one clip per
+// pinned quote, in board order, its window the quote's cue span. It spends
+// nothing; it writes a project.
+//
+// RESEARCH RULES: a board holding a local-only quote (Candace's channels,
+// rules.mjs) never hands off to an article -- the article store publishes.
+// Its video project is local, and the plan says it must stay so.
+// ---------------------------------------------------------------------------
+
+const exists = (p: string) => stat(p).then(() => true, () => false);
+
+/** The board's channels (slugs): the scope's, else every quoted one. */
+function channelsOf(doc: CaseDoc): string[] {
+ const fromScope = (doc.scope.channels ?? []).map((k) => k.split(":").pop()!).filter(Boolean);
+ const quoted = [...new Set(doc.quotes.map((q) => q.cite.channel))];
+ return fromScope.length ? [...new Set(fromScope)] : quoted;
+}
+
+// ── the article ──
+
+export async function planArticle(id: string, over: { article?: string; model?: string; question?: string } = {}): Promise<{ plan: ArticlePlan; seed: string }> {
+ const view = await caseView(id);
+ const doc = view.case;
+ const refusals: string[] = [];
+ const warnings: string[] = [];
+ const article = (over.article ?? doc.id).trim();
+ if (!isReportId(article)) refusals.push(`"${article}" is not an article id (lowercase letters, digits and dashes)`);
+ if (!doc.quotes.length) refusals.push("the board has no quotes: pin some first");
+ const local = localOnlyQuotes(doc).length;
+ if (local) refusals.push(`${local} ${local === 1 ? "quote is" : "quotes are"} from a local-only channel: an article can be published, so this board never becomes one (export the markdown instead)`);
+ const channels = channelsOf(doc);
+ if (!channels.length) refusals.push("the board names no channel to sweep");
+ const question = (over.question ?? doc.scope.query ?? doc.title).trim();
+ const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
+ if (drifted) warnings.push(`${drifted} ${drifted === 1 ? "quote" : "quotes"} drifted or missing at the last re-verify: the sweep checks every quote again`);
+ const unverified = doc.quotes.filter((q) => !q.verify).length;
+ if (unverified) warnings.push(`${unverified} ${unverified === 1 ? "quote was" : "quotes were"} never re-verified`);
+ const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length;
+ if (unchecked) warnings.push(`${unchecked} with the speaker not checked: the seed says so on each`);
+ const articleExists = isReportId(article) ? await exists(articleDir(sitesPaths(), article)) : false;
+ if (articleExists) warnings.push(`the article "${article}" exists: the sweep adds an iteration to it`);
+
+ let model: string | null = null;
+ let route: string | null = null;
+ let capUsd: number | null = null;
+ let policyError: string | undefined;
+ try {
+ const p = await readPolicy();
+ route = p.generation.routes.sweep;
+ model = over.model?.trim() || p.generation.models.api;
+ capUsd = Math.min(p.generation.caps.sweep, p.generation.caps.max);
+ if (route !== "api") warnings.push(`the policy routes sweeps to ${route === "code" ? "Claude Code" : "the local model"}; a seeded sweep runs the API agent on ${model}`);
+ } catch (e) {
+ policyError = (e as Error).message;
+ model = over.model?.trim() || null;
+ }
+ if (model && !model.startsWith("claude-")) refusals.push(`a seeded sweep runs on a Claude model, not ${model}: the local pipeline writes its report from scratch`);
+
+ const seed = exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) });
+ return {
+ plan: {
+ to: "article",
+ article,
+ articleExists,
+ question,
+ channels,
+ ...(doc.scope.dateFrom ? { dateFrom: doc.scope.dateFrom } : {}),
+ ...(doc.scope.dateTo ? { dateTo: doc.scope.dateTo } : {}),
+ source: doc.scope.source,
+ model,
+ route,
+ capUsd,
+ seed: { chars: seed.length, quotes: doc.quotes.length },
+ spends: true,
+ refusals,
+ warnings,
+ ...(policyError ? { policyError } : {}),
+ },
+ seed,
+ };
+}
+
+export async function confirmArticle(id: string, over: { article?: string; model?: string; question?: string }): Promise<{ href: string; jobId: string; iteration: number }> {
+ const { plan, seed } = await planArticle(id, over);
+ if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409);
+ if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502);
+ // The one way umtool asks the editor for a draft (lib/articles/generation.ts).
+ const answer = await enqueueDraft({
+ task: "sweep",
+ article: plan.article,
+ question: plan.question,
+ channels: plan.channels,
+ from: plan.dateFrom,
+ to: plan.dateTo,
+ source: plan.source,
+ model: plan.model,
+ seed,
+ });
+ const href = articleHref({ site: ARTICLES_KEY, id: plan.article });
+ await mutateBoard(id, (doc) =>
+ recordHandoff(doc, { to: "article", href, what: `${plan.article} i${answer.iteration}, job ${answer.jobId}` }),
+ );
+ return { href, jobId: answer.jobId, iteration: answer.iteration };
+}
+
+// ── the video ──
+
+/** The viewer origin every quote's link shares, else "" (the project's `check` asks for it). */
+function originOf(doc: CaseDoc): string {
+ const origins = new Set<string>();
+ for (const q of doc.quotes) {
+ if (q.cite.kind !== "video" || !q.cite.url) continue;
+ try {
+ const u = new URL(q.cite.url);
+ if (!u.searchParams.has("v")) return "";
+ origins.add(u.origin);
+ } catch {
+ return "";
+ }
+ }
+ return origins.size === 1 ? [...origins][0] : "";
+}
+
+const r2 = (n: number) => Math.round(n * 100) / 100;
+
+export function clipsOf(doc: CaseDoc): { clips: Record<string, unknown>[]; skipped: number } {
+ const clips: Record<string, unknown>[] = [];
+ let skipped = 0;
+ let n = 0;
+ for (const g of boardGroups(doc)) {
+ for (const q of g.quotes) {
+ if (q.cite.kind !== "video" || !(q.cite.end > q.cite.t)) {
+ skipped++;
+ continue;
+ }
+ const c = q.cite;
+ const date = /^\d{8}$/.test(c.date ?? "") ? `${c.date!.slice(0, 4)}-${c.date!.slice(4, 6)}-${c.date!.slice(6, 8)}` : undefined;
+ clips.push({
+ type: "clip",
+ id: `c${String(n++).padStart(2, "0")}`,
+ // The editor's directory (a Rumble clip's URL slug); the archive's ids
+ // beside it when they differ, so its cues resolve (report-to-video/cues.mjs).
+ channel: c.channel,
+ video: c.dirVideo ?? c.video,
+ ...(c.dirVideo ? { siteVideo: c.video, siteChannel: c.channel } : {}),
+ start: r2(c.t),
+ end: r2(c.end),
+ cite: Math.floor(c.t),
+ quote: q.text,
+ ...(date ? { date } : {}),
+ ...(q.claim ? { note: q.claim } : {}),
+ ...(c.trackId ? { track: c.trackId } : {}),
+ });
+ }
+ }
+ return { clips, skipped };
+}
+
+export async function planVideo(id: string, over: { slug?: string; title?: string } = {}): Promise<VideoPlan> {
+ const view = await caseView(id);
+ const doc = view.case;
+ const refusals: string[] = [];
+ const warnings: string[] = [];
+ const slug = (over.slug ?? doc.id).trim();
+ if (!SLUG_RE.test(slug)) refusals.push(`"${slug}" will not route: lowercase letters, digits and dashes`);
+ else if (await exists(path.join(REPORTS_ROOT, slug))) refusals.push(`a project folder "${slug}" already exists under the reports root: name another`);
+ const { clips, skipped } = clipsOf(doc);
+ if (!clips.length) refusals.push("the board has no video quotes to clip");
+ if (skipped) warnings.push(`${skipped} ${skipped === 1 ? "quote has" : "quotes have"} no window (a post, or no cue span) and ${skipped === 1 ? "is" : "are"} left out`);
+ const local = localOnlyQuotes(doc).length;
+ if (local) warnings.push(`${local} local-only ${local === 1 ? "quote" : "quotes"}: this project must never be published`);
+ const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
+ if (drifted) warnings.push(`${drifted} drifted or missing at the last re-verify: their windows are the pinned seconds`);
+ const siteOrigin = originOf(doc);
+ if (!siteOrigin) warnings.push("no one viewer origin in the quotes' links: set provenance.siteOrigin before the build");
+ return {
+ to: "video",
+ slug,
+ title: (over.title ?? doc.title).trim() || doc.title,
+ siteOrigin,
+ clips: clips.map((c) => ({ id: String(c.id), channel: String(c.channel), video: String(c.video), start: Number(c.start), end: Number(c.end), quote: String(c.quote) })),
+ writes: `${slug}/ (video.manifest.json, README.md) under the reports root`,
+ spends: false,
+ refusals,
+ warnings,
+ };
+}
+
+export async function confirmVideo(id: string, over: { slug?: string; title?: string }): Promise<{ href: string }> {
+ const plan = await planVideo(id, over);
+ if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409);
+ const doc = (await caseView(id)).case;
+ const { clips } = clipsOf(doc);
+ try {
+ await scaffoldReportVideo({ root: REPORTS_ROOT, slug: plan.slug, title: plan.title, siteOrigin: plan.siteOrigin || null, timeline: clips, timelineFrom: `“${doc.title}” (c:${doc.id})` });
+ } catch (e) {
+ const msg = (e as Error).message;
+ throw new CaseError(msg, /already exists/.test(msg) ? 409 : 400);
+ }
+ invalidateProjects();
+ const href = projectHref(plan.slug);
+ await mutateBoard(id, (d) => recordHandoff(d, { to: "video", href, what: `${clips.length} clips` }));
+ return { href };
+}
diff --git a/umtool/lib/research/hrefs.ts b/umtool/lib/research/hrefs.ts
@@ -7,7 +7,7 @@
import { withQuery } from "../hrefs";
import type { Scope } from "./types";
-export type ResearchQuery = Partial<Scope> & { q?: string };
+export type ResearchQuery = Partial<Scope> & { q?: string; /** The case a pin goes to (R2). */ case?: string };
function scopeQuery(s: Partial<Scope>) {
return {
@@ -23,7 +23,33 @@ function scopeQuery(s: Partial<Scope>) {
/** The Research page, with a query and a scope when given. */
export function researchHref(q: ResearchQuery = {}): string {
- return withQuery("/research", { q: q.q, ...scopeQuery(q) });
+ return withQuery("/research", { q: q.q, ...scopeQuery(q), case: q.case });
+}
+
+// ── R2: the boards (cases) ──
+
+const enc = encodeURIComponent;
+
+/** A case's board. */
+export function researchCaseHref(id: string): string {
+ return `/research/${enc(id)}`;
+}
+
+/** Research with a case's scope and query, pins going to the case. */
+export function researchFromCaseHref(c: { id: string; scope: Partial<Scope> & { query?: string } }): string {
+ const { query, ...scope } = c.scope;
+ return researchHref({ ...scope, q: query, case: c.id });
+}
+
+/** The case API (app/api/research/cases/route.ts documents it). */
+export const researchCasesApi = () => "/api/research/cases";
+export const researchCaseApi = (id: string) => `/api/research/cases/${enc(id)}`;
+export const researchCaseQuotesApi = (id: string) => `/api/research/cases/${enc(id)}/quotes`;
+export const researchCaseQuoteApi = (id: string, qid: string) => `/api/research/cases/${enc(id)}/quotes/${enc(qid)}`;
+export const researchCaseVerifyApi = (id: string) => `/api/research/cases/${enc(id)}/verify`;
+export const researchCaseHandoffApi = (id: string) => `/api/research/cases/${enc(id)}/handoff`;
+export function researchCaseExportApi(id: string, opts: { download?: boolean } = {}): string {
+ return withQuery(`/api/research/cases/${enc(id)}/export.md`, { download: opts.download === true });
}
/** The archive inventory (channels × years). */