Cotton code
506 lines · 27.3 KB · TypeScriptRaw
/** * COTTON FETCH IN THE OBJECT (owner, 5 Nov 2026: a link becomes an owned * file in the tool that plays it, fetched by the Mac). The table is the * personal kit's `fetch` (crates/cotton-core/kits/personal/tables/fetch.json), * shown by the Downloads tool; anyone holding the owner's word can push a row * into it (the phone's Plus, the share sheet, create_record over Cotton MCP) * and the Mac (`pnpm fetch:run`) does the fetching. * These are the queue's acts and its read: * * - `fetch_add { source, wants?, title? }`: the phone's door, a row from a *   link; a page card's Fetch sends the page's own title, which the row *   wears until the Mac's. *   Every created fetch row, by this act or a plain create, is completed by *   `withFetchDefaults`: the link checked, its kind (`source_kind`), what it *   wants (video for a page, files for a torrent or a file), the moment it was *   added and a title until the Mac knows a better one. * - `GET /v1/fetch/pending`: the queued rows, oldest first: the Mac's poll. * - The Mac's: `fetch_claim { id, machine }` (queued → fetching, refused when *   the row is not queued), `fetch_progress { id, … }` (refused once the row *   is cancelled: that is how the Mac learns to stop), `fetch_landed { id, *   landed }` (→ done, each record linked) and `fetch_failed { id, error }` *   (→ failed, the fetcher's reason in one sentence). * - The owner's: `fetch_cancel { fetch }`, `fetch_retry { fetch }` and *   `fetch_again { fetch }` (owner, 18 Nov 2026: a download *   that landed before films kept their originals is fetched once more, so its *   films come back keeping them). A second fetch is marked by `again_on`; one *   that fails or is cancelled leaves the row done, its landed records still *   linked, `again_outcome` saying how it went and `again_error` why. */import type { Engine, Outcome } from "./engine.ts";import { refuse, text } from "./http.ts";import type { Data } from "./mcp/context.ts";import type { Cond, Store, StoredRow } from "./store.ts";import { isSealedRow } from "./seal.ts";export const FETCH = "fetch";export type FetchState = "queued" | "fetching" | "landing" | "done" | "failed" | "cancelled";export type SourceKind = "torrent" | "page" | "file";const KINDS: readonly SourceKind[] = ["torrent", "page", "file"];export type Wants = "video" | "audio" | "files";const WANTS: readonly Wants[] = ["video", "audio", "files"];/** The states a row is still on its way in: the Mac may be working on it. */export const ACTIVE: readonly FetchState[] = ["queued", "fetching", "landing"];export const FETCH_FILE = "fetch_file";/** The tables a fetched file lands in, each by its fetch_file kind (the link column naming it). */export const LANDS: Record<string, string> = {  film: "film",  film_episode: "episode",  book: "book",  photo: "photo",  document: "document",};/** A file's own extensions, as a link's path ends: what makes a link a plain file rather than a page. */const FILE_EXTENSIONS = new Set([  "mp4", "mkv", "mov", "m4v", "webm", "avi",  "mp3", "m4a", "flac", "ogg", "opus", "wav", "aac",  "epub", "pdf",  "jpg", "jpeg", "png", "heic", "webp", "gif",  "zip", "iso", "srt", "txt", "7z", "rar", "tar", "gz", "dmg",]);/** The longest error a row keeps: one sentence, never a stack. */export const ERROR_MAX = 300;const textOf = (v: unknown): string => (typeof v === "string" ? v.trim() : "");const blank = (v: unknown): boolean => v === undefined || v === null || (typeof v === "string" && v.trim() === "");/** A link the Mac can fetch: a magnet, or an http(s) address. */export function checkSource(value: unknown): string {  const source = textOf(value);  if (!source) refuse(400, "bad_source", "a download needs its link: a magnet, a .torrent, a file's link or a page");  if (/^magnet:\?/i.test(source)) {    if (!/[?&]xt=urn:bt[im]h:/i.test(source)) refuse(400, "bad_source", "this magnet names no torrent (it has no xt=urn:btih)");    return source;  }  let url: URL;  try {    url = new URL(source);  } catch {    refuse(400, "bad_source", "a download's link is a magnet or an http(s) address");  }  if (url.protocol !== "http:" && url.protocol !== "https:") refuse(400, "bad_source", "a download's link is a magnet or an http(s) address");  return source;}/** What a link is, by its spelling alone: a magnet or a .torrent is a torrent, a path ending in a file's extension a file, anything else a page. The Mac may know better once it asks. */export function sourceKindOf(source: string): SourceKind {  if (/^magnet:/i.test(source)) return "torrent";  let path = "";  try {    path = new URL(source).pathname.toLowerCase();  } catch {    return "page";  }  if (path.endsWith(".torrent")) return "torrent";  const ext = /\.([a-z0-9]+)$/.exec(path)?.[1];  return ext && FILE_EXTENSIONS.has(ext) ? "file" : "page";}/** What a link wants unless the owner said: a page's video, a torrent's or a file's files. */export const wantsOf = (kind: SourceKind): Wants => (kind === "page" ? "video" : "files");/** A title until the Mac knows the real one: a magnet's display name, else the file's name, else the host and path. */export function provisionalTitle(source: string): string {  if (/^magnet:/i.test(source)) {    const dn = /[?&]dn=([^&]+)/i.exec(source)?.[1];    if (dn) {      try {        return decodeURIComponent(dn.replace(/\+/g, " ")).trim() || "A torrent";      } catch {        return dn;      }    }    return "A torrent";  }  try {    const url = new URL(source);    const last = url.pathname.split("/").filter(Boolean).pop();    if (last && /\.[a-z0-9]+$/i.test(last)) return decodeURIComponent(last);    return `${url.host}${url.pathname === "/" ? "" : url.pathname}`.slice(0, 120);  } catch {    return source.slice(0, 120);  }}/** * A fetch row as it is created, completed: the link checked and trimmed, its * kind, what it wants (a choice the owner may give; else by its kind), queued, * when it was added, and a title until the Mac's. */export function withFetchDefaults(data: Data, now: string): Data {  // A row a device sealed carries its link inside the seal (e2e rulings R1): the device says its kind, and nothing here reads the link.  if (isSealedRow(data)) {    const kind = data.source_kind as SourceKind;    if (!KINDS.includes(kind)) refuse(400, "bad_args", "a sealed download says its kind (source_kind) beside its seal");    const wants = blank(data.wants) ? wantsOf(kind) : data.wants;    if (!WANTS.includes(wants as Wants)) refuse(400, "bad_wants", "a download wants video, audio or files");    return { ...data, wants, source_kind: kind, state: "queued", added_on: blank(data.added_on) ? now : data.added_on };  }  const source = checkSource(data.source);  const kind = sourceKindOf(source);  const wants = blank(data.wants) ? wantsOf(kind) : data.wants;  if (!WANTS.includes(wants as Wants)) refuse(400, "bad_wants", "a download wants video, audio or files");  return {    ...data,    source,    wants,    source_kind: kind,    state: "queued",    added_on: blank(data.added_on) ? now : data.added_on,    title: blank(data.title) ? provisionalTitle(source) : data.title,  };}function live(store: Store, id: unknown, said = "id"): StoredRow {  if (typeof id !== "string" || !id.trim()) refuse(400, "bad_args", `name the download: its ${said}`);  const row = store.get(FETCH, id.trim());  if (!row || row.deleted) refuse(404, "no_such_download", `no download with id ${id}`);  return row;}const stateOf = (row: StoredRow): FetchState => (textOf(row.data.state) || "queued") as FetchState;/** How a second fetch went: landed, failed or cancelled; empty while it runs. */export type AgainOutcome = "landed" | "failed" | "cancelled";/** A row on its second fetch, still running: asked again (`again_on`) and no outcome yet. */export const fetchingAgain = (row: StoredRow): boolean => !blank(row.data.again_on) && blank(row.data.again_outcome);/** A second fetch stopped (failed or cancelled): the row is done again, and the Mac holding it stops. */const againStopped = (row: StoredRow): boolean => stateOf(row) === "done" && !blank(row.data.again_on) && (row.data.again_outcome === "failed" || row.data.again_outcome === "cancelled");/** * A second fetch that did not land: the row is done again (what it landed before stays linked), the run's * figures cleared, how it went in `again_outcome` and one sentence of why in `again_error` (never `error`: * a good download does not look broken). */function backToDone(engine: Engine, row: StoredRow, outcome: AgainOutcome, why: string, now: string, version: number, out: Outcome): void {  engine.update(row, { state: "done", again_outcome: outcome, again_error: why, error: null, progress: 100, bytes: null, of_bytes: null, speed_bps: null, eta_seconds: null, finished_on: now, ...NO_STAGE }, version, out);}// ── the owner's ──────────────────────────────────────────────────────────/** `fetch_add { source, wants?, title? }`: a queued row from a link, titled by the card it came from when it says one. */export function fetchAdd(engine: Engine, args: Record<string, unknown>, version: number, outcome: Outcome): { fetch: string } {  const data: Data = { source: args.source };  if (args.wants !== undefined) data.wants = args.wants;  if (!blank(args.title)) data.title = textOf(args.title).slice(0, 300);  const row = engine.create(FETCH, data, version, outcome);  outcome.made = row;  return { fetch: row.id };}/** `fetch_cancel { fetch }`: a row still on its way in stops; the Mac kills its job when it next speaks of it. */export function fetchCancel(engine: Engine, args: Record<string, unknown>, now: string, version: number, outcome: Outcome): { fetch: string; state: FetchState } {  const row = live(engine.store, args.fetch, "id (fetch)");  if (!ACTIVE.includes(stateOf(row))) refuse(409, "not_active", `this download is ${stateOf(row)}: only one still on its way in can be cancelled`);  // A second fetch cancelled leaves the download as it was: done, what it landed still linked.  if (fetchingAgain(row)) {    backToDone(engine, row, "cancelled", "Cancelled by the owner before it landed.", now, version, outcome);    return { fetch: row.id, state: "done" };  }  engine.update(row, { state: "cancelled", finished_on: now, speed_bps: null, eta_seconds: null }, version, outcome);  return { fetch: row.id, state: "cancelled" };}/** `fetch_retry { fetch }`: a failed or cancelled row is queued again, its last try forgotten. */export function fetchRetry(engine: Engine, args: Record<string, unknown>, version: number, outcome: Outcome): { fetch: string; state: FetchState } {  const row = live(engine.store, args.fetch, "id (fetch)");  const state = stateOf(row);  if (state !== "failed" && state !== "cancelled") refuse(409, "not_stopped", `this download is ${state}: only a failed or cancelled one is tried again`);  engine.update(row, { state: "queued", error: null, progress: null, bytes: null, of_bytes: null, speed_bps: null, eta_seconds: null, machine: null, started_on: null, finished_on: null, ...NO_STAGE }, version, outcome);  return { fetch: row.id, state: "queued" };}/** * `fetch_again { fetch }`: a done row is queued once more, its sealed link untouched (nothing here reads it), * its last run's figures cleared and `again_on` stamped: a second fetch, whose landing gives the films it * landed their originals (the Mac's fetch run). Refused, in words, for a row that is not done. */export function fetchAgain(engine: Engine, args: Record<string, unknown>, now: string, version: number, outcome: Outcome): { fetch: string; state: FetchState } {  const row = live(engine.store, args.fetch, "id (fetch)");  const state = stateOf(row);  if (state !== "done") refuse(409, "not_done", `this download is ${state}: only a done one is fetched again (a failed or cancelled one is tried again)`);  engine.update(row, { state: "queued", again_on: now, again_outcome: null, again_error: null, error: null, progress: null, bytes: null, of_bytes: null, speed_bps: null, eta_seconds: null, machine: null, started_on: null, finished_on: null, ...NO_STAGE }, version, outcome);  return { fetch: row.id, state: "queued" };}// ── the Mac's ────────────────────────────────────────────────────────────export interface PendingFetch {  id: string;  source: string;  wants: Wants;  source_kind: SourceKind;  title: string;  /** A second fetch (fetch_again): what the download landed before, by record, its fetch_file row named; never a name. */  again?: { before: { file: string; table: string; id: string }[] };}/** The records a download landed (its live fetch_file rows), by table and id: the clear columns alone. */export function landedBefore(store: Store, fetch: string): { file: string; table: string; id: string }[] {  const out: { file: string; table: string; id: string }[] = [];  for (const f of store.scan(FETCH_FILE, [{ sql: `json_extract(data, '$."fetch"') = ?`, args: [fetch] }])) {    if (f.deleted) continue;    const kind = textOf(f.data.kind);    const table = Object.keys(LANDS).find((t) => LANDS[t] === kind);    const id = kind ? textOf(f.data[kind]) : "";    if (table && id) out.push({ file: f.id, table, id });  }  return out.sort((a, b) => a.file.localeCompare(b.file));}/** * `GET /v1/fetch/pending[?machine=<name>]`: every queued row, oldest first; * with a machine, also the rows it holds still fetching or landing (`held`), * which a Mac restarted mid-fetch takes up again. */export function pending(store: Store, machine: string | null): { rows: PendingFetch[]; held?: PendingFetch[] } {  const rows = pendingIn(store, [{ sql: `json_extract(data, '$."state"') = 'queued'`, args: [] }]);  if (!machine) return { rows };  const held = pendingIn(store, [{ sql: `json_extract(data, '$."state"') IN ('fetching', 'landing') AND json_extract(data, '$."machine"') = ?`, args: [machine] }]);  return { rows, held };}function pendingIn(store: Store, where: Cond[]): PendingFetch[] {  return [...store.scan(FETCH, where)]    .sort((a, b) => (textOf(a.data.added_on) || a.created_at).localeCompare(textOf(b.data.added_on) || b.created_at) || a.id.localeCompare(b.id))    .map((row) => {      const source = textOf(row.data.source);      const kind = (textOf(row.data.source_kind) || sourceKindOf(source)) as SourceKind;      const pending: PendingFetch = { id: row.id, source, wants: (textOf(row.data.wants) || wantsOf(kind)) as Wants, source_kind: kind, title: textOf(row.data.title) };      if (fetchingAgain(row)) pending.again = { before: landedBefore(store, row.id) };      return pending;    });}/** `fetch_claim { id, machine }`: a queued row is this Mac's. */export function fetchClaim(engine: Engine, args: Record<string, unknown>, now: string, version: number, outcome: Outcome): { fetch: string; state: FetchState } {  const row = live(engine.store, args.id);  const machine = text(args.machine, "machine");  if (stateOf(row) !== "queued") refuse(409, "not_queued", `this download is ${stateOf(row)}, not queued: another Mac may hold it`);  engine.update(row, { state: "fetching", machine, started_on: now, error: null }, version, outcome);  return { fetch: row.id, state: "fetching" };}/** A Mac's word on a row it holds: refused once the row is no longer fetching or landing (cancelled: the Mac stops). */function held(engine: Engine, id: unknown): StoredRow {  const row = live(engine.store, id);  const state = stateOf(row);  if (state === "cancelled") refuse(409, "fetch_cancelled", "this download was cancelled: stop fetching it");  if (againStopped(row)) refuse(409, "fetch_cancelled", "this second fetch was stopped and the download is done as it was: stop fetching it");  if (state !== "fetching" && state !== "landing") refuse(409, "not_fetching", `this download is ${state}: claim it first`);  return row;}const count = (v: unknown, what: string): number | null => {  if (v === undefined || v === null) return null;  if (typeof v !== "number" || !Number.isFinite(v) || v < 0) refuse(400, "bad_args", `${what} is a number, zero or more`);  return v;};/** * `fetch_progress { id, progress?, bytes?, of_bytes?, speed_bps?, eta_seconds?, * files?, title?, picture?, source_kind?, landing? }`: how far the Mac is. * progress is a share, 0 to 1 (kept as a percent, as the book's is); * picture is a photo the Mac sent first (`<database>/photos/…`); landing * says the fetching is over and the files are going in. */export function fetchProgress(engine: Engine, args: Record<string, unknown>, databaseId: string, version: number, outcome: Outcome): { fetch: string; state: FetchState } {  const row = held(engine, args.id);  const patch: Data = {};  const share = count(args.progress, "progress");  if (share !== null) {    if (share > 1) refuse(400, "bad_args", "progress is a share, 0 to 1");    patch.progress = Math.floor(share * 100);  }  for (const key of ["bytes", "of_bytes", "speed_bps", "eta_seconds", "files"] as const) {    const n = count(args[key], key);    if (n !== null) patch[key] = Math.round(n);  }  if (!blank(args.title)) patch.title = textOf(args.title).slice(0, 300);  if (!blank(args.picture)) {    const picture = textOf(args.picture);    if (!picture.startsWith(`${databaseId}/photos/`) || picture.slice(databaseId.length + 8).includes("/")) refuse(400, "bad_picture", `a download's picture is a photo sent first, ${databaseId}/photos/<sha256>.<ext>`);    patch.picture = picture;  }  if (!blank(args.source_kind)) {    const kind = textOf(args.source_kind);    if (kind !== "torrent" && kind !== "page" && kind !== "file") refuse(400, "bad_args", "source_kind is torrent, page or file");    patch.source_kind = kind;  }  if (args.landing === true) {    patch.state = "landing";    patch.speed_bps = null;    patch.eta_seconds = null;  }  engine.update(row, patch, version, outcome);  return { fetch: row.id, state: (patch.state as FetchState | undefined) ?? stateOf(row) };}const STAGES = ["converting", "sending", "sending_original", "smaller_copies", "waiting"];/** A row that says nothing of a stage. */const NO_STAGE: Data = { stage: null, stage_done: null, stage_of: null, stage_at: null, stage_line: null };/** * `fetch_stage { id, stage?, done?, of?, line? }`: where a download has got to while it lands. A landed film's smaller * copies are made after its row is done, so a done row takes it too; no stage clears what the row said. */export function fetchStage(engine: Engine, args: Record<string, unknown>, now: string, version: number, outcome: Outcome): { fetch: string; stage: string | null } {  const row = live(engine.store, args.id);  const state = stateOf(row);  if (state === "cancelled") refuse(409, "fetch_cancelled", "the owner cancelled this download");  if (state !== "fetching" && state !== "landing" && state !== "done") refuse(409, "not_fetching", `this download is ${state}: claim it first`);  if (blank(args.stage)) {    engine.update(row, NO_STAGE, version, outcome);    return { fetch: row.id, stage: null };  }  const stage = textOf(args.stage);  if (!STAGES.includes(stage)) refuse(400, "bad_args", `stage is one of ${STAGES.join(", ")}`);  const line = blank(args.line) ? null : oneSentence(textOf(args.line));  engine.update(row, { stage, stage_done: count(args.done, "done"), stage_of: count(args.of, "of"), stage_at: now, stage_line: line }, version, outcome);  return { fetch: row.id, stage };}/** * `fetch_landed { id, landed: [{ table, id, name?, bytes? }] }`: every file is * in; one fetch_file row per record, linking it in its own tool; the row is * done. */export function fetchLanded(engine: Engine, args: Record<string, unknown>, now: string, version: number, outcome: Outcome): { fetch: string; state: FetchState; landed: number } {  const row = held(engine, args.id);  if (!Array.isArray(args.landed)) refuse(400, "bad_args", "landed is a list of { table, id, name?, bytes? }");  const files: Data[] = [];  const seen = new Set<string>();  const linked = new Set(landedBefore(engine.store, row.id).map((f) => `${f.table}/${f.id}`));  const weighed: (number | null)[] = [];  let kept = 0;  for (const item of args.landed as unknown[]) {    const entry = item && typeof item === "object" ? (item as Record<string, unknown>) : {};    const table = textOf(entry.table);    const id = textOf(entry.id);    // Music is retired (TABLE DROP 1): a song lands nowhere, said by name.    if (table === "song") refuse(410, "retired", "Music is retired: its tables are no longer served");    const kind = LANDS[table];    if (!kind) refuse(400, "bad_args", `a download lands in ${Object.keys(LANDS).join(", ")}, not ${JSON.stringify(entry.table)}`);    const record = engine.store.get(table, id);    if (!record || record.deleted) refuse(404, "no_such_record", `no ${table} with id ${id}`);    if (seen.has(`${table}/${id}`)) continue;    seen.add(`${table}/${id}`);    // A second fetch links each record once: one the download holds already gets no second fetch_file row.    if (linked.has(`${table}/${id}`)) {      kept++;      weighed.push(count(entry.bytes, "bytes"));      continue;    }    const bytes = count(entry.bytes, "bytes");    weighed.push(bytes);    // An episode's file names its series too, from the episode's clear links (its series, else its season's film), so a    // phone holding no episodes can tell from the file alone which title it belongs to.    const series = kind === "episode" ? seriesOf(engine, record.data) : null;    files.push({ fetch: row.id, name: textOf(entry.name) || textOf(record.data.title) || id, kind, [kind]: id, ...(series ? { series } : {}), ...(bytes !== null ? { bytes: Math.round(bytes) } : {}) });  }  for (const file of files) engine.create(FETCH_FILE, file, version, outcome);  // What landed is what was fetched: the row's sizes are its files', not the fetcher's last word.  const all = weighed.length > 0 && weighed.every((b) => b !== null);  const total = weighed.reduce<number>((sum, b) => sum + (b === null ? 0 : Math.round(b)), 0);  const sizes: Data = all ? { bytes: total, of_bytes: total } : {};  const again: Data = fetchingAgain(row) ? { again_outcome: "landed", again_error: null } : {};  engine.update(row, { state: "done", finished_on: now, progress: 100, speed_bps: null, eta_seconds: null, error: null, landed_count: files.length + kept, ...NO_STAGE, ...sizes, ...again }, version, outcome);  return { fetch: row.id, state: "done", landed: files.length + kept };}/** An episode's series by its clear links: its own `series`, else its season's `film`; null when neither says. */function seriesOf(engine: Engine, episode: Data): string | null {  const own = textOf(episode.series);  if (own) return own;  const season = textOf(episode.season);  if (!season) return null;  const row = engine.store.get("film_season", season);  return row && !row.deleted ? textOf(row.data.film) || null : null;}/** One sentence of the fetcher's reason: its first line, no stack, no trailing noise, at most ERROR_MAX characters. */export function oneSentence(value: string): string {  const line = value.split(/\r?\n/).map((l) => l.trim()).find(Boolean) ?? "";  const plain = line.replace(/\s+/g, " ").trim();  return plain.length > ERROR_MAX ? `${plain.slice(0, ERROR_MAX - 1).trimEnd()}…` : plain;}/** `fetch_failed { id, error }`: the row failed, saying why. A cancelled row stays cancelled. */export function fetchFailed(engine: Engine, args: Record<string, unknown>, now: string, version: number, outcome: Outcome): { fetch: string; state: FetchState } {  const row = live(engine.store, args.id);  const state = stateOf(row);  if (state === "cancelled" || againStopped(row)) return { fetch: row.id, state };  if (state !== "fetching" && state !== "landing") refuse(409, "not_fetching", `this download is ${state}: claim it first`);  const error = oneSentence(text(args.error, "error"));  if (!error) refuse(400, "bad_args", "error says why, in one sentence");  // A second fetch that failed leaves a good download as it was: done, its earlier records linked, the reason kept apart.  if (fetchingAgain(row)) {    backToDone(engine, row, "failed", error, now, version, outcome);    return { fetch: row.id, state: "done" };  }  engine.update(row, { state: "failed", error, finished_on: now, speed_bps: null, eta_seconds: null, ...NO_STAGE }, version, outcome);  return { fetch: row.id, state: "failed" };}// ── fetching again ───────────────────────────────────────────────────────/** What `GET /v1/fetch/again` answers: ids and counts alone, from clear columns; never a link, a title or a name. */export interface AgainPlan {  /** Done downloads never fetched again that landed a film or an episode streaming without an original, oldest first. */  fetch: string[];  /** Second fetches still on their way in (queued, fetching, landing). */  running: number;  /** Second fetches that failed: their source is dead (again_error says why). */  dead: number;  /** Second fetches that landed or were cancelled, whose films still keep no original: left for the owner. */  tried: number;  /** Films and episodes streaming without an original that no download links: those can only be attached by hand. */  unaccounted: number;}const VIDEO_KINDS: Record<string, string> = { film: "film", episode: "film_episode" };/** * The downloads `pnpm fetch:again` may ask fetch_again for, and the counts it says: one read of the fetch, * fetch_file and film tables' clear columns (state, again_on, again_outcome; each link's kind and record; a * film's file and original). A film "keeps no original" when it streams (file) and its original is empty. */export function againPlan(store: Store, defines: (table: string) => boolean): AgainPlan {  const without = new Set<string>();  for (const table of ["film", "film_episode"].filter(defines)) {    for (const row of store.scan(table, [{ sql: `COALESCE(json_extract(data, '$."file"'), '') <> '' AND COALESCE(json_extract(data, '$."original"'), '') = ''`, args: [] }])) without.add(`${table}/${row.id}`);  }  const fetches = new Map<string, StoredRow>();  for (const row of store.scan(FETCH)) fetches.set(row.id, row);  const lacking = new Map<string, number>();  const accounted = new Set<string>();  for (const f of store.scan(FETCH_FILE)) {    const fetch = textOf(f.data.fetch);    const kind = textOf(f.data.kind);    const table = VIDEO_KINDS[kind];    if (!table || !fetches.has(fetch)) continue;    const key = `${table}/${textOf(f.data[kind])}`;    if (!without.has(key)) continue;    accounted.add(key);    lacking.set(fetch, (lacking.get(fetch) ?? 0) + 1);  }  const plan: AgainPlan = { fetch: [], running: 0, dead: 0, tried: 0, unaccounted: [...without].filter((k) => !accounted.has(k)).length };  const due: StoredRow[] = [];  for (const row of fetches.values()) {    if (fetchingAgain(row) && ACTIVE.includes(stateOf(row))) plan.running++;    else if (row.data.again_outcome === "failed") plan.dead++;    else if (stateOf(row) !== "done" || !lacking.has(row.id)) continue;    else if (!blank(row.data.again_on)) plan.tried++;    else due.push(row);  }  plan.fetch = due.sort((a, b) => (textOf(a.data.added_on) || a.created_at).localeCompare(textOf(b.data.added_on) || b.created_at) || a.id.localeCompare(b.id)).map((r) => r.id);  return plan;}