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 { checkWordsInWindow, enOrigDifference } from "yt-dlp-transcript-common/lib/report/quoteWords"; import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes } 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 { boardGate } from "./case-private"; 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 => listAt(REPORTS_ROOT) as Promise; export const readCase = (id: string): Promise => readAt(REPORTS_ROOT, id) as Promise; export type CreateCaseInput = { title?: string; id?: string; scope?: Partial; query?: string; notes?: string }; export const createCase = (input: CreateCaseInput): Promise => createAt(REPORTS_ROOT, input) as unknown as Promise; /** One change to a case, read and written inside the store's lock (cases.mjs mutateCase). */ export async function mutateBoard(id: string, fn: (doc: CaseDoc) => T | Promise): 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): Promise { 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): 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 `:`), 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; /** 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 }; /** * 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 { 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; } // The words, against the window: common's check (lib/report/quoteWords.ts), // shared with a refresh's re-verify (R4). const v = checkWordsInWindow(q.text, { t: c.t, end: c.end }, win); let status: QuoteVerify; if (v.status === "ok") { status = v.nowAt !== undefined ? { status: "ok", at, nowAt: v.nowAt, message: `the words now start at ${clock(v.nowAt)} (pinned at ${clock(c.t)})` } : { status: "ok", at }; } else if (v.empty) { status = { status: "drifted", at, now: "", message: `no cues within 30 s of ${clock(c.t)}${c.trackId ? ` on the ${c.trackId} track` : ""} now` }; } else { status = { status: "drifted", at, now: v.now, ...(v.nowAt !== undefined ? { nowAt: v.nowAt } : {}) }; } 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>["source"], q: Quote): Promise { 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 cuesOn = (track: string) => (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[]; const diff = enOrigDifference(cuesOn(enId), cuesOn(origId), { t: c.t, end: c.end }); if (!diff) return undefined; const orig = diff.orig; const en = diff.en; 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 { if (!handle) return null; const sources = await listSources().catch(() => []); return sources.find((s) => s.handle === handle)?.label ?? null; } async function readingOf(doc: CaseDoc): Promise { 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 { 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); // The case pipeline's privacy gate (lib/research/case-private.ts): a 409 naming quote ids, never the name. const blocked = await boardGate(view.case, "this export"); if (blocked) throw blocked; return { doc: view.case, markdown: exportMarkdown(view.case, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }), }; }