commit a06da009e93a34df2c00429de6b2f0ea83b61650
parent 686eb80b4142613db57e19396c0418aeabd0b7e0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 00:54:59 -0500
Merge lane/play-fixes: Play's clock no longer jumps back to the ?at= place (the anchor lets go on the first play or seek); a project lookup that misses on the memoised walk walks again (bench-prep); an edit made while a save re-reads the deck is kept (deck claims and markers); /tools/digest-context, the digest-context review where only the operator's Yes makes a suggested note active
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
26 files changed, 1124 insertions(+), 30 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 list-decimal 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/projects/DeckClaimsEditor.tsx b/umtool/components/projects/DeckClaimsEditor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { DECK_CLAIM_LIMITS, DECK_CLAIM_OPS, DECK_CLAIM_PERS, deckClaimShapeErrors } from "umtool-report-to-video/claims";
@@ -111,17 +111,35 @@ export default function DeckClaimsEditor({
const savedKey = JSON.stringify(claims);
const [rows, setRows] = useState<Row[]>(() => claims.map(rowOf));
const [dirty, setDirty] = useState(false);
+ // Every edit is counted; `saved` is the count the last save was sent at (-1: none is in
+ // hand -- a save refused, or edits never saved). A save re-reads the deck after it writes
+ // (and recomposes the preview: seconds, on a busy machine), and an edit made meanwhile is
+ // the operator's: the saved value arriving after it must not put the old claims back,
+ // nor the save's end mark it saved.
+ const edits = useRef(0);
+ const saved = useRef(0);
useEffect(() => {
+ // The saved value, by its text: a re-read with the same claims keeps the edits; another
+ // value replaces the rows only when it accounts for every edit made (none since the save).
+ if (edits.current !== saved.current) return;
setRows(claims.map(rowOf));
setDirty(false);
- // The saved value, by its text: a re-read with the same claims keeps the edits.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [savedKey]);
const change = (next: Row[]) => {
+ edits.current += 1;
setRows(next);
setDirty(true);
};
+ const onSave = () => {
+ const at = edits.current;
+ saved.current = at;
+ void save(list.length ? list : null).then((ok) => {
+ if (!ok) saved.current = -1;
+ else if (edits.current === at) setDirty(false);
+ });
+ };
const put = (i: number, patch: Partial<CountRow> | Partial<GoalRow>) => change(rows.map((r, j) => (j === i ? ({ ...r, ...patch } as Row) : r)));
const putStep = (i: number, k: number, patch: Partial<Step>) =>
change(rows.map((r, j) => (j === i && r.kind === "goalpost" ? { ...r, steps: r.steps.map((s, m) => (m === k ? { ...s, ...patch } : s)) } : r)));
@@ -197,7 +215,7 @@ export default function DeckClaimsEditor({
type="button"
data-testid="claims-save"
disabled={busy || !dirty || problems.length > 0}
- onClick={() => void save(list.length ? list : null).then((ok) => ok && setDirty(false))}
+ onClick={onSave}
className={`${buttonVariants({ variant: "outline", size: "sm" })} ml-auto`}
>
save claims
diff --git a/umtool/components/projects/MarkersEditor.tsx b/umtool/components/projects/MarkersEditor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { MARKER_LIMITS } from "umtool-report-to-video/marker-limits";
import { buttonVariants } from "@/components/ui/button";
@@ -72,17 +72,34 @@ export default function MarkersEditor({
const [rows, setRows] = useState<Row[]>(() => markers.map(rowOf));
const [layout, setLayout] = useState(markerLayout ?? "");
const [dirty, setDirty] = useState(false);
+ // An edit made while a save re-reads the deck is kept (DeckClaimsEditor.tsx, the same rule):
+ // edits are counted, and the saved value replaces the rows only when it accounts for all of them.
+ const edits = useRef(0);
+ const saved = useRef(0);
useEffect(() => {
+ // The saved value, by its text: a re-read with the same markers keeps the edits.
+ if (edits.current !== saved.current) return;
setRows(markers.map(rowOf));
setLayout(markerLayout ?? "");
setDirty(false);
- // The saved value, by its text: a re-read with the same markers keeps the edits.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [savedKey]);
+ const edited = () => {
+ edits.current += 1;
+ setDirty(true);
+ };
const change = (next: Row[]) => {
setRows(next);
- setDirty(true);
+ edited();
+ };
+ const onSave = () => {
+ const at = edits.current;
+ saved.current = at;
+ void save({ markers: rows.map(markerOf), markerLayout: layout || null }).then((ok) => {
+ if (!ok) saved.current = -1;
+ else if (edits.current === at) setDirty(false);
+ });
};
const put = (i: number, patch: Partial<Row>) => change(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const move = (i: number, d: number) => {
@@ -119,7 +136,7 @@ export default function MarkersEditor({
value={layout}
onChange={(e) => {
setLayout(e.target.value);
- setDirty(true);
+ edited();
}}
className={input}
>
@@ -138,7 +155,7 @@ export default function MarkersEditor({
type="button"
data-testid="markers-save"
disabled={busy || !dirty || labelLong || leadSub >= 0 || rows.some((r) => !r.label.trim() || !r.after)}
- onClick={() => void save({ markers: rows.map(markerOf), markerLayout: layout || null }).then((ok) => ok && setDirty(false))}
+ onClick={onSave}
className={`${buttonVariants({ variant: "outline", size: "sm" })} ml-auto`}
>
save markers
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -364,7 +364,7 @@ export default function PlayCut({
const engine = usePlayEngine({
plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring",
});
- const { ui, rate, failed, seekTo, setPlaying, now } = engine;
+ const { ui, rate, failed, now } = engine;
const setRate = engine.setRate;
// `?clip=&at=` (back from the clip bench): that clip, that far in -- the
@@ -373,7 +373,31 @@ export default function PlayCut({
// placed again (cutAtSource) whenever the plan is re-timed under it: the
// composed schedule replacing the estimate's, the render's edges arriving.
// Let go once both have settled. A card keeps its offset.
+ //
+ // ...and let go the moment the operator takes the transport (plays, seeks,
+ // steps): from then on the place is the playhead's, and the engine carries a
+ // playhead across a re-plan itself (engine.ts setPlan: the same clip, by its
+ // source second). Held on, a plan re-timed under a PLAYING cut -- the render's
+ // edges measured, the deck composed, 12-17 s in on a long cut -- put the
+ // clock back on the place it opened at.
const anchor = useRef<{ clip: string; at: number; src?: number; t?: number } | null>(initialAt);
+ // The anchor's own placing is the engine's seek; every other seek and every play is the operator's.
+ const placeAt = engine.seekTo;
+ const seekTo = useCallback(
+ (t: number) => {
+ anchor.current = null;
+ placeAt(t);
+ },
+ [placeAt],
+ );
+ const enginePlaying = engine.setPlaying;
+ const setPlaying = useCallback(
+ (on: boolean) => {
+ if (on) anchor.current = null;
+ enginePlaying(on);
+ },
+ [enginePlaying],
+ );
// A place set to be found again (back from the bench, after a reorder): the effect below runs
// for it even when the plan did not change.
const [anchorTick, setAnchorTick] = useState(0);
@@ -421,14 +445,14 @@ export default function PlayCut({
// (The offset was taken on the render's clock: turned into a source second once the render's edges are in.)
if (it.clip && a.src === undefined && edges.state !== "measuring") a.src = sourceAt(it, inside(it.from + a.at)) ?? undefined;
const landed = it.clip && a.src !== undefined ? inside(cutAtSource(it, a.src)) : inside(it.from + a.at);
- seekTo(landed);
+ placeAt(landed);
const waiting = awaitView.current > 0 && performance.now() - awaitView.current < 20_000;
if (composeState !== "composing" && edges.state !== "measuring" && !waiting) {
anchor.current = null;
// The cut second it was left at is not where that clip's offset is now: an edit moved it.
if (a.t !== undefined && Math.abs(landed - a.t) > 0.1) setBackToast(`Back at ${a.clip} · ${timecode(landed)} (the cut changed)`);
}
- }, [plan, composeState, edges.state, seekTo, anchorTick]);
+ }, [plan, composeState, edges.state, placeAt, anchorTick]);
// A structural write landed (Reject, its undo): the view and the chrome are read again.
const afterStructure = useCallback(() => {
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 list-disc 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/knobs.md b/umtool/docs/knobs.md
@@ -492,7 +492,8 @@ drawn as a dissolve; the limiter after the loudness gain is not applied; a monta
cuts. A clip whose source window is not on disk is a named placeholder that plays on (silent) — fetch it from the
Cut tab. **Reload the cut** reads an edit made elsewhere, and the edges are measured again for what moved. **Edit this clip** (E) and the bench's **Back to the cut** come back
to the same clip — and the same take — by its id and then by the SOURCE second you left (`?clip=&at=`, the offset turned into a source
-second once the render's edges are in), so an edit that moves the clip's start does not move you off the word. The
+second once the render's edges are in), so an edit that moves the clip's start does not move you off the word — until
+you play or seek: from then the place is the playhead's, and edges or a deck arriving later never put it back. The
bench draws the render's cut over its waveform and, on a phone, on the edge strip (a faint line, and its offset under
each edge).
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/bench-prep.spec.ts b/umtool/e2e/bench-prep.spec.ts
@@ -10,7 +10,8 @@ import * as urls from "./urls";
// clip's first open -- a long recording's excerpt, the waveform -- and the
// bench then opens on the prepared files.
//
-// Its own project, made here and removed after (the suite runs one spec file
+// Its own project, made here -- by the test, a moment after the server walked
+// the reports without it -- and removed after (the suite runs one spec file
// at a time, so no other spec's project count sees it): r01 sits on a
// "recording", a cached window whose NAME says 0–700 s (longer than the
// bench's EXCERPT_OVER_S, so the bench is given an excerpt of it), and r02 on
@@ -24,7 +25,14 @@ const DIR = path.join(FIXTURE, "reports", "prep-fixture");
const TONE = path.join(FIXTURE, "reports", "report-fixture", "out", "clips-raw", "vid1_0.00-9.00.mp4");
const EXCERPT = path.join(DIR, "out", "bench-excerpts", "vidp", "0.00-60.00.excerpt.mp4");
-test.beforeAll(() => {
+/**
+ * The project, on disk. Made INSIDE the test, after the server has walked the
+ * reports without it: whatever an earlier spec asked a moment ago (the walk is
+ * memoised for a second, lib/projects.ts), a project made on disk is found
+ * the moment it is asked for -- in a full run the spec before this one used to
+ * leave a walk that did not have it, and the Cut tab 404'd.
+ */
+function makeProject() {
rmSync(DIR, { recursive: true, force: true });
mkdirSync(path.join(DIR, "out", "clips-raw"), { recursive: true });
const clip = (id: string, video: string) => ({ type: "clip", id, video, start: 3, end: 6, cite: 3, section: 0, lock: true, quote: "and because" });
@@ -34,6 +42,10 @@ test.beforeAll(() => {
);
copyFileSync(TONE, path.join(DIR, "out", "clips-raw", "vidp_0.00-700.00.mp4"));
copyFileSync(TONE, path.join(DIR, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+}
+
+test.beforeAll(() => {
+ rmSync(DIR, { recursive: true, force: true });
});
test.afterAll(() => {
@@ -41,6 +53,10 @@ test.afterAll(() => {
});
test("Prepare clips for the walk makes the excerpt and the waveforms, and the bench opens on them", async ({ page, request }) => {
+ // The server walks the reports now, and finds no such project...
+ expect((await request.get(`/api/report/prep?project=${encodeURIComponent(PROJECT)}`)).status()).toBe(404);
+ // ...which is made a moment later, and opened at once.
+ makeProject();
await page.goto(urls.section(PROJECT, "timeline"));
const panel = page.locator("[data-bench-prep]");
await expect(panel.locator("[data-bench-prep-status]")).toHaveText("0 of 2 ready to open · 2 to prepare");
diff --git a/umtool/e2e/deck-claims.spec.ts b/umtool/e2e/deck-claims.spec.ts
@@ -110,12 +110,31 @@ test("the claims editor: a count and a goalpost -- validated as typed, the playh
await page.getByTestId("claim-per-0").selectOption("P1W");
await page.getByTestId("claim-remove-0").click();
await page.getByTestId("claim-step-remove-0-0").click();
+ // The save's re-read of the deck (GET /api/report/chrome) held until the next edit is made:
+ // the file is written at once, and an edit made while the editor reads it back is the
+ // operator's -- the saved value arriving after it must not put the old claims back, nor
+ // the save's end mark it saved. (Under a loaded machine the re-read and the recompose
+ // after it are seconds; an edit there used to be lost and Save stay disabled.)
+ let release!: () => void;
+ const reread = new Promise<void>((r) => (release = r));
+ await page.route(
+ (u) => u.pathname === "/api/report/chrome",
+ async (route) => {
+ if (route.request().method() === "GET") await reread;
+ await route.continue();
+ },
+ );
await page.getByTestId("claims-save").click();
await expect.poll(() => claims()).toEqual([
{ kind: "goalpost", label: "Pill test results", steps: [{ at: "c02", t: 10, said: "“6–8 weeks”", from: "2026-10-15", due: ["P6W", "P8W"] }] },
]);
- // Removing the last claim removes the key.
+ // Removing the last claim removes the key -- removed while the save is still reading back.
await page.getByTestId("claim-remove-0").click();
- await page.getByTestId("claims-save").click();
+ release();
+ await expect(page.getByTestId("onscreen-note")).toHaveText("saved 1 claim check", { timeout: 30_000 });
+ // The edit stands: no claim left, unsaved.
+ await expect(ed).toContainText(/(^|\D)0 of \d/);
+ await expect(ed).toContainText("unsaved");
+ await page.getByTestId("claims-save").click({ timeout: 15_000 });
await expect.poll(() => readManifest().render.chrome?.deck && "claims" in readManifest().render.chrome!.deck!).toBe(false);
});
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";
@@ -2255,6 +2256,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/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts
@@ -238,3 +238,51 @@ test("a take plays its own timeline (its patch over the project's manifest); a r
await page.locator('[data-play-row="c02"]').press("Enter");
expect(await tNow(page)).toBeCloseTo(2.133, 2);
});
+
+test("opened at ?clip=&at=, the clock never jumps back there when the render's edges and the deck arrive while it plays", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ // The late data, held until the clock has run on from the place: the render's edges
+ // (cut-points, 12-17 s on a long real cut) and the composed deck (the chrome preview).
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const held: string[] = [];
+ for (const late of ["/api/report/cut-points", "/api/report/chrome/preview"]) {
+ await page.route((u) => u.pathname === late, async (route) => {
+ held.push(new URL(route.request().url()).pathname);
+ await gate;
+ await route.continue();
+ });
+ }
+ await page.goto(urls.playHref(PROJECT, { clip: "c01", at: 0.3 }));
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(root(page)).toHaveAttribute("data-play-edges", "measuring");
+ await expect.poll(() => tNow(page)).toBeCloseTo(0.3, 2);
+ // Every frame's clock, read off the engine itself (not the attribute React renders).
+ await page.evaluate(() => {
+ const w = window as Window & { __umtoolPlayEngine?: { now(): number; playing: boolean }; __clock?: number[] };
+ w.__clock = [];
+ const loop = () => {
+ const e = w.__umtoolPlayEngine;
+ if (e?.playing) w.__clock!.push(e.now());
+ requestAnimationFrame(loop);
+ };
+ requestAnimationFrame(loop);
+ });
+ await page.locator("[data-play-toggle]").click();
+ await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(1.3);
+ expect(held).toEqual(expect.arrayContaining(["/api/report/cut-points", "/api/report/chrome/preview"]));
+ release();
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ // On past the re-plan: the clock goes on from where it was.
+ const at = await tNow(page);
+ await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(at + 0.8);
+ await page.screenshot({ path: test.info().outputPath("play-at-no-jump.png") });
+ await page.keyboard.press("k");
+ const clock = await page.evaluate(() => (window as Window & { __clock?: number[] }).__clock ?? []);
+ expect(clock.length).toBeGreaterThan(30);
+ // The render's edges re-time the plan under the playhead (the same source second, a few
+ // frames either way); a jump back to the place it opened at is a second and more.
+ const back = clock.slice(1).map((t, i) => clock[i] - t);
+ expect(Math.max(...back), `the clock went back: ${JSON.stringify(clock.map((t) => Math.round(t * 100) / 100))}`).toBeLessThan(0.25);
+ expect(Math.min(...clock.slice(clock.length >> 1))).toBeGreaterThan(1.3);
+});
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/lib/projects.ts b/umtool/lib/projects.ts
@@ -113,6 +113,22 @@ export async function projectRefs(): Promise<ProjectRef[]> {
}
/**
+ * A lookup over the walk that walks again when it misses on a MEMOISED walk: a
+ * project made on disk a moment ago (the CLI's scaffold, an agent, a spec) is
+ * found the first time it is asked for, not up to a second later -- the memo
+ * answered "no such project" for it, and its page 404'd (bench-prep.spec.ts,
+ * in a full run, behind a spec whose last request had just walked). A miss on
+ * a fresh walk is final, so a wrong address costs one walk, never a loop.
+ */
+async function lookUp<T>(find: (refs: ProjectRef[]) => T | null): Promise<T | null> {
+ const memo = !!CACHES.walk && Date.now() - CACHES.walk.at < 1000;
+ const got = find(await projectRefs());
+ if (got !== null || !memo) return got;
+ CACHES.walk = null;
+ return find(await projectRefs());
+}
+
+/**
* What `pruneIndex` would drop, read only (Settings · system's plan, P5): the
* index's records for projects the walk no longer finds, against a fresh walk.
*/
@@ -143,7 +159,7 @@ export async function pruneIndex(): Promise<number> {
}
export async function projectRef(id: string): Promise<ProjectRef | null> {
- return (await projectRefs()).find((p) => p.id === id) ?? null;
+ return lookUp((refs) => refs.find((p) => p.id === id) ?? null);
}
type KindSummary = {
@@ -375,20 +391,25 @@ export type Resolved =
* path, and `a/b` being a project must not stop `a/b/c` from being one too.
*/
export async function resolveProjectPath(segments: string[]): Promise<Resolved> {
- const refs = await projectRefs();
const id = segments.join("/");
- let best: ProjectRef | null = null;
- for (const p of refs) {
- if (p.routing !== "ok") continue;
- if (id === p.id || id.startsWith(`${p.id}/`)) {
- if (!best || p.id.length > best.id.length) best = p;
+ const longest = (refs: ProjectRef[]) => {
+ let best: ProjectRef | null = null;
+ for (const p of refs) {
+ if (p.routing !== "ok") continue;
+ if (id === p.id || id.startsWith(`${p.id}/`)) {
+ if (!best || p.id.length > best.id.length) best = p;
+ }
}
- }
+ return best;
+ };
+ const best = await lookUp(longest);
if (best) {
const rest = id === best.id ? [] : id.slice(best.id.length + 1).split("/");
return { project: best, rest, folder: null };
}
+ // (The walk the miss above made: memoised now, so the folders and the alias read the same one.)
+ const refs = await projectRefs();
const folders = await listFolders();
const folder = folders.get(id);
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.