// THE CHANNEL CONTEXT NOTES, REVIEWED (plans/digest-context-review.md): the // candidate `digest-context.suggested.md` notes drafted from corpus evidence, // each with what it asserts (the note itself) and what that rests on (the plan // file's evidence for its channel), and the operator's Yes or No. // // A note reaches the digest prompt only as `digest-context.md` // (common/lib/digestContext-server.ts), and only a person puts it there: // auto-applying model-authored context is forbidden (PLAN.md), because a wrong // inference degrades every future summary for the channel and still reads as // plausible. So: // // Yes renames digest-context.suggested.md -> digest-context.md in that // channel's dir, no-clobber (a link, then the old name unlinked): an // active note already there is never overwritten. The note's sha256 must // be the one the page was shown, so what is promoted is what was read. // Promoting changes the channel's contextHash: every digest already made // for it goes stale and regenerates (the plan's "What promoting one costs"). // No writes digest-context.suggested.refused.json beside it ({by, at, // sha256}): the note is no longer pending, and the file stays. A note // redrafted since (another sha256) is pending again. // // The ONE route that does either is app/api/digest-context (handleDigestContext // below); nothing applies a note by itself, and a request carrying any // Authorization header -- the way an agent writes (lib/annotations/agentAuth.mjs) // -- is refused: the press is the operator's. These are the only two corpus // writes this module makes, both inside CHANNELS_DIR//, whose real path // must be the lexical one (a channel dir is never a link). import { createHash } from "node:crypto"; import { link, lstat, readFile, readdir, realpath, rename, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SUGGESTED = "digest-context.suggested.md"; export const ACTIVE = "digest-context.md"; export const REFUSED = "digest-context.suggested.refused.json"; /** What reaches the prompt of a note (digestContext-server.ts MAX_CONTEXT_CHARS). */ export const PROMPT_CHARS = 4000; /** A channel dir's name: one path segment, no dot-names (channels.ts slugs, YouTube handles' case kept). */ export const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; const sha256 = (text) => createHash("sha256").update(text).digest("hex"); /** * The plan file's evidence, by channel: each `### ` heading under "## Evidence * behind each note" names its channels in backticks (one heading may name three: * the HasanAbi archives share a note) and its bullets are the evidence; the * queue table gives each channel's rank and chunks remaining; "What to check * before promoting" and the first paragraph of "What promoting one costs" are * the page's head. * * @param {string} text */ export function parseReviewPlan(text) { /** @type {Record} */ const evidence = {}; /** @type {Record} */ const queue = {}; /** @type {string[]} */ const checks = []; let cost = ""; let section = ""; /** @type {{ heading: string; flag: string | null; bullets: string[]; slugs: string[] } | null} */ let cur = null; let costLines = /** @type {string[] | null} */ (null); const flush = () => { if (cur) for (const s of cur.slugs) evidence[s] = { heading: cur.heading, flag: cur.flag, bullets: cur.bullets }; cur = null; }; for (const line of String(text).split(/\r?\n/)) { if (/^## /.test(line)) { flush(); section = line.slice(3).trim(); costLines = /^What promoting one costs/i.test(section) ? [] : null; continue; } if (/^Evidence behind each note/i.test(section) && /^### /.test(line)) { flush(); const head = line.slice(4).trim(); const slugs = [...head.matchAll(/`([^`]+)`/g)].map((m) => m[1]).filter((s) => SLUG_RE.test(s)); const flag = /—\s*\*\*(.+?)\*\*/.exec(head)?.[1] ?? null; cur = { heading: head.replace(/\s*—\s*\*\*.+?\*\*\s*$/, ""), flag, bullets: [], slugs }; continue; } if (cur) { if (/^- /.test(line)) cur.bullets.push(line.slice(2).trim()); else if (/^\s{2,}\S/.test(line) && cur.bullets.length) cur.bullets[cur.bullets.length - 1] += ` ${line.trim()}`; continue; } if (/^Why these channels/i.test(section)) { const m = /^\|\s*(\d+)\s*\|\s*`([^`]+)`\s*\|\s*([\d,]+)\s*\|/.exec(line); if (m) queue[m[2]] = { rank: Number(m[1]), chunks: Number(m[3].replace(/,/g, "")) }; continue; } if (/^What to check before promoting/i.test(section)) { const m = /^\d+\.\s+(.*)$/.exec(line); if (m) checks.push(m[1].trim()); else if (/^\s{2,}\S/.test(line) && checks.length) checks[checks.length - 1] += ` ${line.trim()}`; continue; } if (costLines) { if (line.trim() === "") { if (costLines.length) { cost = costLines.join(" "); costLines = null; } } else costLines.push(line.trim()); } } flush(); if (costLines?.length) cost = costLines.join(" "); return { evidence, queue, checks, cost }; } /** @param {string} p */ async function lstatOrNull(p) { try { return await lstat(/* turbopackIgnore: true */ p); } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e).code === "ENOENT") return null; throw e; } } /** @param {string} p */ async function readJsonOrNull(p) { try { return JSON.parse(await readFile(/* turbopackIgnore: true */ p, "utf8")); } catch { return null; } } /** * The channel's dir, or why it will not be written: the slug a single segment, * the dir real (not a link) and the lexical one under the real channels dir. * * @param {string} channelsDir * @param {string} slug * @returns {Promise<{ dir: string } | { error: string; status: number }>} */ export async function channelDirOf(channelsDir, slug) { if (typeof slug !== "string" || !SLUG_RE.test(slug)) return { error: "not a channel name", status: 400 }; const root = path.resolve(/* turbopackIgnore: true */ channelsDir); const dir = path.join(/* turbopackIgnore: true */ root, slug); const st = await lstatOrNull(dir); if (!st) return { error: `no channel ${slug}`, status: 404 }; if (!st.isDirectory()) return { error: `channels/${slug} is not a directory here`, status: 409 }; const [realRoot, realDir] = await Promise.all([realpath(/* turbopackIgnore: true */ root), realpath(/* turbopackIgnore: true */ dir)]); if (realDir !== path.join(/* turbopackIgnore: true */ realRoot, slug)) return { error: `channels/${slug} resolves outside the channels dir`, status: 409 }; return { dir }; } /** * One channel's note as the page shows it, or null when it has neither a * suggested note nor (for a channel the plan names) an active one. * * @param {string} channelsDir * @param {string} slug * @param {ReturnType} plan */ export async function readChannelNote(channelsDir, slug, plan) { const at = await channelDirOf(channelsDir, slug); if (!("dir" in at)) return null; const sugPath = path.join(/* turbopackIgnore: true */ at.dir, SUGGESTED); const [sug, active, refusal] = await Promise.all([ lstatOrNull(sugPath), lstatOrNull(path.join(/* turbopackIgnore: true */ at.dir, ACTIVE)), readJsonOrNull(path.join(/* turbopackIgnore: true */ at.dir, REFUSED)), ]); const ev = plan.evidence[slug] ?? null; const q = plan.queue[slug] ?? null; const base = { slug, rank: q?.rank ?? null, chunks: q?.chunks ?? null, evidence: ev, active: !!active }; if (!sug || !sug.isFile()) { // Promoted (a channel the plan names, its note active and the suggestion gone): said, for the record. if (active && (ev || q)) return { ...base, state: /** @type {const} */ ("active"), text: null, sha256: null, chars: 0, refusal: null }; return null; } const text = await readFile(/* turbopackIgnore: true */ sugPath, "utf8"); const sha = sha256(text); const refused = refusal && typeof refusal === "object" && refusal.sha256 === sha ? { at: String(refusal.at ?? ""), by: String(refusal.by ?? "operator") } : null; return { ...base, state: refused ? /** @type {const} */ ("refused") : /** @type {const} */ ("pending"), text, sha256: sha, chars: text.trim().length, refusal: refused }; } /** * Every channel's note: the pending first (in the sweep's queue order, then by * name), then the refused, then the promoted. * * @param {{ channelsDir: string; planText?: string | null }} o */ export async function listDigestContextNotes({ channelsDir, planText = null }) { const plan = parseReviewPlan(planText ?? ""); /** @type {import("node:fs").Dirent[]} */ let ents = []; try { ents = await readdir(/* turbopackIgnore: true */ channelsDir, { withFileTypes: true }); } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e).code !== "ENOENT") throw e; } const rows = (await Promise.all(ents.filter((d) => d.isDirectory() && SLUG_RE.test(d.name)).map((d) => readChannelNote(channelsDir, d.name, plan)))).filter( (r) => r !== null, ); const order = { pending: 0, refused: 1, active: 2 }; rows.sort((a, b) => order[a.state] - order[b.state] || (a.rank ?? 1e9) - (b.rank ?? 1e9) || a.slug.localeCompare(b.slug)); return { notes: rows, checks: plan.checks, cost: plan.cost, planFound: planText !== null }; } /** * The operator's Yes or No on one channel's note. * * @param {{ channelsDir: string; slug: string; decision: string; sha256: string; planText?: string | null; now?: () => Date }} o * @returns {Promise<{ ok: true; note: Awaited> } | { ok: false; status: number; error: string }>} */ export async function decideDigestContextNote({ channelsDir, slug, decision, sha256: want, planText = null, now = () => new Date() }) { if (decision !== "yes" && decision !== "no") return { ok: false, status: 400, error: 'decision must be "yes" or "no"' }; if (typeof want !== "string" || !/^[0-9a-f]{64}$/.test(want)) return { ok: false, status: 400, error: "sha256 of the note shown is required" }; const at = await channelDirOf(channelsDir, slug); if (!("dir" in at)) return { ok: false, status: at.status, error: at.error }; const sugPath = path.join(/* turbopackIgnore: true */ at.dir, SUGGESTED); const st = await lstatOrNull(sugPath); if (!st) return { ok: false, status: 404, error: `${slug} has no ${SUGGESTED}` }; if (!st.isFile()) return { ok: false, status: 409, error: `${slug}/${SUGGESTED} is not a plain file` }; const text = await readFile(/* turbopackIgnore: true */ sugPath, "utf8"); if (sha256(text) !== want) return { ok: false, status: 409, error: `${slug}'s note changed since it was shown: read it again` }; if (decision === "yes") { const activePath = path.join(/* turbopackIgnore: true */ at.dir, ACTIVE); if (await lstatOrNull(activePath)) return { ok: false, status: 409, error: `${slug} already has an active ${ACTIVE}: it is never overwritten` }; try { // No-clobber: link fails on an existing name, where rename would replace it. await link(/* turbopackIgnore: true */ sugPath, /* turbopackIgnore: true */ activePath); } catch (e) { const code = /** @type {NodeJS.ErrnoException} */ (e).code; if (code === "EEXIST") return { ok: false, status: 409, error: `${slug} already has an active ${ACTIVE}: it is never overwritten` }; throw e; } await unlink(/* turbopackIgnore: true */ sugPath); } else { const rec = { by: "operator", at: now().toISOString(), sha256: want }; const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ at.dir, `.${REFUSED}`)); await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(rec, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, /* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ at.dir, REFUSED)); } return { ok: true, note: await readChannelNote(channelsDir, slug, parseReviewPlan(planText ?? "")) }; } /** * The route (app/api/digest-context/route.ts), as a function of its request: * GET lists, POST { slug, decision: "yes" | "no", sha256 } decides. Refused * with any Authorization header: an agent never promotes or refuses a note. * * @param {Request} request * @param {{ channelsDir: string; readPlan: () => Promise }} o */ export async function handleDigestContext(request, { channelsDir, readPlan }) { const headers = { "cache-control": "no-store" }; if (request.method === "GET") return Response.json(await listDigestContextNotes({ channelsDir, planText: await readPlan() }), { headers }); if (request.method !== "POST") return Response.json({ error: "GET or POST" }, { status: 405, headers }); if (request.headers.get("authorization")) { return Response.json({ error: "a channel's context note is promoted or refused by a person, on the page: no Authorization header" }, { status: 403, headers }); } const b = await request.json().catch(() => null); if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const r = await decideDigestContextNote({ channelsDir, slug: String(b.slug ?? ""), decision: String(b.decision ?? ""), sha256: String(b.sha256 ?? ""), planText: await readPlan() }); if (!r.ok) return Response.json({ error: r.error }, { status: r.status, headers }); return Response.json({ note: r.note }, { headers }); } /** * The plan file's text, or null: plans/digest-context-review.md in the * checkout (E2E_DIGEST_CONTEXT_PLAN in the suite, a fixture's). * * @param {string} repoRoot */ export async function readReviewPlan(repoRoot) { const p = process.env.E2E_DIGEST_CONTEXT_PLAN || path.join(/* turbopackIgnore: true */ repoRoot, "plans", "digest-context-review.md"); try { return await readFile(/* turbopackIgnore: true */ p, "utf8"); } catch { return null; } }