commit 694f2b21c94081a724dfbf82ee2657915fee5134
parent 9a37d40a19cf205fd296f810909f2bfd858229c7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 1 Nov 2026 23:58:46 -0500
umtool tools: the channel context notes' review (/tools/digest-context, Corpus on /tools, the rail's "context", the palette) -- each channel's digest-context.suggested.md in the sweep's queue order, what it asserts (the note as it would reach the prompt) beside what it rests on (plans/digest-context-review.md's evidence for that channel, parsed, the identity claim to check first flagged) under the plan's checks and cost. Yes, asked twice with what it costs (the channel's contextHash: every digest already made for it regenerates), renames it to digest-context.md no-clobber; No writes digest-context.suggested.refused.json beside it (who, when, its sha256) and keeps the file, so it is no longer pending until redrafted. ONE route, GET/POST /api/digest-context (lib/digestContextReview.mjs handleDigestContext): the note's sha256 must be the one shown, an active note is never overwritten, the channel dir must be the real one under CHANNELS_DIR, and any Authorization header -- an agent's way in -- is a 403. Unit tests against a temp channels dir (and the real plan file, read only: evidence for all eleven); digest-context.spec.ts on the fixture's testchan and testchan-odysee with a fixture plan (E2E_DIGEST_CONTEXT_PLAN); the page joins the visual audit; docs/tools.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
18 files changed, 936 insertions(+), 6 deletions(-)
diff --git a/plans/digest-context-review.md b/plans/digest-context-review.md
@@ -4,6 +4,10 @@ Eleven candidate `digest-context.suggested.md` notes, drafted 2026-08-12 from co
evidence. **None is active.** A note only reaches the prompt under the name
`digest-context.md`, and only a human puts it there:
+umtool's **Channel context notes** (`/tools/digest-context`, umtool/docs/tools.md) lists each
+note with its evidence below, and its **Yes** is that rename (its **No** records a refusal
+beside the note, which stays). By hand it is still:
+
```sh
cd transcripts/channels/<slug>
mv digest-context.suggested.md digest-context.md
diff --git a/umtool/app/api/digest-context/route.ts b/umtool/app/api/digest-context/route.ts
@@ -0,0 +1,26 @@
+import { CHANNELS_DIR } from "@/lib/paths";
+import { REPO_ROOT } from "@/lib/paths.mjs";
+import { handleDigestContext, readReviewPlan } from "@/lib/digestContextReview.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE CHANNEL CONTEXT NOTES' REVIEW (lib/digestContextReview.mjs; the page is
+// /tools/digest-context): the ONE route that promotes or refuses a channel's
+// digest-context.suggested.md. Nothing calls it but the operator's press.
+//
+// GET every channel's note: pending, refused, promoted -- each with its evidence
+// POST { slug, decision: "yes", sha256 } digest-context.suggested.md -> digest-context.md (never over an active one)
+// POST { slug, decision: "no", sha256 } digest-context.suggested.refused.json beside it; the note stays
+//
+// `sha256` is the note's as the page showed it: a note changed since is a 409.
+// Any Authorization header is a 403 -- an agent never promotes or refuses one.
+
+const o = { channelsDir: CHANNELS_DIR, readPlan: () => readReviewPlan(REPO_ROOT) };
+
+export async function GET(request: Request) {
+ return handleDigestContext(request, o);
+}
+
+export async function POST(request: Request) {
+ return handleDigestContext(request, o);
+}
diff --git a/umtool/app/tools/digest-context/page.tsx b/umtool/app/tools/digest-context/page.tsx
@@ -0,0 +1,46 @@
+import AppShell from "@/components/shell/AppShell";
+import DigestContextReview, { type DigestNote } from "@/components/tools/DigestContextReview";
+import { inline } from "@/components/tools/inlineMarks";
+import { PROMPT_CHARS, listDigestContextNotes, readReviewPlan } from "@/lib/digestContextReview.mjs";
+import { CHANNELS_DIR } from "@/lib/paths";
+import { REPO_ROOT } from "@/lib/paths.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE CHANNEL CONTEXT NOTES (plans/digest-context-review.md): every channel's
+// candidate digest-context.suggested.md, what it asserts and what it rests on,
+// and Yes (it becomes the channel's digest-context.md) or No (refused, the file
+// kept). The press is the operator's: lib/digestContextReview.mjs.
+
+export default async function DigestContextPage() {
+ const list = await listDigestContextNotes({ channelsDir: CHANNELS_DIR, planText: await readReviewPlan(REPO_ROOT) });
+ const pending = list.notes.filter((n) => n.state === "pending").length;
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell active="context" crumbs={[{ href: "/tools", label: "Tools" }, { label: "Channel context notes" }]} note={`${pending} pending`} />
+ <main className="deck-main flex-1 px-4 pb-6 pt-4" data-digest-review="">
+ <div className="mb-5 grid gap-4 md:grid-cols-2">
+ <div>
+ <div className="micro mb-1">check before promoting</div>
+ {list.checks.length ? (
+ <ol className="m-0 space-y-1 pl-5 text-[12.5px] leading-[1.5]">
+ {list.checks.map((c, i) => (
+ <li key={i}>{inline(c)}</li>
+ ))}
+ </ol>
+ ) : (
+ <p className="m-0 text-[12px] text-[var(--color-dim)]">{list.planFound ? "The plan lists no checks." : "plans/digest-context-review.md is not in this checkout: no evidence to show."}</p>
+ )}
+ </div>
+ {list.cost && (
+ <div>
+ <div className="micro mb-1">what promoting one costs</div>
+ <p className="m-0 text-[12.5px] leading-[1.5]">{inline(list.cost)}</p>
+ </div>
+ )}
+ </div>
+ <DigestContextReview initial={list.notes as DigestNote[]} promptChars={PROMPT_CHARS} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/app/tools/page.tsx b/umtool/app/tools/page.tsx
@@ -1,6 +1,6 @@
import AppShell from "@/components/shell/AppShell";
import ToolList, { PILE_WHAT, type ToolEntry } from "@/components/tools/ToolList";
-import { benchHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs";
+import { benchHref, digestContextHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs";
import { TRIM_SETS } from "@/lib/trim";
export const dynamic = "force-dynamic";
@@ -27,7 +27,10 @@ export default function ToolsPage() {
const montage: ToolEntry[] = [
{ href: phraseFinderHref(), name: "phrases", what: "How often phrases were said, by year, and a montage from one", testid: "phrases" },
];
- const n = song.length + articles.length + montage.length;
+ const corpus: ToolEntry[] = [
+ { href: digestContextHref(), name: "context notes", what: "Each channel's suggested digest context note, its evidence, and your Yes or No", testid: "context" },
+ ];
+ const n = song.length + articles.length + montage.length + corpus.length;
return (
<div className="flex h-full flex-col">
<AppShell active="tools" crumbs={[{ label: "Tools" }]} meta={`${n} tools`} />
@@ -37,6 +40,7 @@ export default function ToolsPage() {
{ title: "Song", tools: song },
{ title: "Montage", tools: montage },
{ title: "Articles", tools: articles },
+ { title: "Corpus", tools: corpus },
]}
/>
</main>
diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx
@@ -2,6 +2,7 @@ import Link from "next/link";
import { MODES } from "@/lib/types";
import {
benchHref,
+ digestContextHref,
findHref,
facesHref,
homeHref,
@@ -44,6 +45,7 @@ const TOOL_ITEMS = [
{ href: facesHref(), label: "faces" },
{ href: sourcesHref(), label: "sources" },
{ href: benchHref(), label: "bench" },
+ { href: digestContextHref(), label: "context" },
];
const PLACE_OF: Record<string, string> = {
diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
benchHref,
+ digestContextHref,
createHref,
facesHref,
findHref,
@@ -57,6 +58,7 @@ const FIXED: Item[] = [
{ id: "faces", section: "Tools", label: "Faces", hint: "the face judger", href: facesHref() },
{ id: "sources", section: "Tools", label: "Sources", hint: "where the palette comes from", href: sourcesHref() },
{ id: "bench", section: "Tools", label: "Verdict bench", hint: "could a model propose a verdict", href: benchHref() },
+ { id: "context", section: "Tools", label: "Channel context notes", hint: "each suggested digest note, its evidence, Yes or No", href: digestContextHref() },
// Each opens one line of /create (P5), its form open.
{ id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) },
{ id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) },
diff --git a/umtool/components/tools/DigestContextReview.tsx b/umtool/components/tools/DigestContextReview.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { inline } from "./inlineMarks";
+
+// THE CHANNEL CONTEXT NOTES (lib/digestContextReview.mjs; /tools/digest-context):
+// each candidate note as it would reach the digest prompt, beside what the plan
+// says it rests on, and the operator's Yes or No. Yes is asked twice -- the
+// cost is every digest already made for that channel -- and only then sent to
+// the one route. Nothing here decides anything by itself.
+
+export type DigestNote = {
+ slug: string;
+ state: "pending" | "refused" | "active";
+ rank: number | null;
+ chunks: number | null;
+ active: boolean;
+ text: string | null;
+ sha256: string | null;
+ chars: number;
+ refusal: { at: string; by: string } | null;
+ evidence: { heading: string; flag: string | null; bullets: string[] } | null;
+};
+
+const day = (iso: string) => {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? iso : d.toISOString().slice(0, 10);
+};
+
+export default function DigestContextReview({ initial, promptChars }: { initial: DigestNote[]; promptChars: number }) {
+ const [notes, setNotes] = useState(initial);
+ const [confirming, setConfirming] = useState<string | null>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [errors, setErrors] = useState<Record<string, string>>({});
+
+ const decide = async (n: DigestNote, decision: "yes" | "no") => {
+ setBusy(n.slug);
+ setErrors((e) => ({ ...e, [n.slug]: "" }));
+ try {
+ const r = await fetch("/api/digest-context", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ slug: n.slug, decision, sha256: n.sha256 }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { note?: DigestNote | null; error?: string };
+ if (!r.ok) {
+ setErrors((e) => ({ ...e, [n.slug]: j.error ?? `HTTP ${r.status}` }));
+ return;
+ }
+ setNotes((all) => (j.note ? all.map((x) => (x.slug === n.slug ? j.note! : x)) : all.filter((x) => x.slug !== n.slug)));
+ setConfirming(null);
+ } catch (e) {
+ setErrors((x) => ({ ...x, [n.slug]: e instanceof Error ? e.message : String(e) }));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const pending = notes.filter((n) => n.state === "pending");
+ const decided = notes.filter((n) => n.state !== "pending");
+
+ return (
+ <div className="space-y-6">
+ <p className="m-0 text-[12px] text-[var(--color-dim)]" data-digest-counts="">
+ <span data-digest-pending={pending.length}>{pending.length} pending</span> · {notes.filter((n) => n.state === "refused").length} refused ·{" "}
+ {notes.filter((n) => n.state === "active").length} active
+ </p>
+ {pending.length === 0 && (
+ <p className="m-0 text-[12.5px]" data-digest-none="">
+ No note is waiting on you.
+ </p>
+ )}
+ {[...pending, ...decided].map((n) => {
+ const ask = confirming === n.slug;
+ return (
+ <section key={n.slug} data-digest-note={n.slug} data-digest-state={n.state} className="border-t border-[var(--color-line)] pt-3">
+ <header className="mb-2 flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h2 className="m-0 font-mono text-[14px] text-text">{n.slug}</h2>
+ {n.rank !== null && (
+ <span className="text-[11.5px] text-[var(--color-dim)]">
+ #{n.rank} in the sweep's queue{n.chunks !== null ? ` · ${n.chunks.toLocaleString("en-US")} chunks to generate` : ""}
+ </span>
+ )}
+ {n.evidence?.flag && (
+ <span className="text-[11.5px] font-semibold text-[var(--color-dirty)]" data-digest-flag="">
+ {n.evidence.flag}
+ </span>
+ )}
+ <span className="micro ml-auto" data-digest-status="">
+ {n.state === "pending" ? "pending" : n.state === "refused" ? `refused ${day(n.refusal?.at ?? "")}` : "active: digest-context.md"}
+ </span>
+ </header>
+ {n.state !== "active" && (
+ <div className="grid gap-4 md:grid-cols-2">
+ <div className="min-w-0">
+ <div className="micro mb-1">what it asserts — digest-context.suggested.md</div>
+ <pre data-digest-text="" className="m-0 max-h-[360px] overflow-auto whitespace-pre-wrap break-words rounded-[3px] border border-[var(--color-line)] bg-panel p-2.5 font-sans text-[12.5px] leading-[1.5] text-text">
+ {n.text}
+ </pre>
+ {n.chars > promptChars && (
+ <p className="m-0 mt-1 text-[11px] text-[var(--color-dirty)]">
+ {n.chars} characters: only the first {promptChars} reach the prompt.
+ </p>
+ )}
+ </div>
+ <div className="min-w-0">
+ <div className="micro mb-1">what it rests on — the plan's evidence</div>
+ {n.evidence ? (
+ <ul data-digest-evidence="" className="m-0 space-y-1.5 pl-4 text-[12.5px] leading-[1.5]">
+ {n.evidence.bullets.map((b, i) => (
+ <li key={i}>{inline(b)}</li>
+ ))}
+ </ul>
+ ) : (
+ <p data-digest-evidence="" className="m-0 text-[12px] text-[var(--color-dim)]">
+ The plan gives no evidence for this channel: judge the note on its own.
+ </p>
+ )}
+ </div>
+ </div>
+ )}
+ {n.state !== "active" && (
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ {!ask ? (
+ <>
+ <button
+ type="button"
+ data-digest-yes={n.slug}
+ disabled={busy !== null || n.active}
+ onClick={() => setConfirming(n.slug)}
+ className={buttonVariants({ size: "sm" })}
+ title={n.active ? "this channel already has an active digest-context.md" : "make it the channel's digest-context.md"}
+ >
+ Yes, make it active
+ </button>
+ {n.state === "pending" && (
+ <button type="button" data-digest-no={n.slug} disabled={busy !== null} onClick={() => void decide(n, "no")} className={buttonVariants({ size: "sm" })}>
+ No
+ </button>
+ )}
+ {n.active && <span className="text-[11.5px] text-[var(--color-dim)]">This channel already has an active digest-context.md: it is never overwritten.</span>}
+ </>
+ ) : (
+ <>
+ <span className="text-[12px]" data-digest-confirm={n.slug}>
+ {n.slug}'s note becomes <code className="font-mono">digest-context.md</code>: every digest already made for this channel goes stale and
+ regenerates.
+ </span>
+ <button type="button" data-digest-confirm-yes={n.slug} disabled={busy !== null} onClick={() => void decide(n, "yes")} className={buttonVariants({ size: "sm" })}>
+ Make it active
+ </button>
+ <button type="button" disabled={busy !== null} onClick={() => setConfirming(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ </>
+ )}
+ {errors[n.slug] && (
+ <span className="text-[11.5px] text-[var(--color-bad)]" data-digest-error={n.slug}>
+ {errors[n.slug]}
+ </span>
+ )}
+ </div>
+ )}
+ </section>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/umtool/components/tools/inlineMarks.tsx b/umtool/components/tools/inlineMarks.tsx
@@ -0,0 +1,18 @@
+import { Fragment, type ReactNode } from "react";
+
+// The plan files' inline marks, for a page that quotes one (the channel context notes' evidence). Server-safe.
+
+/** `**bold**` and `` `code` `` -- all the plan's evidence lines use. */
+export function inline(s: string): ReactNode {
+ const out: ReactNode[] = [];
+ const re = /\*\*(.+?)\*\*|`([^`]+)`/g;
+ let at = 0;
+ let k = 0;
+ for (let m = re.exec(s); m; m = re.exec(s)) {
+ if (m.index > at) out.push(<Fragment key={k++}>{s.slice(at, m.index)}</Fragment>);
+ out.push(m[1] !== undefined ? <strong key={k++}>{inline(m[1])}</strong> : <code key={k++} className="font-mono text-[0.95em]">{m[2]}</code>);
+ at = m.index + m[0].length;
+ }
+ if (at < s.length) out.push(<Fragment key={k++}>{s.slice(at)}</Fragment>);
+ return out;
+}
diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md
@@ -2,9 +2,9 @@
## `/tools`
-Three lists. **Song**: song piles, find, mix, faces, sources, a trim set. **Montage**: the phrase finder. **Articles**:
-the verdict bench. While you are in a tool the rail opens Tools into its tools: find · mix · phrases · **song ▸** (the
-four piles) · faces · sources · bench.
+Four lists. **Song**: song piles, find, mix, faces, sources, a trim set. **Montage**: the phrase finder. **Articles**:
+the verdict bench. **Corpus**: the channel context notes. While you are in a tool the rail opens Tools into its tools:
+find · mix · phrases · **song ▸** (the four piles) · faces · sources · bench · context.
| Tool | Address | What it is |
|---|---|---|
@@ -16,11 +16,31 @@ four piles) · faces · sources · bench.
| Sources | `/tools/sources` | where the song palette comes from: placements (the finished runtime an episode supplies) and clips (the palette) per episode — different units, both shown, never summed — the top episode, the top five, how many cover half |
| Trim | `/tools/trim/<set>` | a hook set's trims against the waveform, then **run the chain** (apply-hook-trims → pick-take → mix-hooks) |
| Verdict bench | `/tools/bench` | could a model propose a fact-check verdict well enough to review: runs of `archilyzer reports bench-verdicts`, each with its prompt version and items hash, each model's agreement and recalls against the bar (**passes the bar** / **fails the bar**), confusion matrices, the items; **compare with** another run over the same items (each model's agreement in both, the claims whose answers changed); **Right** / **Wrong** on each disagreement (was the model right? kept in the run's `marks.json`), and not-CORROBORATED precision and recall as ruled and as marked beside the bar; what the verdicts mean. The bar is set here (`settings.generation.verdicts`), and with it the window proposals read (`verdicts.window`: the run's window mode and seconds); a ticked model is the only kind verdict proposals run on (the Inbox's `verdict-proposed`, [inbox.md](inbox.md)) |
+| Channel context notes | `/tools/digest-context` | each channel's candidate `digest-context.suggested.md` ([below](#channel-context-notes-toolsdigest-context)): what it asserts beside what it rests on, and **Yes** or **No** |
A song's own page links its piles, find, mix and sources (its Overview's Song tools; [piece.md](piece.md#a-song-projectspath)).
The old addresses (`/sort`, `/salvage`, `/verify`, `/keeps`, `/mix`, `/bench`, `/browse/find`, `/browse/faces`,
`/browse/sources`, `/browse/trim/<set>`) redirect here.
+## Channel context notes (`/tools/digest-context`)
+
+The candidate per-channel digest notes ([plans/digest-context-review.md](../../plans/digest-context-review.md)), one
+at a time in the sweep's queue order: what each **asserts** (the `digest-context.suggested.md` in
+`CHANNELS_DIR/<slug>/`, as it would reach the prompt — only its first 4,000 characters do) beside what it **rests on**
+(the plan's evidence for that channel), the identity claim to check first flagged, and the plan's checks and cost
+above them.
+
+- **Yes, make it active** asks once more, saying what it costs — the channel's `contextHash` changes, so every digest
+ already made for it goes stale and regenerates — and then renames the note to `digest-context.md` in that channel's
+ dir. An active note already there is never overwritten, and a note changed since the page showed it is refused
+ (409: read it again).
+- **No** records the refusal beside the note (`digest-context.suggested.refused.json`: who, when, the note's sha256);
+ the note is no longer pending and the file stays. A note redrafted since is pending again.
+
+Nothing applies a note by itself. The one route is `GET`/`POST /api/digest-context` (`lib/digestContextReview.mjs`),
+and a request carrying any `Authorization` header — the way an agent writes — is a 403: the press is the operator's.
+Besides the notes files (`lib/paths.mjs` isCorpusNotesFile), these two are the only corpus files umtool writes.
+
## The phrase finder (`/tools/phrases`)
Finding the next montage phrase, with no model. Type phrases — one row each, **Add phrase** for another — pick the
diff --git a/umtool/e2e/digest-context.spec.ts b/umtool/e2e/digest-context.spec.ts
@@ -0,0 +1,96 @@
+import { test, expect } from "@playwright/test";
+import { createHash } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { DIGEST_NOTES, makeDigestContextFixture } from "./fixtures/digest-context-fixture.mjs";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The channel context notes' review (/tools/digest-context;
+// lib/digestContextReview.mjs, plans/digest-context-review.md): each candidate
+// digest-context.suggested.md with what it asserts and the plan's evidence,
+// and the operator's Yes (it becomes the channel's digest-context.md, asked
+// twice) or No (a refusal recorded beside it, the file kept). Fixture:
+// e2e/fixtures/digest-context-fixture.mjs -- the fixture's own channels and
+// plan, put back before and after.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const CHANNELS = path.join(FIXTURE, "channels");
+const file = (slug: string, name: string) => path.join(CHANNELS, slug, name);
+const reset = () => makeDigestContextFixture({ dest: FIXTURE, channels: CHANNELS });
+
+test.beforeAll(reset);
+test.afterAll(reset);
+
+test("each note with its evidence; No refuses it and keeps the file; Yes, asked twice, makes it the channel's digest-context.md", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 900 });
+ // Found from Tools.
+ await page.goto(urls.toolsHref());
+ await expect(page.locator("[data-tool-entry=context] a")).toHaveAttribute("href", urls.digestContextHref());
+ await page.goto(urls.digestContextHref());
+
+ const note = (slug: string) => page.locator(`[data-digest-note="${slug}"]`);
+ await expect(page.locator("[data-digest-pending]")).toHaveAttribute("data-digest-pending", "2");
+ // In the sweep's queue order, the identity claim to check first flagged.
+ expect(await page.locator("[data-digest-note]").evaluateAll((els) => els.map((e) => e.getAttribute("data-digest-note")))).toEqual(["testchan", "testchan-odysee"]);
+ await expect(note("testchan")).toContainText("#1 in the sweep's queue · 1,234 chunks to generate");
+ await expect(note("testchan").locator("[data-digest-flag]")).toHaveText("check this one first");
+ // What it asserts (the note, as it would reach the prompt) and what it rests on (the plan's bullets).
+ await expect(note("testchan").locator("[data-digest-text]")).toContainText("This channel belongs to Test Host, who streams alone.");
+ await expect(note("testchan").locator("[data-digest-evidence] li")).toHaveCount(2);
+ await expect(note("testchan").locator("[data-digest-evidence] li").first().locator("strong")).toHaveText("Claims the host streams alone.");
+ await expect(note("testchan-odysee").locator("[data-digest-evidence]")).toContainText("40 of 50 titles match");
+ await expect(page.locator("[data-digest-review]")).toContainText("every digest already generated for that channel becomes stale and regenerates");
+ // It fits a desk without scrolling sideways.
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
+ await page.screenshot({ path: test.info().outputPath("digest-context-1366.png"), fullPage: true });
+
+ // No: refused, listed as such, the note still on disk, the refusal beside it.
+ await note("testchan-odysee").locator("[data-digest-no]").click();
+ await expect(note("testchan-odysee")).toHaveAttribute("data-digest-state", "refused");
+ await expect(note("testchan-odysee").locator("[data-digest-status]")).toContainText("refused");
+ await expect(note("testchan-odysee").locator("[data-digest-no]")).toHaveCount(0);
+ expect(readFileSync(file("testchan-odysee", "digest-context.suggested.md"), "utf8")).toBe(DIGEST_NOTES["testchan-odysee"]);
+ const refusal = JSON.parse(readFileSync(file("testchan-odysee", "digest-context.suggested.refused.json"), "utf8"));
+ expect(refusal).toMatchObject({ by: "operator", sha256: createHash("sha256").update(DIGEST_NOTES["testchan-odysee"]).digest("hex") });
+ expect(existsSync(file("testchan-odysee", "digest-context.md"))).toBe(false);
+ await expect(page.locator("[data-digest-pending]")).toHaveAttribute("data-digest-pending", "1");
+
+ // Yes asks first, with what it costs; Cancel writes nothing.
+ await note("testchan").locator("[data-digest-yes]").click();
+ await expect(note("testchan").locator("[data-digest-confirm]")).toContainText("every digest already made for this channel goes stale and regenerates");
+ await page.screenshot({ path: test.info().outputPath("digest-context-confirm.png") });
+ await note("testchan").getByRole("button", { name: "Cancel" }).click();
+ expect(existsSync(file("testchan", "digest-context.md"))).toBe(false);
+ await note("testchan").locator("[data-digest-yes]").click();
+ await note("testchan").locator("[data-digest-confirm-yes]").click();
+ await expect(note("testchan")).toHaveAttribute("data-digest-state", "active");
+ expect(readFileSync(file("testchan", "digest-context.md"), "utf8")).toBe(DIGEST_NOTES.testchan);
+ expect(existsSync(file("testchan", "digest-context.suggested.md"))).toBe(false);
+
+ // Read again: nothing pending; the refused one and the active one stay listed.
+ await page.reload();
+ await expect(page.locator("[data-digest-none]")).toHaveText("No note is waiting on you.");
+ await expect(note("testchan")).toHaveAttribute("data-digest-state", "active");
+ await expect(note("testchan-odysee")).toHaveAttribute("data-digest-state", "refused");
+ await page.screenshot({ path: test.info().outputPath("digest-context-decided.png"), fullPage: true });
+ // And at a phone's width, no sideways scroll.
+ await page.setViewportSize({ width: 390, height: 844 });
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
+});
+
+test("the route: an agent's request (any Authorization header) is refused, a note changed since it was shown is a 409", async ({ request }) => {
+ reset();
+ const sha = createHash("sha256").update(DIGEST_NOTES.testchan).digest("hex");
+ const asAgent = await request.post("/api/digest-context", { data: { slug: "testchan", decision: "yes", sha256: sha }, headers: { authorization: "Bearer umtool-e2e-token" } });
+ expect(asAgent.status()).toBe(403);
+ expect(existsSync(file("testchan", "digest-context.md"))).toBe(false);
+ const stale = await request.post("/api/digest-context", { data: { slug: "testchan", decision: "yes", sha256: "0".repeat(64) } });
+ expect(stale.status()).toBe(409);
+ expect(existsSync(file("testchan", "digest-context.suggested.md"))).toBe(true);
+ const list = await (await request.get("/api/digest-context")).json();
+ expect(list.notes.map((n: { slug: string; state: string }) => `${n.slug}:${n.state}`)).toEqual(["testchan:pending", "testchan-odysee:pending"]);
+});
diff --git a/umtool/e2e/fixtures/digest-context-fixture.mjs b/umtool/e2e/fixtures/digest-context-fixture.mjs
@@ -0,0 +1,55 @@
+// What digest-context.spec.ts reviews (lib/digestContextReview.mjs; the page
+// /tools/digest-context): two candidate channel context notes in the fixture's
+// corpus -- testchan and testchan-odysee, channels make-fixture.mjs already
+// makes, so no other spec's channel count moves -- and a plan file of the real
+// one's shape (plans/digest-context-review.md) naming their evidence, which the
+// app reads through E2E_DIGEST_CONTEXT_PLAN. Never the real corpus or plan.
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const DIGEST_NOTES = {
+ testchan: "This channel belongs to Test Host, who streams alone.\n\nRecurring segments:\n\n- \"Test News\" — a news-reaction segment\n",
+ "testchan-odysee": "The Odysee mirror of testchan: the same streams, re-uploaded.\n",
+};
+
+export const DIGEST_PLAN = `# Channel context notes — candidates awaiting review (fixture)
+
+## Why these channels, in this order
+
+| # | Channel | Chunks remaining | Note |
+| ---: | --- | ---: | --- |
+| 1 | \`testchan\` | 1,234 | drafted |
+| 2 | \`testchan-odysee\` | 56 | drafted |
+
+## Evidence behind each note
+
+### \`testchan\` — **check this one first**
+- **Claims the host streams alone.** Rests on: "Test Host" in 150/150 descriptions.
+- "Test News" in 12 of 150 titles.
+
+### \`testchan-odysee\`
+- Same streams as \`testchan\`: 40 of 50 titles match.
+
+## What to check before promoting
+
+1. **Identity claims** — testchan = Test Host's channel.
+2. **Cast lists** — a one-off guest listed as a regular.
+
+## What promoting one costs, and how to tell it worked
+
+Promoting a note changes that channel's \`contextHash\`, so **every digest already
+generated for that channel becomes stale and regenerates.**
+`;
+
+/** Write (or put back) the two notes and the plan; nothing decided. */
+export function makeDigestContextFixture({ dest, channels }) {
+ for (const [slug, text] of Object.entries(DIGEST_NOTES)) {
+ const dir = path.join(channels, slug);
+ mkdirSync(dir, { recursive: true });
+ for (const f of ["digest-context.md", "digest-context.suggested.refused.json"]) rmSync(path.join(dir, f), { force: true });
+ writeFileSync(path.join(dir, "digest-context.suggested.md"), text);
+ }
+ const plan = path.join(dest, "digest-context-review.md");
+ writeFileSync(plan, DIGEST_PLAN);
+ return { plan };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -38,6 +38,7 @@ import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
+import { makeDigestContextFixture } from "./digest-context-fixture.mjs";
import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs";
import { makeVideoAssistFixture } from "./video-assist-fixture.mjs";
@@ -2236,6 +2237,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 });
+// Two channel context notes to review (digest-context.spec.ts), on channels already made above.
+makeDigestContextFixture({ 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 });
// R3: transparent runs -- a traced sweep, an imported turns-only one with two
diff --git a/umtool/e2e/visual-audit.spec.ts b/umtool/e2e/visual-audit.spec.ts
@@ -68,6 +68,7 @@ const PAGES: [string, string][] = [
["tools-trim", urls.trimHref("mk-hooks")],
["tools-sources", urls.sourcesHref()],
["tools-bench", urls.benchHref()],
+ ["tools-digest-context", urls.digestContextHref()],
["settings-generation", urls.generationPolicyHref()],
["settings-system", urls.systemHref()],
];
diff --git a/umtool/lib/digestContextReview.mjs b/umtool/lib/digestContextReview.mjs
@@ -0,0 +1,280 @@
+// 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/<slug>/, 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";
+
+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<string, { heading: string; flag: string | null; bullets: string[] }>} */
+ const evidence = {};
+ /** @type {Record<string, { rank: number; chunks: number }>} */
+ 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<typeof parseReviewPlan>} 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<ReturnType<typeof readChannelNote>> } | { 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 = path.join(/* turbopackIgnore: true */ at.dir, `.${REFUSED}.${process.pid}.tmp`);
+ 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<string | null> }} 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;
+ }
+}
diff --git a/umtool/lib/digestContextReview.test.mjs b/umtool/lib/digestContextReview.test.mjs
@@ -0,0 +1,191 @@
+// The channel context notes' review (lib/digestContextReview.mjs): the plan's
+// evidence parsed (from the real plan file, read only), and the one route's
+// Yes and No against a TEMP channels dir -- never the corpus.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { ACTIVE, REFUSED, SUGGESTED, handleDigestContext, listDigestContextNotes, parseReviewPlan } from "./digestContextReview.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REAL_PLAN = path.join(HERE, "..", "..", "plans", "digest-context-review.md");
+const sha = (t) => createHash("sha256").update(t).digest("hex");
+
+const PLAN = `# Notes
+
+## Why these channels, in this order
+
+| # | Channel | Chunks remaining | Note |
+| ---: | --- | ---: | --- |
+| 1 | \`alpha\` | 1,200 | drafted |
+| 2 | \`beta\` | 900 | drafted |
+
+## Evidence behind each note
+
+### \`alpha\` — **check this one first**
+- **Claims it is the archive of A.** Rests on titles
+ "A plays", "A talks".
+- The segment labels are the channel's own.
+
+### \`beta\`, \`gamma\`
+- Same show, two archives.
+
+## What to check before promoting
+
+1. **Identity claims** — alpha = A's archive.
+2. **Cast lists** — a one-off guest listed as a regular.
+
+## What promoting one costs, and how to tell it worked
+
+Promoting a note changes that channel's \`contextHash\`, so **every digest already
+generated for that channel becomes stale and regenerates.**
+
+Nothing else is touched.
+`;
+
+function tempChannels() {
+ const root = mkdtempSync(path.join(os.tmpdir(), "umtool-digest-ctx-"));
+ const channels = path.join(root, "channels");
+ for (const slug of ["alpha", "beta", "gamma", "plain"]) mkdirSync(path.join(channels, slug), { recursive: true });
+ writeFileSync(path.join(channels, "alpha", SUGGESTED), "This channel is A's archive.\n");
+ writeFileSync(path.join(channels, "beta", SUGGESTED), "The host is B.\n");
+ writeFileSync(path.join(channels, "gamma", ACTIVE), "Already active.\n");
+ writeFileSync(path.join(channels, "gamma", SUGGESTED), "A second draft.\n");
+ return { root, channels };
+}
+
+const call = (channels, init) =>
+ handleDigestContext(new Request("http://x/api/digest-context", init), { channelsDir: channels, readPlan: async () => PLAN });
+const post = (channels, body, headers = {}) =>
+ call(channels, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
+
+test("the plan's evidence, queue, checks and cost, by channel", () => {
+ const p = parseReviewPlan(PLAN);
+ assert.deepEqual(p.queue, { alpha: { rank: 1, chunks: 1200 }, beta: { rank: 2, chunks: 900 } });
+ assert.equal(p.evidence.alpha.flag, "check this one first");
+ assert.equal(p.evidence.alpha.heading, "`alpha`");
+ assert.deepEqual(p.evidence.alpha.bullets, ['**Claims it is the archive of A.** Rests on titles "A plays", "A talks".', "The segment labels are the channel's own."]);
+ // One heading, two channels: the evidence is each one's.
+ assert.equal(p.evidence.gamma.bullets[0], "Same show, two archives.");
+ assert.deepEqual(p.evidence.beta, p.evidence.gamma);
+ assert.equal(p.checks.length, 2);
+ assert.match(p.cost, /every digest already generated for that channel becomes stale/);
+});
+
+test("the real plan file gives evidence for every one of its eleven channels", { skip: !existsSync(REAL_PLAN) && "no plans/ here" }, () => {
+ const p = parseReviewPlan(readFileSync(REAL_PLAN, "utf8"));
+ const eleven = ["omnibased", "HasanAbiVODs3", "destiny", "rekietalaw", "the-quartering", "chibi-reviews", "chrissie-mayr", "HasanAbiVODs", "kirsche", "nuxanor", "HasanAbiVODsbackup"];
+ assert.deepEqual(Object.keys(p.queue).sort(), [...eleven].sort());
+ for (const slug of eleven) assert.ok(p.evidence[slug]?.bullets.length, `evidence for ${slug}`);
+ assert.equal(p.evidence.omnibased.flag, "check this one first");
+ assert.equal(p.queue.omnibased.chunks, 16747);
+ assert.equal(p.checks.length, 3);
+ assert.match(p.cost, /contextHash/);
+});
+
+test("GET lists the pending notes in queue order, each with its evidence; a channel with no note is not listed", async () => {
+ const { root, channels } = tempChannels();
+ try {
+ const r = await call(channels, { method: "GET" });
+ assert.equal(r.status, 200);
+ const j = await r.json();
+ assert.deepEqual(j.notes.map((n) => [n.slug, n.state, n.active]), [["alpha", "pending", false], ["beta", "pending", false], ["gamma", "pending", true]]);
+ assert.equal(j.notes[0].text, "This channel is A's archive.\n");
+ assert.equal(j.notes[0].sha256, sha("This channel is A's archive.\n"));
+ assert.equal(j.notes[0].chunks, 1200);
+ assert.equal(j.notes[0].evidence.bullets.length, 2);
+ assert.equal(j.checks.length, 2);
+ assert.equal(j.planFound, true);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("Yes renames the suggestion to digest-context.md -- the note shown, never over an active one", async () => {
+ const { root, channels } = tempChannels();
+ try {
+ const text = "This channel is A's archive.\n";
+ // The note it was shown, or nothing.
+ let r = await post(channels, { slug: "alpha", decision: "yes", sha256: sha("something else") });
+ assert.equal(r.status, 409);
+ assert.match((await r.json()).error, /changed since it was shown/);
+ assert.ok(existsSync(path.join(channels, "alpha", SUGGESTED)));
+ r = await post(channels, { slug: "alpha", decision: "yes", sha256: sha(text) });
+ assert.equal(r.status, 200);
+ // (alpha is in the plan's queue: listed on as promoted.)
+ assert.equal((await r.json()).note.state, "active");
+ assert.equal(readFileSync(path.join(channels, "alpha", ACTIVE), "utf8"), text);
+ assert.equal(existsSync(path.join(channels, "alpha", SUGGESTED)), false);
+ const j = await (await call(channels, { method: "GET" })).json();
+ assert.deepEqual(j.notes.map((n) => [n.slug, n.state]), [["beta", "pending"], ["gamma", "pending"], ["alpha", "active"]]);
+ // gamma has an active note already: Yes is refused, both files as they were.
+ const g = await post(channels, { slug: "gamma", decision: "yes", sha256: sha("A second draft.\n") });
+ assert.equal(g.status, 409);
+ assert.match((await g.json()).error, /already has an active digest-context\.md/);
+ assert.equal(readFileSync(path.join(channels, "gamma", ACTIVE), "utf8"), "Already active.\n");
+ assert.ok(existsSync(path.join(channels, "gamma", SUGGESTED)));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("No records the refusal beside the note, which stays; a redrafted note is pending again", async () => {
+ const { root, channels } = tempChannels();
+ try {
+ const r = await post(channels, { slug: "beta", decision: "no", sha256: sha("The host is B.\n") });
+ assert.equal(r.status, 200);
+ const { note } = await r.json();
+ assert.equal(note.state, "refused");
+ assert.equal(note.refusal.by, "operator");
+ assert.equal(readFileSync(path.join(channels, "beta", SUGGESTED), "utf8"), "The host is B.\n");
+ const rec = JSON.parse(readFileSync(path.join(channels, "beta", REFUSED), "utf8"));
+ assert.equal(rec.sha256, sha("The host is B.\n"));
+ let j = await (await call(channels, { method: "GET" })).json();
+ assert.deepEqual(j.notes.filter((n) => n.state === "pending").map((n) => n.slug), ["alpha", "gamma"]);
+ writeFileSync(path.join(channels, "beta", SUGGESTED), "The host is B, with C.\n");
+ j = await (await call(channels, { method: "GET" })).json();
+ assert.equal(j.notes.find((n) => n.slug === "beta").state, "pending");
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("refused: an Authorization header (an agent), a bad name, a link out, a bad decision, a missing note", async () => {
+ const { root, channels } = tempChannels();
+ try {
+ const good = { slug: "alpha", decision: "yes", sha256: sha("This channel is A's archive.\n") };
+ let r = await post(channels, good, { authorization: "Bearer umtool-e2e-token" });
+ assert.equal(r.status, 403);
+ assert.ok(existsSync(path.join(channels, "alpha", SUGGESTED)), "nothing renamed");
+ for (const slug of ["../alpha", "alpha/..", ".", "..", "a/b", ""]) {
+ r = await post(channels, { ...good, slug });
+ assert.equal(r.status, 400, slug);
+ }
+ // A channel dir that is a link out of the channels dir is not written.
+ const outside = path.join(root, "outside");
+ mkdirSync(outside);
+ writeFileSync(path.join(outside, SUGGESTED), "x\n");
+ symlinkSync(outside, path.join(channels, "linked"));
+ r = await post(channels, { slug: "linked", decision: "no", sha256: sha("x\n") });
+ assert.equal(r.status, 409);
+ assert.equal(existsSync(path.join(outside, REFUSED)), false);
+ r = await post(channels, { ...good, decision: "maybe" });
+ assert.equal(r.status, 400);
+ r = await post(channels, { slug: "plain", decision: "no", sha256: sha("x") });
+ assert.equal(r.status, 404);
+ r = await post(channels, { slug: "nope", decision: "no", sha256: sha("x") });
+ assert.equal(r.status, 404);
+ r = await call(channels, { method: "DELETE" });
+ assert.equal(r.status, 405);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("no channels dir at all: an empty list, not an error", async () => {
+ const j = await listDigestContextNotes({ channelsDir: path.join(os.tmpdir(), "umtool-no-such-channels-dir"), planText: null });
+ assert.deepEqual(j, { notes: [], checks: [], cost: "", planFound: false });
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -421,6 +421,11 @@ export function benchHref(q: { run?: string; model?: string; verdict?: string }
return withQuery("/tools/bench", q);
}
+/** The channel context notes awaiting review (plans/digest-context-review.md): Yes or No on each. */
+export function digestContextHref(): string {
+ return "/tools/digest-context";
+}
+
/** Every tool. */
export function toolsHref(): string {
return "/tools";
diff --git a/umtool/lib/paths.mjs b/umtool/lib/paths.mjs
@@ -155,7 +155,9 @@ export function mediaMirror(abs, { reportsRoot = REPORTS_ROOT, mediaRoot = MEDIA
//
// It does NOT join WRITE_ROOTS, and that is the whole reason the two lists
// exist: the corpus is real production data, and nothing here should be able to
-// render over it.
+// render over it. (The one channel-dir write is the operator's Yes or No on a
+// channel's suggested context note, by its own guarded route:
+// lib/digestContextReview.mjs.)
//
// Same env var the cue reader already uses (lib/projects/report.mjs
// GLOBAL_CHANNELS_DIR, which now returns this one), so a fixture that confines
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -38,6 +38,10 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
// E2E_CLIP_FETCH_GAP_MS set below for the whole run: the gap between two
// network clip fetches in a build (build-video.mjs),
// in place of the real 30–120 s
+// E2E_DIGEST_CONTEXT_PLAN set below on the app server: the plan file the
+// channel context notes' review reads its evidence
+// from (lib/digestContextReview.mjs), a fixture's
+// in place of plans/digest-context-review.md
// E2E_UMTOOL_OPEN_FOLDER_LOG set below on the app server: where the clip
// export's Open folder records what it was asked to
// show, in place of a file manager (lib/report/openFolder.mjs)
@@ -223,6 +227,7 @@ export default defineConfig({
`E2E_UMTOOL_CUT_DELAY_MS=2000 ` +
// Open folder (a clip's export) records the ask instead of opening a file manager.
`E2E_UMTOOL_OPEN_FOLDER_LOG=${FIXTURE}/open-folder.jsonl ` +
+ `E2E_DIGEST_CONTEXT_PLAN=${FIXTURE}/digest-context-review.md ` +
// No background refresh check (R4, lib/inbox/refresh.ts): an Inbox read
// would otherwise enumerate every fixture article's corpus and add cards
// other specs count. refresh.spec runs the check itself, through its route.