// THE READING LOG (plans/umtool-redesign.md, "Research, first-class" 4): each // hit of a search is read, skipped or unread, and the header says "read 37 of // 97" -- the sweep discipline's coverage rule, made visible for the human. // // REPORTS_ROOT/.umtool/research/sessions/.json // { format: "umtool-research-log", version: 1, session, query, scope, // updatedAt, marks: { "/": { state, at } } } // // A SCRATCH SESSION keyed by query + scope (facets.mjs sessionKey) until R2's // cases exist; a case will carry its own. Umtool-side, NEVER in the corpus: // REPORTS_ROOT's dot-dirs are state the project walk skips. // // 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 read treats it as empty and says so in `error`). import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LOG_FORMAT = "umtool-research-log"; export const LOG_VERSION = 1; export const MARK_STATES = ["read", "skipped"]; const SESSION_RE = /^[0-9a-f]{16}$/; // `/`: the slug grammar and the editor's id grammar. const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[\w.-]{1,128}$/; export class LogError extends Error { constructor(message, status = 400) { super(message); this.name = "LogError"; this.status = status; } } export const isSession = (s) => typeof s === "string" && SESSION_RE.test(s); export const isHitKey = (k) => typeof k === "string" && KEY_RE.test(k) && !k.split("/").some((p) => p === "." || p === ".."); /** The file for one session under a reports root. */ export function logFile(reportsRoot, session) { return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "research", "sessions", `${session}.json`); } /** * The log of one session. A missing file is an empty log; an unreadable one * is empty with `error`. * * @param {string} reportsRoot * @param {string} session * @returns {Promise<{ marks: Record, query?: string, scope?: Record, error?: string }>} */ export async function readLog(reportsRoot, session) { if (!isSession(session)) return { marks: {}, error: "not a session id" }; let text; try { text = await readFile(/* turbopackIgnore: true */ logFile(reportsRoot, session), "utf8"); } catch (err) { if (err?.code === "ENOENT") return { marks: {} }; return { marks: {}, error: `the reading log cannot be read: ${err?.message ?? err}` }; } let raw; try { raw = JSON.parse(text); } catch (err) { return { marks: {}, error: `the reading log is not JSON: ${err.message}` }; } if (!raw || typeof raw !== "object" || raw.format !== LOG_FORMAT || typeof raw.marks !== "object" || !raw.marks) { return { marks: {}, error: "not a umtool-research-log file" }; } /** @type {Record} */ const marks = {}; for (const [k, m] of Object.entries(raw.marks)) { if (!isHitKey(k) || !m || typeof m !== "object" || !MARK_STATES.includes(m.state)) continue; marks[k] = { state: m.state, at: typeof m.at === "string" ? m.at : "" }; } return { marks, ...(typeof raw.query === "string" ? { query: raw.query } : {}), ...(raw.scope && typeof raw.scope === "object" ? { scope: raw.scope } : {}), }; } /** Counts over a set of hit keys: read, skipped, unread. */ export function tally(marks, keys) { let read = 0; let skipped = 0; for (const k of keys) { const s = marks[k]?.state; if (s === "read") read++; else if (s === "skipped") skipped++; } return { read, skipped, unread: keys.length - read - skipped, total: keys.length }; } let chain = Promise.resolve(); /** * Mark one hit read, skipped, or (`unread`) clear its mark. `meta` names the * query and scope in the file, for a person reading it later. * * @param {string} reportsRoot * @param {string} session * @param {string} key `/` * @param {"read" | "skipped" | "unread"} state * @param {{ query?: string, scope?: Record, now?: Date }} [meta] */ export function markHit(reportsRoot, session, key, state, meta = {}) { if (!isSession(session)) return Promise.reject(new LogError(`not a session id: ${JSON.stringify(session)}`)); if (!isHitKey(key)) return Promise.reject(new LogError(`not a hit: ${JSON.stringify(key)} (channel/id)`)); if (state !== "unread" && !MARK_STATES.includes(state)) { return Promise.reject(new LogError(`state is read | skipped | unread, not ${JSON.stringify(state)}`)); } const run = chain.then(() => write(reportsRoot, session, key, state, meta)); chain = run.catch(() => {}); return run; } async function write(reportsRoot, session, key, state, meta) { const file = logFile(reportsRoot, session); const read = await readLog(reportsRoot, session); if (read.error) throw new LogError(`${read.error}; fix or remove ${file} first`, 409); const now = (meta.now ?? new Date()).toISOString(); const marks = { ...read.marks }; if (state === "unread") delete marks[key]; else marks[key] = { state, at: now }; const query = typeof meta.query === "string" ? meta.query.slice(0, 500) : read.query; const scope = meta.scope && typeof meta.scope === "object" ? meta.scope : read.scope; const doc = { format: LOG_FORMAT, version: LOG_VERSION, session, ...(query !== undefined ? { query } : {}), ...(scope !== undefined ? { scope } : {}), updatedAt: now, marks: Object.fromEntries(Object.entries(marks).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); const tmp = tmpPathFor(file); 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; } return { key, state, at: now, marks: doc.marks }; }