commit 92d28a8e8f93d367973ca9136e3a49036a84f5e4
parent 48b14021ce99f08f6b7ecb07450914c83cfb5d7c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 11:28:04 -0400
Merge r27/checks-tools: release 27 S2 (checks, op engines), S3 (tools), S3b (research tools)
# Conflicts:
# editor/CHANGELOG.md
# plans/release-27.md
Diffstat:
54 files changed, 4880 insertions(+), 9 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -130,6 +130,11 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | |
| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | |
| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` |
+| `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -> {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` |
+| `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` |
+| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
+| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
+| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
### Usage, flags and environment
diff --git a/common/bin/reports-check.test.ts b/common/bin/reports-check.test.ts
@@ -30,6 +30,8 @@ const { getPaths } = await import("../lib/paths");
const { checkMain, verifyQuotesMain } = await import("./reports-check");
const { attachVideoMain } = await import("./reports-attach-video");
const { encodePlan, encodeArgs } = await import("../publish/reportVideo");
+const { CHANNELS } = await import("../testing/draft/corpus.mjs");
+const { convertFixture } = await import("../testing/draft/derive");
const paths = getPaths();
const CHAN = "chan";
@@ -191,6 +193,62 @@ test("verify-quotes: a clean report exits 0, in words", async () => {
assert.match(c.text(), /1 quote\(s\): 1 ok/);
});
+test("verify-quotes: `inexact` — recall passes, the strict check does not — is a warning (testing/draft/sweeps/inexact.md)", async () => {
+ // The synthetic kitchen channel, its records as served `en` tracks.
+ writeJson(path.join(paths.channelsDir, "synth-kitchen", "config.json"), {
+ handling: "youtube",
+ name: "Synth Kitchen",
+ url: "https://video.example/@synth-kitchen",
+ });
+ const kitchen = CHANNELS.find((ch) => ch.slug === "synth-kitchen")!;
+ for (const r of kitchen.records) {
+ const dir = path.join(paths.channelsDir, "synth-kitchen", "data", r.id);
+ writeJson(path.join(dir, "metadata.info.json"), {
+ id: r.id,
+ title: r.title,
+ channel: r.channel,
+ upload_date: r.uploadDate,
+ duration: r.duration,
+ webpage_url: r.webpageUrl,
+ extractor_key: "Youtube",
+ });
+ writeText(path.join(dir, "transcript.en.vtt"), vtt(r.cues.map((q) => [q.start, q.end, q.text])));
+ }
+ const { report } = await convertFixture("inexact");
+ const file = path.join(ROOT, "inexact.report.json");
+ writeJson(file, report);
+
+ const c = capture();
+ const code = await verifyQuotesMain({ file, json: true, paths }, c.out);
+ const { results } = JSON.parse(c.text()) as {
+ results: { citation: string; status: string; score?: number; strict?: { ok: boolean; failed?: string } }[];
+ };
+ const by = Object.fromEntries(results.map((r) => [r.citation, r]));
+ // Reversed: every token is in the cue, so recall passes at 1 — but the
+ // words are not what was said.
+ assert.equal(by.c01.status, "inexact");
+ assert.equal(by.c01.score, 1);
+ assert.deepEqual(by.c01.strict, { ok: false, failed: "I would sell the bakery to a chain" });
+ // Two hundred seconds from its link: recall fails it already (its ±5 s
+ // window shares only "the"), so it is a drift, the stronger status.
+ assert.equal(by.c02.status, "drift");
+ assert.equal(by.c02.strict, undefined);
+ // Exact.
+ assert.equal(by.c03.status, "ok");
+ assert.deepEqual(by.c03.strict, { ok: true });
+ assert.equal(code, 1, "the drift fails it; the inexact alone would not");
+
+ // Without the drift, an inexact quote is a warning: exit 0, in words.
+ const warnOnly = { ...report, citations: { c01: report.citations!.c01, c03: report.citations!.c03 } };
+ warnOnly.sections = [{ id: "s", title: "S", body: "Said [this](cite:c01) and [that](cite:c03)." }];
+ writeJson(file, warnOnly);
+ const w = capture();
+ assert.equal(await verifyQuotesMain({ file, paths }, w.out), 0);
+ assert.match(w.text(), /INEXACT \(warning\) c01 {2}video synth-kitchen\/bread-day-01 15–19\.8 s {2}1\.00 transcript\.en\.vtt/);
+ assert.match(w.text(), /"I would sell the bakery to a chain" is not verbatim within ±90 s/);
+ assert.match(w.text(), /2 quote\(s\): 1 inexact, 1 ok \(inexact is a warning\)/);
+});
+
// ─── attach-video ───
test("encodePlan: remux an H.264 mp4 under the limit; encode the rest to fit; refuse what cannot", () => {
diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts
@@ -19,6 +19,12 @@
// `en-orig` is not what the speaker said, and is reported as such, even
// though compose (which takes the best track) would pass it.
//
+// A quote that passes compose's recall check but is not VERBATIM within
+// ±90 s of its second (the strict check, lib/citations/verify.ts
+// strictQuoteCheck — release 27 D3) is `inexact`: a WARNING. It is printed
+// and counted, and does not change the exit code; compose and publish do not
+// use it.
+//
// `--article <id>` checks one ARTICLE (release 26: transcripts/reports/<id>/,
// published or a draft) as the homepage's compose would — any channel of the
// corpus citable, the articles' prepared media.
@@ -36,7 +42,15 @@ import { readAllPosts } from "../lib/posts-server";
import { parseReport } from "../lib/report/validate";
import type { Report } from "../lib/report/schema";
import { reportCitationNumbers } from "../lib/report/uses";
-import { QUOTE_DRIFT_THRESHOLD, quoteDrifted, quoteVerification, roundScore } from "../lib/citations/verify";
+import {
+ QUOTE_DRIFT_THRESHOLD,
+ quoteDrifted,
+ quoteVerification,
+ roundScore,
+ strictQuoteCheck,
+ strictTextCheck,
+ type StrictQuoteResult,
+} from "../lib/citations/verify";
import {
ComposeReportsError,
checkSpanQuote,
@@ -126,6 +140,8 @@ export type QuoteStatus =
| "ok"
| "drift"
| "en-orig-drift"
+ // Recall passes, the strict check does not: a warning (release 27 D3).
+ | "inexact"
| "missing-record"
| "no-cues"
| "missing-post"
@@ -146,9 +162,25 @@ export type QuoteResult = {
// Every track's score; and the en-orig track's, when the record has one.
tracks?: { name: string; score: number }[];
enOrig?: number;
+ // The strict check (verbatim within ±90 s): whether it passed, and the
+ // first fragment it did not find. Absent where recall already failed.
+ strict?: { ok: boolean; failed?: string };
message?: string;
};
+// Statuses that are warnings: printed and counted, never a failure.
+export const QUOTE_WARNING_STATUSES: ReadonlySet<QuoteStatus> = new Set<QuoteStatus>(["inexact"]);
+
+const strictOf = (r: StrictQuoteResult): NonNullable<QuoteResult["strict"]> =>
+ r.ok ? { ok: true } : { ok: false, ...(r.failed !== undefined ? { failed: r.failed } : {}) };
+
+export function inexactMessage(failed: string | undefined): string {
+ return (
+ `recall passes, but ${failed ? `"${failed.slice(0, 120)}"` : "the quote"} is not verbatim within ±90 s ` +
+ `of the cited second (the strict check generated quotes must pass) — a warning; compose is unchanged`
+ );
+}
+
export const EN_ORIG_TRACK = "transcript.en-orig.vtt";
// Every video, audio and post citation of a report, checked against the
@@ -200,12 +232,19 @@ export async function verifyReportQuotes(
continue;
}
const v = quoteVerification(c.quote, postText, now);
+ const strict = quoteDrifted(v) ? null : strictTextCheck(c.quote, postText);
+ const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : "ok";
results.push({
...base,
score: v.quoteScore,
track: "post",
- status: quoteDrifted(v) ? "drift" : "ok",
- ...(quoteDrifted(v) ? { message: quoteDriftMessage(v.quoteScore) } : {}),
+ status,
+ ...(strict ? { strict: strictOf(strict) } : {}),
+ ...(status === "drift"
+ ? { message: quoteDriftMessage(v.quoteScore) }
+ : status === "inexact"
+ ? { message: inexactMessage(strict?.failed) }
+ : {}),
});
continue;
}
@@ -227,6 +266,17 @@ export async function verifyReportQuotes(
const enOrig = checked.tracks.find((t) => t.name === EN_ORIG_TRACK)?.score;
let status: QuoteStatus = "ok";
let message: string | undefined;
+ // The strict check passes when any track has the quote verbatim near
+ // the cited second (as recall takes the best track).
+ let strict: StrictQuoteResult | null = null;
+ if (!quoteDrifted(checked.verification)) {
+ const tracks = record.tracks.length ? record.tracks.map((t) => t.cues) : [record.cues];
+ for (const cues of tracks) {
+ const r = strictQuoteCheck(c.quote, cues, c.start);
+ if (!strict || r.ok) strict = r;
+ if (r.ok) break;
+ }
+ }
if (quoteDrifted(checked.verification)) {
status = "drift";
message = quoteDriftMessage(score);
@@ -235,6 +285,9 @@ export async function verifyReportQuotes(
message =
`the quote matches ${best?.name ?? "a track"} (${score.toFixed(2)}) but only ${Math.round(enOrig * 100)}% of ` +
`the en-orig track, the words as spoken — a served \`en\` track can rewrite them: quote en-orig, or check the audio`;
+ } else if (strict && !strict.ok) {
+ status = "inexact";
+ message = inexactMessage(strict.failed);
}
results.push({
...base,
@@ -242,6 +295,7 @@ export async function verifyReportQuotes(
...(best ? { track: best.name } : {}),
tracks: checked.tracks,
...(enOrig !== undefined ? { enOrig } : {}),
+ ...(strict ? { strict: strictOf(strict) } : {}),
status,
...(message ? { message } : {}),
});
@@ -253,7 +307,7 @@ function describe(r: QuoteResult): string {
const where = r.kind === "post" ? `${r.channel}/${r.id}` : `${r.channel}/${r.id} ${r.start}–${r.end} s`;
const score = r.score === undefined ? "" : ` ${r.score.toFixed(2)}${r.track ? ` ${r.track}` : ""}`;
const orig = r.enOrig === undefined || r.track === EN_ORIG_TRACK ? "" : ` · en-orig ${r.enOrig.toFixed(2)}`;
- const label = r.status === "ok" ? "ok" : r.status.toUpperCase();
+ const label = r.status === "ok" ? "ok" : QUOTE_WARNING_STATUSES.has(r.status) ? `${r.status.toUpperCase()} (warning)` : r.status.toUpperCase();
return ` ${label.padEnd(14)} ${r.citation}${r.cited ? "" : " (not cited)"} ${r.kind} ${where}${score}${orig}` +
(r.message ? `\n${" ".repeat(17)}${r.message}` : "");
}
@@ -277,18 +331,19 @@ export async function verifyQuotesMain(
return 1;
}
const results = await verifyReportQuotes(parsed.value, { paths, ...(opts.now ? { now: opts.now } : {}) });
- const bad = results.filter((r) => r.status !== "ok");
+ const bad = results.filter((r) => r.status !== "ok" && !QUOTE_WARNING_STATUSES.has(r.status));
if (opts.json) {
out.log(JSON.stringify({ file: opts.file, problems: parsed.problems, results }, null, 2));
} else {
for (const p of parsed.problems) out.error(` invalid: ${p.path}: ${p.message}`);
- for (const r of results) (r.status === "ok" ? out.log : out.error)(describe(r));
+ for (const r of results) (r.status === "ok" || QUOTE_WARNING_STATUSES.has(r.status) ? out.log : out.error)(describe(r));
const counts = new Map<QuoteStatus, number>();
for (const r of results) counts.set(r.status, (counts.get(r.status) ?? 0) + 1);
out.log(
`reports verify-quotes: ${results.length} quote(s): ` +
[...counts].map(([s, n]) => `${n} ${s}`).join(", ") +
- (parsed.problems.length ? `; ${parsed.problems.length} validation problem(s)` : ""),
+ (parsed.problems.length ? `; ${parsed.problems.length} validation problem(s)` : "") +
+ (results.some((r) => QUOTE_WARNING_STATUSES.has(r.status)) ? " (inexact is a warning)" : ""),
);
}
return bad.length > 0 || parsed.problems.length > 0 ? 1 : 0;
diff --git a/common/controller/archiveOrgImport.ts b/common/controller/archiveOrgImport.ts
@@ -43,6 +43,7 @@ import type { Paths } from "../lib/paths";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
import {
listArchiveOrgMediaFiles,
+ parseArchiveOrgLength,
pickArchiveOrgFiles,
type ArchiveOrgFileSelection,
type ArchiveOrgItemMetadata,
@@ -267,6 +268,87 @@ export async function searchArchiveOrgItems(
return { found, items };
}
+// ─── One item, described (release 27 S3b: a research run's read) ───
+
+export type ArchiveOrgItemSummary = {
+ identifier: string;
+ url: string;
+ title?: string;
+ date?: string;
+ mediatype?: string;
+ creator?: string;
+ collections: string[];
+ // archive.org restricts the whole item (every download answers 401/403).
+ restricted: boolean;
+ // The media originals (what an import takes, one record each), their
+ // total size, and every file with what the metadata says about it.
+ mediaFiles: number;
+ mediaBytes: number;
+ files: {
+ name: string;
+ format?: string;
+ source?: string;
+ size?: number;
+ seconds?: number;
+ media: boolean;
+ restricted: boolean;
+ original?: string;
+ }[];
+};
+
+const firstOf = (v: unknown): string | undefined =>
+ typeof v === "string" ? v.trim() || undefined : Array.isArray(v) ? v.find((x): x is string => typeof x === "string" && !!x.trim()) : undefined;
+
+// What one item holds, read off its metadata (one request through the polite
+// client, cached): its files with their sizes, formats and lengths, which are
+// the media originals an import would take, and what archive.org restricts.
+// Nothing is downloaded.
+export async function describeArchiveOrgItem(
+ identifier: string,
+ opts: { client?: ArchiveOrgClient; signal?: AbortSignal } = {},
+): Promise<ArchiveOrgItemSummary> {
+ const client = opts.client ?? archiveOrgClient;
+ const item = await client.itemMetadata(identifier, opts.signal);
+ const restriction = archiveOrgRestriction(item);
+ const media = new Set(listArchiveOrgMediaFiles(item).map((f) => f.name));
+ const sizeOf = (v: string | undefined) => (v && /^\d+$/.test(v) ? Number(v) : undefined);
+ const files = item.files.map((f) => {
+ const size = sizeOf(f.size);
+ const seconds = parseArchiveOrgLength(f.length);
+ return {
+ name: f.name,
+ ...(f.format ? { format: f.format } : {}),
+ ...(f.source ? { source: f.source } : {}),
+ ...(size !== undefined ? { size } : {}),
+ ...(seconds !== undefined ? { seconds } : {}),
+ media: media.has(f.name),
+ restricted: restriction.files.has(f.name),
+ ...(f.original ? { original: f.original } : {}),
+ };
+ });
+ const meta = item.metadata as Record<string, unknown>;
+ const collections = (Array.isArray(meta.collection) ? meta.collection : [meta.collection]).filter(
+ (c): c is string => typeof c === "string" && !!c,
+ );
+ const title = firstOf(meta.title);
+ const date = firstOf(meta.date);
+ const mediatype = firstOf(meta.mediatype);
+ const creator = firstOf(meta.creator);
+ return {
+ identifier: item.metadata.identifier,
+ url: archiveOrgDetailsUrl({ identifier: item.metadata.identifier }),
+ ...(title ? { title } : {}),
+ ...(date ? { date } : {}),
+ ...(mediatype ? { mediatype } : {}),
+ ...(creator ? { creator } : {}),
+ collections,
+ restricted: restriction.item,
+ mediaFiles: media.size,
+ mediaBytes: files.filter((f) => f.media).reduce((n, f) => n + (f.size ?? 0), 0),
+ files,
+ };
+}
+
// The gap before the next file: the configured pause, floored, plus up to
// half again at random so a batch never settles into a fixed beat.
export function archiveOrgGapMs(sleepBetweenDownloadsSeconds: number, random: number): number {
diff --git a/common/controller/archiveOrgResearch.test.ts b/common/controller/archiveOrgResearch.test.ts
@@ -0,0 +1,78 @@
+// archive.org reads for a research run (release 27 S3b), against the test
+// kit's fake archive.org through the real polite client: the search, one
+// item's file list, its pace and its back-off.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { startFakeArchiveOrg, type FakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs";
+import { ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { describeArchiveOrgItem, searchArchiveOrgItems } from "./archiveOrgImport";
+
+let ia: FakeArchiveOrg;
+before(async () => {
+ ia = await startFakeArchiveOrg();
+});
+after(() => ia.close());
+
+function client(f: (url: string, init: RequestInit) => Promise<Response> = ia.fetch) {
+ let now = 0;
+ const sleeps: number[] = [];
+ const c = new ArchiveOrgClient(
+ {
+ fetch: f,
+ now: () => now,
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ now += ms;
+ },
+ random: () => 0.5,
+ },
+ {},
+ );
+ return { c, sleeps };
+}
+
+test("search: identifiers and titles, in identifier order, paced 2 s apart", async () => {
+ const { c, sleeps } = client();
+ const r = await searchArchiveOrgItems("bakery", { client: c, rows: 10 });
+ assert.equal(r.found, 2);
+ assert.deepEqual(r.items, [
+ { identifier: "synth-kitchen-episodes-2026", title: "Synth Kitchen — episodes, spring 2026" },
+ { identifier: "synth-radio-tape-01", title: "Synth radio — the bakery call-in" },
+ ]);
+ await searchArchiveOrgItems("members", { client: c });
+ assert.deepEqual(sleeps, [2000]);
+ assert.match(ia.requests[0]!, /^\/advancedsearch\.php\?q=bakery&fl%5B%5D=identifier/);
+});
+
+test("an item described: its files, sizes, lengths, which are the media originals, and what is restricted", async () => {
+ const { c } = client();
+ const d = await describeArchiveOrgItem("synth-kitchen-episodes-2026", { client: c });
+ assert.equal(d.url, "https://archive.org/details/synth-kitchen-episodes-2026");
+ assert.equal(d.title, "Synth Kitchen — episodes, spring 2026");
+ assert.deepEqual(d.collections, ["opensource_movies"]);
+ assert.equal(d.restricted, false);
+ assert.equal(d.mediaFiles, 2);
+ assert.equal(d.mediaBytes, 104857600 + 209715200);
+ const byName = Object.fromEntries(d.files.map((f) => [f.name, f]));
+ assert.deepEqual(byName["Bread day.mp4"], { name: "Bread day.mp4", format: "MPEG4", source: "original", size: 104857600, seconds: 70, media: true, restricted: false });
+ assert.equal(byName["Pie stream.mkv"]!.seconds, 120);
+ assert.equal(byName["Pie stream.mp4"]!.media, false, "a derivative is the same recording");
+ assert.equal(byName["Pie stream.mp4"]!.original, "Pie stream.mkv");
+ const r = await describeArchiveOrgItem("synth-kitchen-restricted", { client: c });
+ assert.equal(r.restricted, true);
+ assert.equal(r.files[0]!.restricted, true);
+ await assert.rejects(describeArchiveOrgItem("no-such-item", { client: c }));
+});
+
+test("a 429 backs off (Retry-After) and the read goes through", async () => {
+ const busy = await startFakeArchiveOrg({ busyTimes: 1 });
+ try {
+ const { c, sleeps } = client(busy.fetch);
+ const r = await searchArchiveOrgItems("radio", { client: c });
+ assert.equal(r.items[0]!.identifier, "synth-radio-tape-01");
+ assert.deepEqual(sleeps, [1000, 1000], "Retry-After: 1, then the rest of the 2 s gap");
+ } finally {
+ await busy.close();
+ }
+});
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -580,6 +580,18 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "platform",
},
+ // ONE post by its URL into a posts channel of its platform (release 27 S3b,
+ // social/importPost.ts): one read through the channel's fetcher. On the
+ // PLATFORM queue, like fetch-posts, so it serialises with a fetch of the same
+ // source and shares its backoff. Not drainable (one read); not replayable
+ // (a second import of the same post reads nothing anyway).
+ "import-post": {
+ kind: "import-post",
+ label: "Import one post",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ },
// A screenshot and the attached media of specific archived posts (and the X
// Article a post links to), into the channel's `posts-media/`
// (controller/capturePosts.ts). On the PLATFORM queue, like fetch-posts:
@@ -1076,6 +1088,7 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"persist-kept",
"fetch-posts",
"import-forum-pages",
+ "import-post",
"capture-posts",
"check-post-availability",
"sync",
diff --git a/common/lib/citations/verify.test.ts b/common/lib/citations/verify.test.ts
@@ -8,7 +8,13 @@ import {
quoteTokens,
quoteVerification,
tokenRecall,
+ STRICT_QUOTE_WINDOW_SECONDS,
+ quoteFragments,
+ strictNormalize,
+ strictQuoteCheck,
+ strictTextCheck,
} from "./verify";
+import { cuesOf } from "../../testing/draft/corpus.mjs";
test("tokens: lowercased, punctuation stripped, split on whitespace", () => {
assert.deepEqual(quoteTokens("Don't stop — the U.S. bridge, OK?"), ["dont", "stop", "the", "us", "bridge", "ok"]);
@@ -47,3 +53,64 @@ test("the block: rounded score, the time, the method; drift below the threshold"
assert.equal(quoteDrifted({}), true);
assert.ok(!("voiceChecked" in v), "a voice is never vouched for");
});
+
+// ─── the strict check (release 27 D3) ───
+
+test("strict normalisation: case, punctuation, whitespace, curly quotes and apostrophes", () => {
+ assert.equal(strictNormalize(" Don’t STOP — the “U.S.” bridge,\nOK?"), "dont stop the u s bridge ok");
+ assert.equal(strictNormalize("don't"), strictNormalize("Don’t"));
+});
+
+test("strict fragments: split on the ellipsis convertSweep joins with", () => {
+ assert.deepEqual(quoteFragments("a lot of you asked … I did not enter"), ["a lot of you asked", "I did not enter"]);
+ assert.deepEqual(quoteFragments("one... two"), ["one", "two"]);
+ assert.deepEqual(quoteFragments(" … "), []);
+});
+
+test("strict: a reversed quote recall passes is refused; the exact one passes", async () => {
+ const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!;
+ // Recall passes it — every token of the reversed quote is in the cue.
+ assert.equal(tokenRecall("I would sell the bakery to a chain", cueWindowText(cues, 15, 19.8)), 1);
+ const reversed = strictQuoteCheck("I would sell the bakery to a chain", cues, 15);
+ assert.equal(reversed.ok, false);
+ assert.equal(reversed.failed, "I would sell the bakery to a chain");
+ assert.equal(strictQuoteCheck("I would never sell the bakery to a chain", cues, 15).ok, true);
+ // Case, punctuation and curly quotes do not matter.
+ assert.equal(strictQuoteCheck("I WOULD never sell the bakery, to a chain!", cues, 15).ok, true);
+});
+
+test("strict: every fragment must be found; a quote spanning two cues passes", async () => {
+ const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!;
+ const two = strictQuoteCheck("we never said that about the old oven … the oven was fine it just ran hot", cues, 25);
+ assert.equal(two.ok, true);
+ assert.deepEqual(two.fragments.map((f) => f.ok), [true, true]);
+ const across = strictQuoteCheck("about the old oven the oven was fine", cues, 25);
+ assert.equal(across.ok, true);
+ const oneBad = strictQuoteCheck("we never said that about the old oven … the oven was broken", cues, 25);
+ assert.equal(oneBad.ok, false);
+ assert.equal(oneBad.failed, "the oven was broken");
+});
+
+test("strict: on word boundaries — a fragment inside a longer word does not pass", async () => {
+ const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!;
+ assert.equal(strictQuoteCheck("he oven", cues, 25).ok, false);
+ assert.equal(strictQuoteCheck("the oven", cues, 25).ok, true);
+});
+
+test("strict: within ±90 s of the cited second, and no further", async () => {
+ const cues = (await cuesOf("synth-kitchen", "qa-long-03"))!;
+ const q = "we opened the second shop in the spring"; // said at 205 s
+ assert.equal(STRICT_QUOTE_WINDOW_SECONDS, 90);
+ assert.equal(strictQuoteCheck(q, cues, 205).ok, true);
+ assert.equal(strictQuoteCheck(q, cues, 120).ok, true);
+ assert.equal(strictQuoteCheck(q, cues, 5).ok, false, "two hundred seconds from its link");
+ assert.equal(strictQuoteCheck(q, cues, 100).ok, false);
+ assert.equal(strictQuoteCheck(q, cues, 5, { windowSeconds: 300 }).ok, true);
+});
+
+test("strict: an empty quote never passes; a post is checked against its text", () => {
+ assert.equal(strictTextCheck("", "anything").ok, false);
+ const post = "No, I did not enter the pie contest. The judges are my friends.";
+ assert.equal(strictTextCheck("No, I did not enter the pie contest.", post).ok, true);
+ assert.equal(strictTextCheck("I did enter the pie contest", post).ok, false);
+});
diff --git a/common/lib/citations/verify.ts b/common/lib/citations/verify.ts
@@ -95,3 +95,103 @@ export function quoteVerification(quote: string, text: string, checkedAt: string
export function quoteDrifted(v: Pick<CitationVerification, "quoteScore">): boolean {
return (v.quoteScore ?? 0) < QUOTE_DRIFT_THRESHOLD;
}
+
+// ─── the STRICT check (release 27, D3) ───
+//
+// Token recall passes a quote whose meaning is reversed: "I would sell" scores
+// 1.0 against a record that says "I would never sell", and a quote with two
+// words reversed in meaning passed at 0.85. A GENERATED quote is held to
+// more: every quoted fragment — the fragments convertSweep joins with an
+// ellipsis — must be in the record's text VERBATIM after normalisation
+// (strictNormalize: case, punctuation, whitespace, curly quotes), within
+// ±STRICT_QUOTE_WINDOW_SECONDS of the cited second, on word boundaries.
+//
+// verify-quotes reports a quote that passes recall and fails this as
+// `inexact` — a WARNING for existing reports; compose and publish do not use
+// it (release 27 D3). The generation tasks refuse a quote that fails it.
+
+export const STRICT_QUOTE_WINDOW_SECONDS = 90;
+
+export const STRICT_QUOTE_METHOD =
+ "strict v1: every fragment verbatim (case, punctuation, whitespace and curly quotes normalised) within ±90 s of the cited second";
+
+// The text both sides are compared as: NFKC, lowercased, curly quotes made
+// straight, apostrophes removed ("don't" is "dont"), every other character
+// that is not a letter, a digit or whitespace made a space, whitespace
+// collapsed.
+export function strictNormalize(text: string): string {
+ return text
+ .normalize("NFKC")
+ .toLowerCase()
+ .replace(/[‘’ʼ]/g, "'")
+ .replace(/[“”]/g, '"')
+ .replace(/[^\p{L}\p{N}\s']/gu, " ")
+ .replace(/'/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+// A quote's fragments: split on the ellipsis convertSweep joins quoted runs
+// with (`…`, or three dots), blanks dropped.
+export function quoteFragments(quote: string): string[] {
+ return quote
+ .split(/…|\.\.\./)
+ .map((f) => f.trim())
+ .filter((f) => strictNormalize(f).length > 0);
+}
+
+export type StrictFragmentResult = { fragment: string; ok: boolean };
+
+export type StrictQuoteResult = {
+ // Every fragment found; false for a quote with no words.
+ ok: boolean;
+ fragments: StrictFragmentResult[];
+ // The first fragment that was not found, as quoted.
+ failed?: string;
+ method: string;
+};
+
+// Whether `needle` occurs in `hay` on word boundaries (both normalised).
+function containsWords(hay: string, needle: string): boolean {
+ return needle.length > 0 && ` ${hay} `.includes(` ${needle} `);
+}
+
+function strictAgainst(quote: string, text: string): StrictQuoteResult {
+ const hay = strictNormalize(text);
+ const fragments = quoteFragments(quote).map((fragment) => ({
+ fragment,
+ ok: containsWords(hay, strictNormalize(fragment)),
+ }));
+ const failed = fragments.find((f) => !f.ok)?.fragment;
+ return {
+ ok: fragments.length > 0 && failed === undefined,
+ fragments,
+ ...(failed !== undefined ? { failed } : fragments.length === 0 ? { failed: quote } : {}),
+ method: STRICT_QUOTE_METHOD,
+ };
+}
+
+// The text of every cue overlapping [second − window, second + window].
+export function strictWindowText(
+ cues: readonly TimedText[],
+ second: number,
+ windowSeconds = STRICT_QUOTE_WINDOW_SECONDS,
+): string {
+ return cueWindowText(cues, second, second, windowSeconds);
+}
+
+// A span quote, strictly: each fragment verbatim in the cues within
+// ±windowSeconds of `second` (the cited second — a citation's `start`).
+export function strictQuoteCheck(
+ quote: string,
+ cues: readonly TimedText[],
+ second: number,
+ opts: { windowSeconds?: number } = {},
+): StrictQuoteResult {
+ return strictAgainst(quote, strictWindowText(cues, second, opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS));
+}
+
+// A post quote, strictly: each fragment verbatim in the post's text.
+export function strictTextCheck(quote: string, text: string): StrictQuoteResult {
+ return strictAgainst(quote, text);
+}
diff --git a/common/lib/report/draft/agentTool.ts b/common/lib/report/draft/agentTool.ts
@@ -0,0 +1,13 @@
+// The tool shape the agent loop runs (common/lib/llm, release 27 lane A):
+// a name, a description, a JSON schema for its input, and `run`, whose text
+// goes back to the model. A thrown error is the tool's error result.
+//
+// Declared here (and in mcp/src/callTool.ts) until S5 imports lane A's one
+// definition; the two must stay this exact shape.
+
+export type AgentTool = {
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+ run(input: any, ctx: { signal?: AbortSignal }): Promise<string>; // eslint-disable-line @typescript-eslint/no-explicit-any
+};
diff --git a/common/lib/report/draft/grounding.test.ts b/common/lib/report/draft/grounding.test.ts
@@ -0,0 +1,77 @@
+// Grounding: the hard checks every narration line passes, and the Q0 lints.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { checkNarration, groundingInputOf, lintNarration, reportText, QUOTE_RUN_MESSAGE } from "./grounding";
+
+const REPORTS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/reports");
+const basic = JSON.parse(await readFile(path.join(REPORTS, "basic.report.json"), "utf8"));
+const input = groundingInputOf(basic);
+
+test("the report's text: title, sections, claims, quotes and labels", () => {
+ const t = reportText(basic);
+ assert.match(t, /Synth Kitchen — what the baker says about the bakery/);
+ assert.match(t, /The contest/);
+ assert.match(t, /I paid for the new mixer myself/);
+ assert.match(t, /Bread day/);
+});
+
+test("a grounded line passes clean", () => {
+ assert.deepEqual(checkNarration("She talks about the bakery, the oven and the contest. Here's what she said.", input), {
+ hard: [],
+ soft: [],
+ });
+});
+
+test("hard: numbers and names the report lacks", () => {
+ const r = checkNarration("She sold 7 bakeries to Megacorp in twenty minutes.", input);
+ assert.ok(r.hard.includes("number 7 is not in the report"), r.hard.join("|"));
+ assert.ok(r.hard.includes("name “Megacorp” is not in the report"), r.hard.join("|"));
+ assert.ok(r.hard.includes("number “twenty” is not in the report"), r.hard.join("|"));
+ // A name the report has passes, possessive or not; the first word of a sentence is not a name.
+ assert.deepEqual(checkNarration("Kitchen talk. Bread day is where Synth Kitchen's baker speaks.", input).hard, []);
+});
+
+test("hard: tags, stock phrases, quotation marks, quotes read out", () => {
+ assert.deepEqual(checkNarration("<laugh> So she did.", input).hard, ["has a tag in angle brackets"]);
+ assert.deepEqual(checkNarration("Let's dive in to the bakery.", input).hard, [
+ "stock phrase “dive in”",
+ "stock phrase “let's dive in”",
+ "stock phrase “let's dive”",
+ ]);
+ assert.deepEqual(checkNarration("She said “no” to the bakery.", input).hard, [
+ "text in quotation marks: no quotes in narration",
+ ]);
+ // Six words of a quote, said as the narrator's own.
+ assert.deepEqual(checkNarration("She says she would never sell the bakery to a chain.", input).hard, [QUOTE_RUN_MESSAGE]);
+ // Five words are not a quote run.
+ assert.deepEqual(checkNarration("She would never sell the bakery.", input).hard, []);
+});
+
+test("soft (Q0): a negation mismatch — the meaning reversed against its evidence", () => {
+ const ev = ["I have never met the other finalist", "She says she paid for the new mixer herself"];
+ const w = lintNarration("She met the other finalist backstage.", ev);
+ assert.equal(w.length, 1);
+ assert.match(w[0]!, /^negation mismatch: “She met the other finalist backstage\.” against “I have never met the other finalist”/);
+ assert.deepEqual(lintNarration("She has never met the other finalist.", ev), []);
+ // A line about something else is not compared.
+ assert.deepEqual(lintNarration("The pie needs an hour.", ev), []);
+});
+
+test("soft (Q0): a dropped hedge", () => {
+ const ev = ["next year maybe I will enter the contest again"];
+ const w = lintNarration("Next year she will enter the contest again.", ev);
+ assert.equal(w.length, 1);
+ assert.match(w[0]!, /^dropped hedge: /);
+ assert.deepEqual(lintNarration("Maybe she will enter the contest again next year.", ev), []);
+});
+
+test("checkNarration carries the lints as soft warnings", () => {
+ const r = checkNarration("She paid nothing for the new mixer.", input);
+ assert.deepEqual(r.hard, []);
+ assert.equal(r.soft.length, 1);
+ assert.match(r.soft[0]!, /negation mismatch/);
+});
diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts
@@ -0,0 +1,237 @@
+// GROUNDING — the code checks every drafted narration line passes before it
+// is used (the stopgap's local_narrate.py `checks`, release 27 S2), plus the
+// Q0 lints.
+//
+// HARD (the line is refused):
+// - a tag in angle brackets (no expressive tags or stage directions);
+// - a stock phrase from BANNED_PHRASES;
+// - a number — digits or a number word — the report does not have;
+// - a capitalised name the report does not have (the first word of a
+// sentence and the COMMON_CAPS words aside);
+// - text in quotation marks: a narrator does not read quotes out;
+// - six or more consecutive words of a cited quote: the clip says it.
+//
+// SOFT (a warning; the line may be used, flagged for review) — the Q0 lints,
+// for what the hard checks cannot see (plans/local-llm-report-media.md, Q0):
+// - a NEGATION MISMATCH: the line shares its content with an evidence line
+// (a claim or a quote) but one of them is negated and the other is not
+// ("I have never met the finalist" → "she met the finalist");
+// - a DROPPED HEDGE: the evidence line hedges ("maybe", "allegedly", "I
+// think") and the line that restates it does not.
+//
+// Pure: the report's text and quotes are the inputs.
+
+import { strictNormalize } from "../../citations/verify";
+
+export const BANNED_PHRASES = [
+ "that's an allegation, not a ruling",
+ "that is an allegation",
+ "worth being precise",
+ "here's the thing",
+ "let's dive in",
+ "let's dive",
+ "dive in",
+ "dive into",
+ "delve",
+ "buckle up",
+ "in conclusion",
+ "it's worth noting",
+ "it is worth noting",
+ "let's unpack",
+ "unpack",
+ "at the end of the day",
+ "a testament to",
+ "in a world where",
+ "make no mistake",
+ "the plot thickens",
+ "stay tuned",
+ "game-changer",
+ "navigate the",
+ "tapestry",
+ "let that sink in",
+] as const;
+
+const NUM_WORDS: Record<string, number> = {
+ zero: 0, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
+ eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18,
+ nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90,
+ hundred: 100, thousand: 1000, million: 1000000, dozen: 12,
+};
+
+// Capitalised words that are not names.
+export const COMMON_CAPS = new Set(
+ `I I'm I've I'd I'll A An The And But So Or Yet Then Now Here There This That These Those It It's
+He She They We You His Her Their Our Your What When Where Why How Who Which One No Not Yes Just Still Also
+Even Only First Next Last Again Some Many Most All Every Each Nothing Something Everything Anyone Someone
+Today Tomorrow Yesterday Oh Okay Ok Well Plus Because If Once While Since Before After Later Meanwhile
+Monday Tuesday Wednesday Thursday Friday Saturday Sunday January February March April May June July August
+September October November December Twice Different Same Another Both Either Neither Over Under`.split(/\s+/),
+);
+
+export const QUOTE_RUN_WORDS = 6;
+
+export const QUOTE_RUN_MESSAGE = "repeats 6+ words of a quote: the clip says it; do not read quotes out";
+
+export type GroundingInput = {
+ // Everything the report says (reportText), where numbers and names must be.
+ reference: string;
+ // The cited quotes the line must not read out.
+ quotes: readonly string[];
+ // The evidence lines (claims and quotes) the Q0 lints compare against;
+ // default: the quotes.
+ evidence?: readonly string[];
+};
+
+export type GroundingResult = { hard: string[]; soft: string[] };
+
+type ReportLike = {
+ title?: string;
+ summary?: string | null;
+ sections?: readonly { title?: string; body?: string | null; claims?: readonly { text?: string; title?: string }[] | null }[];
+ citations?: Record<string, { quote?: string; label?: string; date?: string } | undefined> | null;
+};
+
+// Every text of a report a narration may draw on: title, summary, section
+// titles and bodies, claims, and each citation's quote, label and date.
+export function reportText(report: ReportLike): string {
+ const bits: string[] = [report.title ?? "", report.summary ?? ""];
+ for (const s of report.sections ?? []) {
+ bits.push(s.title ?? "", s.body ?? "");
+ for (const c of s.claims ?? []) bits.push(c.text ?? "", c.title ?? "");
+ }
+ for (const c of Object.values(report.citations ?? {})) bits.push(c?.quote ?? "", c?.label ?? "", c?.date ?? "");
+ return bits.filter(Boolean).join("\n");
+}
+
+// The report's cited quotes.
+export function reportQuotes(report: ReportLike): string[] {
+ return Object.values(report.citations ?? {})
+ .map((c) => c?.quote ?? "")
+ .filter(Boolean);
+}
+
+// The evidence lines of a report: each claim (its citation markers
+// stripped) and each quote.
+export function reportEvidence(report: ReportLike): string[] {
+ const out: string[] = [];
+ for (const s of report.sections ?? []) {
+ for (const c of s.claims ?? []) if (c.text) out.push(c.text.replace(/\[([^\]]*)\]\(cite:[^)]+\)|\(cite:[^)]+\)/g, "$1"));
+ }
+ return [...out, ...reportQuotes(report)];
+}
+
+export function groundingInputOf(report: ReportLike): GroundingInput {
+ return { reference: reportText(report), quotes: reportQuotes(report), evidence: reportEvidence(report) };
+}
+
+const SENTENCE_SPLIT = /(?<=[.!?…])\s+/;
+
+export function sentencesOf(text: string): string[] {
+ return text.split(SENTENCE_SPLIT).map((s) => s.trim()).filter(Boolean);
+}
+
+const hasWord = (normText: string, w: string) => ` ${normText} `.includes(` ${w} `);
+
+export function checkNarration(text: string, input: GroundingInput): GroundingResult {
+ const hard = new Set<string>();
+ const soft = new Set<string>();
+ const low = text.toLowerCase();
+ if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets");
+ for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`);
+
+ const ref = input.reference;
+ const refNorm = strictNormalize(ref);
+ const refNums = new Set(ref.replace(/,/g, "").match(/\d+/g) ?? []);
+ for (const d of text.match(/\d[\d,]*/g) ?? []) {
+ if (!refNums.has(d.replace(/,/g, ""))) hard.add(`number ${d} is not in the report`);
+ }
+ for (const w of low.match(/[a-z]+/g) ?? []) {
+ const n = NUM_WORDS[w];
+ if (n === undefined) continue;
+ if (!hasWord(refNorm, w) && !refNums.has(String(n))) hard.add(`number “${w}” is not in the report`);
+ }
+ for (const sent of sentencesOf(text)) {
+ const toks = sent.match(/[A-Za-z][A-Za-z'’.-]*/g) ?? [];
+ for (const raw of toks.slice(1)) {
+ const t = raw.replace(/^[.\-’']+|[.\-’']+$/g, "");
+ if (!/^[A-Z]/.test(t) || COMMON_CAPS.has(t)) continue;
+ const n = strictNormalize(t.replace(/['’]s$/, ""));
+ if (n && !refNorm.includes(n)) hard.add(`name “${t}” is not in the report`);
+ }
+ }
+ if (/(^|\s)'[^']+(\s[^']+){3,}'/.test(text) || /["“”]/.test(text)) {
+ hard.add("text in quotation marks: no quotes in narration");
+ }
+ const said = ` ${strictNormalize(text)} `;
+ for (const q of input.quotes) {
+ const qw = strictNormalize(q).split(" ").filter(Boolean);
+ for (let k = 0; k + QUOTE_RUN_WORDS <= qw.length; k++) {
+ if (said.includes(` ${qw.slice(k, k + QUOTE_RUN_WORDS).join(" ")} `)) {
+ hard.add(QUOTE_RUN_MESSAGE);
+ break;
+ }
+ }
+ }
+ for (const w of lintNarration(text, input.evidence ?? input.quotes)) soft.add(w);
+ return { hard: [...hard].sort(), soft: [...soft].sort() };
+}
+
+// ─── the Q0 lints ───
+
+const NEGATIONS = new Set([
+ "not", "no", "never", "nobody", "nothing", "none", "neither", "nor", "cannot",
+ "dont", "doesnt", "didnt", "wont", "wouldnt", "isnt", "arent", "wasnt", "werent", "cant", "couldnt",
+ "shouldnt", "havent", "hasnt", "hadnt", "aint",
+]);
+
+const HEDGES = [
+ "maybe", "perhaps", "possibly", "probably", "allegedly", "reportedly", "apparently", "might", "may",
+ "could", "seems", "seemed", "i think", "i believe", "i guess", "kind of", "sort of", "not sure", "rumor", "rumour",
+];
+
+const STOP = new Set(
+ `a an the and but or so of to in on at by for with from as is are was were be been being it its this that these those
+i me my we our you your he him his she her they them their there here what which who whom when where why how
+do does did done have has had will would shall should can could may might must just very really also too
+about into over under than then out up down off all any some more most such only own same other again
+s t ll re ve d m o y said says say saying`.split(/\s+/),
+);
+
+function content(normText: string): Set<string> {
+ return new Set(normText.split(" ").filter((w) => w && !STOP.has(w) && !NEGATIONS.has(w)));
+}
+
+const negated = (normText: string) => normText.split(" ").some((w) => NEGATIONS.has(w));
+const hedged = (normText: string) => HEDGES.some((h) => hasWord(normText, h));
+
+// The evidence line a sentence restates: the one sharing the most content
+// words, when it shares at least two and half the sentence's.
+function closest(sentNorm: string, evidence: readonly string[]): string | null {
+ const mine = content(sentNorm);
+ if (mine.size === 0) return null;
+ let best: { line: string; shared: number } | null = null;
+ for (const line of evidence) {
+ const theirs = content(strictNormalize(line));
+ let shared = 0;
+ for (const w of mine) if (theirs.has(w)) shared++;
+ if (!best || shared > best.shared) best = { line, shared };
+ }
+ return best && best.shared >= 2 && best.shared * 2 >= mine.size ? best.line : null;
+}
+
+export function lintNarration(text: string, evidence: readonly string[]): string[] {
+ const out: string[] = [];
+ for (const sent of sentencesOf(text)) {
+ const sn = strictNormalize(sent);
+ const line = closest(sn, evidence);
+ if (!line) continue;
+ const ln = strictNormalize(line);
+ if (negated(ln) !== negated(sn)) {
+ out.push(`negation mismatch: “${sent.slice(0, 80)}” against “${line.slice(0, 80)}” — check the meaning is not reversed`);
+ }
+ if (hedged(ln) && !hedged(sn)) {
+ out.push(`dropped hedge: “${line.slice(0, 80)}” hedges, “${sent.slice(0, 80)}” does not`);
+ }
+ }
+ return out;
+}
diff --git a/common/lib/report/draft/reportOps.test.ts b/common/lib/report/draft/reportOps.test.ts
@@ -0,0 +1,181 @@
+// Report ops over the fixture sweeps: batch numbering, merge chains, reasons
+// on every refusal, no quoted words in claims, quotes untouched, a strict
+// check on every added quote.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { sweepToReport } from "../convertSweep";
+import { cuesOf, momentHref, recordOf } from "../../../testing/draft/corpus.mjs";
+import { readSweep } from "../../../testing/draft/derive";
+import { numberFindings, parseSweep, renderSweep, type SweepDoc } from "./sweepModel";
+import { applyReportOps, quotedClaimProblems, strictCheckerOver, type ReportOpsContext } from "./reportOps";
+
+const load = async (name: Parameters<typeof readSweep>[0]) => parseSweep(await readSweep(name));
+const claims = (doc: SweepDoc) => numberFindings(doc).map((x) => x.finding.claim);
+const ctx: ReportOpsContext = {
+ checkQuote: strictCheckerOver(cuesOf),
+ titleOf: async (c, id) => recordOf(c, id)?.title ?? null,
+ origin: "https://synth.example",
+};
+const quotesOfReport = async (md: string) =>
+ Object.values((await sweepToReport(md, { cuesOf })).report.citations ?? {})
+ .map((c) => ("quote" in c ? c.quote : ""))
+ .sort();
+
+test("a batch numbers against the document at its START: drop 1 then drop 3 drops the 1 and 3 the model saw", async () => {
+ const doc = await load("basic");
+ const before = claims(doc);
+ const r = await applyReportOps(doc, [{ op: "drop", n: 1 }, { op: "drop", n: 3 }, { op: "claim", n: 4, text: "She did not enter" }]);
+ assert.deepEqual(r.refused, []);
+ assert.deepEqual(claims(r.doc), [before[1], "She did not enter", before[4], before[5]]);
+ // The input is not touched.
+ assert.deepEqual(claims(doc), before);
+ // A second batch numbers afresh.
+ const r2 = await applyReportOps(r.doc, [{ op: "drop", n: 1 }]);
+ assert.deepEqual(claims(r2.doc), ["She did not enter", before[4], before[5]]);
+});
+
+test("merge chains resolve: merge 1→2, 2→3, then an op on 1 lands on 3; dropping 1 is refused with its reason", async () => {
+ const doc = await load("basic");
+ const r = await applyReportOps(doc, [
+ { op: "merge", n: 1, into: 2 },
+ { op: "merge", n: 2, into: 3, text: "She denies three stories" },
+ { op: "claim", n: 1, text: "She denies all three" },
+ { op: "drop", n: 1 },
+ { op: "merge", n: 3, into: 1 },
+ ]);
+ assert.deepEqual(r.applied.map((a) => a.index), [0, 1, 2]);
+ assert.equal(r.refused.length, 2);
+ assert.match(r.refused[0]!.why, /finding 1 was merged into finding 3; drop that one/);
+ assert.match(r.refused[1]!.why, /cannot merge into itself/);
+ const fs = numberFindings(r.doc).map((x) => x.finding);
+ assert.equal(fs.length, 4);
+ assert.equal(fs[0]!.claim, "She denies all three");
+ // Every quote kept its own link, in order.
+ const links = [...fs[0]!.rest.matchAll(/&t=(\d+)\)/g)].map((m) => Number(m[1]));
+ assert.deepEqual(links, [45, 25, 15]);
+ // Converted, the quotes are the original quotes — none edited.
+ assert.deepEqual(await quotesOfReport(renderSweep(r.doc)), await quotesOfReport(await readSweep("basic")));
+});
+
+test("every refusal carries a reason, and refuses that op only", async () => {
+ const doc = await load("basic");
+ const r = await applyReportOps(doc, [
+ { op: "drop", n: 99 },
+ { op: "drop" },
+ { op: "explode", n: 1 },
+ { op: "claim", n: 2 },
+ { op: "move", n: 2 },
+ { op: "section", section: "Nope", text: "x" },
+ { op: "section", section: "The bakery", text: "The contest" },
+ { op: "title", text: " " },
+ "nonsense",
+ { op: "drop", n: 2 },
+ { op: "drop", n: 2 },
+ { op: "claim", n: 2, text: "after the drop" },
+ ]);
+ assert.deepEqual(r.applied.map((a) => a.index), [9]);
+ assert.equal(r.refused.length, 11);
+ for (const x of r.refused) assert.ok(x.why.length > 8, JSON.stringify(x));
+ const why = r.refused.map((x) => x.why);
+ assert.match(why[0]!, /no finding 99 \(the document has 6\)/);
+ assert.match(why[2]!, /no op "explode"/);
+ assert.match(why[5]!, /no section "Nope"/);
+ assert.match(why[6]!, /already a section "The contest"/);
+ assert.match(why[9]!, /already dropped/);
+ assert.match(why[10]!, /dropped earlier in this batch/);
+});
+
+test("claims never carry quoted words or a link: the op that would put one in is refused (quotes-in-claims.md)", async () => {
+ const doc = await load("quotes-in-claims");
+ // The fixture breaks the rule; the lint names each finding.
+ assert.deepEqual(quotedClaimProblems(doc).map((p) => p.n), [1, 2, 3]);
+ const r = await applyReportOps(doc, [
+ { op: "claim", n: 1, text: 'She "would never" sell the bakery' },
+ { op: "claim", n: 2, text: "The “old oven” story is denied" },
+ { op: "merge", n: 3, into: 1, text: 'She says "nobody"' },
+ { op: "claim", n: 1, text: "See [this](https://synth.example/?v=a%2Fb&t=1)" },
+ { op: "add", section: "Findings", text: 'She "sold"', quote: "I would never sell the bakery to a chain", link: momentHref("synth-kitchen", "bread-day-01", 15) },
+ { op: "claim", n: 1, text: "She says she would never sell the bakery" },
+ ], ctx);
+ assert.deepEqual(r.applied.map((a) => a.index), [5]);
+ for (const x of r.refused.slice(0, 3)) assert.match(x.why, /no quotation marks/);
+ assert.match(r.refused[3]!.why, /no link/);
+ assert.match(r.refused[4]!.why, /no quotation marks.*put the words in "quote"/);
+ // The clean basic and multi-quote sweeps pass the lint.
+ assert.deepEqual(quotedClaimProblems(await load("basic")), []);
+ assert.deepEqual(quotedClaimProblems(await load("multi-quote")), []);
+});
+
+test("move: to a new section before Coverage, and the document still converts", async () => {
+ const doc = await load("paragraphs");
+ const r = await applyReportOps(doc, [{ op: "move", n: 2, section: "The recipe" }, { op: "move", n: 1, section: "The second shop" }]);
+ assert.match(r.refused[0]!.why, /already in "The second shop"/);
+ assert.deepEqual(r.doc.sections.map((s) => s.title), ["The second shop", "The recipe", "Coverage"]);
+ const md = renderSweep(r.doc);
+ assert.match(md, /\n## The recipe\n\n- The other kitchen tried the recipe: "we tried the sourdough recipe from last week" \[The flat loaf @ 0:05\]\([^)]+\)\n\n## Coverage\n/);
+ const { report, problems } = await sweepToReport(md, { cuesOf });
+ assert.deepEqual(problems, []);
+ assert.deepEqual(report.sections.map((s) => s.title), ["The second shop", "The recipe", "Coverage"]);
+});
+
+test("a section a batch empties goes; one with text left stays", async () => {
+ const basic = await load("basic");
+ const r = await applyReportOps(basic, [{ op: "drop", n: 4 }, { op: "drop", n: 5 }, { op: "drop", n: 6 }]);
+ assert.deepEqual(r.doc.sections.map((s) => s.title), ["The bakery"]);
+ assert.ok(renderSweep(r.doc).endsWith("&t=45)\n"));
+ const para = await load("paragraphs");
+ const r2 = await applyReportOps(para, [{ op: "drop", n: 1 }, { op: "drop", n: 2 }]);
+ assert.deepEqual(r2.doc.sections.map((s) => s.title), ["The second shop", "Coverage"]);
+});
+
+test("add: the quote is strict-checked; exact words in, a reversed quote out; no checker, no add", async () => {
+ const doc = await load("basic");
+ const link = (s: number) => momentHref("synth-kitchen", "bread-day-01", s);
+ const r = await applyReportOps(
+ doc,
+ [
+ { op: "add", section: "The oven", text: "She says the oven ran hot", quote: "“the oven was fine it just ran hot”", link: link(30) },
+ { op: "add", section: "The oven", text: "She says she would sell", quote: "I would sell the bakery to a chain", link: link(15) },
+ { op: "add", section: "The oven", text: "Far away", quote: "thanks for watching see you next week", link: momentHref("synth-kitchen", "qa-long-03", 205) },
+ { op: "add", section: "The oven", text: "No link", quote: "the oven was fine it just ran hot", link: "https://video.example/watch?v=x" },
+ { op: "add", section: "The oven", text: "Other origin", quote: "the oven was fine it just ran hot", link: "https://elsewhere.example/?v=synth-kitchen%2Fbread-day-01&t=30" },
+ { op: "add", section: "The oven", text: "Inner quote", quote: 'the "oven"', link: link(30) },
+ ],
+ ctx,
+ );
+ assert.deepEqual(r.applied.map((a) => a.index), [0]);
+ assert.match(r.refused[0]!.why, /not the transcript's words within 90 s of 15 s: "I would sell the bakery to a chain" is not there/);
+ assert.match(r.refused[1]!.why, /not the transcript's words/);
+ assert.match(r.refused[2]!.why, /needs a moment link/);
+ assert.match(r.refused[3]!.why, /origin https:\/\/synth\.example/);
+ assert.match(r.refused[4]!.why, /no quotation marks inside/);
+ const added = numberFindings(r.doc).map((x) => x.finding).find((f) => f.added)!;
+ assert.equal(
+ `- ${added.claim}${added.sep}${added.rest}`,
+ `- She says the oven ran hot: "the oven was fine it just ran hot" [Bread day @ 0:30](${link(30)})`,
+ );
+ assert.deepEqual(r.doc.sections.map((s) => s.title), ["The bakery", "The contest", "The oven"]);
+ const conv = await sweepToReport(renderSweep(r.doc), { cuesOf });
+ assert.deepEqual(conv.problems, []);
+ assert.ok(Object.values(conv.report.citations ?? {}).some((c) => "quote" in c && c.quote === "the oven was fine it just ran hot"));
+
+ const none = await applyReportOps(doc, [{ op: "add", section: "X", text: "y", quote: "the oven was fine it just ran hot", link: link(30) }]);
+ assert.match(none.refused[0]!.why, /needs the quote checker/);
+});
+
+test("section, title and summary", async () => {
+ const doc = await load("basic");
+ const r = await applyReportOps(doc, [
+ { op: "section", section: "The contest", text: "The pie contest" },
+ { op: "title", text: "What the baker says" },
+ { op: "summary", text: "Six findings from two recordings." },
+ ]);
+ assert.deepEqual(r.refused, []);
+ const md = renderSweep(r.doc);
+ assert.ok(md.startsWith("# What the baker says\n\nSix findings from two recordings.\n\n## The bakery\n"));
+ assert.match(md, /\n## The pie contest\n/);
+ const { report } = await sweepToReport(md, { cuesOf });
+ assert.equal(report.title, "What the baker says");
+ assert.equal(report.summary, "Six findings from two recordings.");
+});
diff --git a/common/lib/report/draft/reportOps.ts b/common/lib/report/draft/reportOps.ts
@@ -0,0 +1,347 @@
+// REPORT OPS — a revision of a sweep report, as checked edit operations a
+// model asks for and code applies (the stopgap's revise.py, release 27 S2).
+//
+// drop {n} remove finding n
+// claim {n, text} rewrite finding n's claim (its quotes and links stay)
+// merge {n, into, text?} fold n into another finding: it keeps every quote with
+// its own link; `text` (optional) is its new claim
+// move {n, section} move n to a section (a new title makes a section, before Coverage)
+// add {section, text, quote, link} a new finding; the quote is STRICT-checked (ctx.checkQuote)
+// section {section, text} rename a section
+// title {text} / summary {text}
+//
+// The rules, in code:
+// - A batch numbers against the document AT THE START of the batch: "drop 3,
+// drop 5" means the 3 and the 5 the model saw, whatever the drop of 3 did.
+// - Merges chain: an op on a finding merged away follows it to the finding it
+// went into (merge 1 into 2, then 2 into 3: an op on 1 lands on 3). Dropping
+// a finding merged away is refused — drop the one it went into.
+// - Every refusal carries its reason, and refuses that op only.
+// - A claim never carries quoted words or a link: convertSweep makes every
+// quoted span before a link THAT link's quote, so a claim quoting another
+// moment's words breaks its citation. An op that would put one in is
+// refused (testing/draft/sweeps/quotes-in-claims.md is the shape it stops).
+// - Quotes are never edited: no op reaches a finding's `rest`, except merge,
+// which appends one finding's quotes and links, verbatim, to another's.
+// - An `add` carries the transcript's exact words; they are checked through
+// the injected strict checker before the finding exists (no checker, no
+// add).
+
+import { STRICT_QUOTE_WINDOW_SECONDS, strictQuoteCheck } from "../../citations/verify";
+import {
+ LINK_RE,
+ QUOTE_MARK_RE,
+ findingsOf,
+ isCoverage,
+ numberFindings,
+ type Finding,
+ type SweepDoc,
+ type SweepSection,
+} from "./sweepModel";
+
+export const REPORT_OP_NAMES = ["drop", "claim", "merge", "move", "add", "section", "title", "summary"] as const;
+export type ReportOpName = (typeof REPORT_OP_NAMES)[number];
+
+// What a model sends: loosely typed, every field checked here.
+export type ReportOp = { op: string } & Record<string, unknown>;
+
+export type AppliedOp = { index: number; op: ReportOp };
+export type RefusedOp = { index: number; op: ReportOp; why: string };
+
+export type QuoteCheckRequest = { channel: string; id: string; second: number; quote: string };
+export type QuoteCheckAnswer = { ok: boolean; why?: string };
+
+export type ReportOpsContext = {
+ // The strict check for an `add`'s quote (e.g. strictCheckerOver below).
+ // Without it every `add` is refused.
+ checkQuote?: (q: QuoteCheckRequest) => Promise<QuoteCheckAnswer>;
+ // A recording's title, for the new finding's link label.
+ titleOf?: (channel: string, id: string) => Promise<string | null>;
+ // When set, an `add`'s link must start with this origin (the article's
+ // citation origin) — moment links never depend on a build's moment_base.
+ origin?: string;
+};
+
+// The strict checker over a cue reader (testing/draft/corpus.mjs cuesOf, or
+// the MCP's transcript read): every fragment verbatim within ±90 s.
+export function strictCheckerOver(
+ cuesOf: (channel: string, id: string) => Promise<readonly { start: number; end: number; text: string }[] | null>,
+ opts: { windowSeconds?: number } = {},
+): (q: QuoteCheckRequest) => Promise<QuoteCheckAnswer> {
+ const windowSeconds = opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS;
+ return async ({ channel, id, second, quote }) => {
+ const cues = await cuesOf(channel, id);
+ if (!cues || cues.length === 0) return { ok: false, why: `no transcript cues for ${channel}/${id}` };
+ const r = strictQuoteCheck(quote, cues, second, { windowSeconds });
+ return r.ok ? { ok: true } : { ok: false, why: `"${r.failed}" is not there` };
+ };
+}
+
+export type ReportOpsResult = { doc: SweepDoc; applied: AppliedOp[]; refused: RefusedOp[] };
+
+class Refusal extends Error {}
+const refuse = (why: string): never => {
+ throw new Refusal(why);
+};
+
+// A claim's text, checked: no quotation marks, no link, not empty.
+export function claimProblem(text: unknown): string | null {
+ if (typeof text !== "string" || !text.trim()) return "a claim needs its text";
+ if (QUOTE_MARK_RE.test(text)) {
+ return "a claim carries no quotation marks or quoted words — quoted words live only in a finding's quote";
+ }
+ if (new RegExp(LINK_RE.source).test(text)) return "a claim carries no link — the finding's link is in its quote";
+ return null;
+}
+
+const MOMENT_LINK_RE = /[?&]v=([^&%/]+)(?:%2F|\/)([^&]+)&t=(\d+)s?(?:&|$)/i;
+
+export function parseMomentLink(link: string): { channel: string; id: string; second: number } | null {
+ if (!/^https?:\/\//.test(link)) return null;
+ const m = MOMENT_LINK_RE.exec(link);
+ if (!m) return null;
+ return { channel: decodeURIComponent(m[1]!), id: decodeURIComponent(m[2]!), second: Number(m[3]) };
+}
+
+export function mmss(seconds: number): string {
+ const s = Math.max(0, Math.floor(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const ss = String(s % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+}
+
+function num(v: unknown): number | null {
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\s*\d+\s*$/.test(v) ? Number(v) : NaN;
+ return Number.isInteger(n) ? n : null;
+}
+
+const blank = (): { type: "line"; text: string } => ({ type: "line", text: "" });
+const isBlank = (b: SweepSection["body"][number]) => b.type === "line" && !b.text.trim();
+
+// Remove a block, and one of two blank lines it leaves side by side.
+function removeBlock(section: SweepSection, block: Finding) {
+ const i = section.body.indexOf(block);
+ if (i < 0) return;
+ section.body.splice(i, 1);
+ const prev = section.body[i - 1];
+ const next = section.body[i];
+ if (prev && next && isBlank(prev) && isBlank(next)) section.body.splice(i, 1);
+}
+
+// A finding into a section: after its last finding, else after its text
+// with a blank line between.
+function insertFinding(section: SweepSection, f: Finding) {
+ const body = section.body;
+ for (let i = body.length - 1; i >= 0; i--) {
+ if (body[i]!.type === "finding") {
+ body.splice(i + 1, 0, f);
+ return;
+ }
+ }
+ let j = body.length;
+ while (j > 0 && isBlank(body[j - 1]!)) j--;
+ body.splice(j, 0, blank(), f);
+ if (j + 2 >= body.length) body.push(blank());
+}
+
+// The section of that title, or a new one before Coverage (else last).
+function sectionFor(doc: SweepDoc, title: string): SweepSection {
+ const found = doc.sections.find((s) => s.title === title.trim());
+ if (found) return found;
+ const made: SweepSection = { title: title.trim(), body: [] };
+ const cov = doc.sections.findIndex(isCoverage);
+ doc.sections.splice(cov >= 0 ? cov : doc.sections.length, 0, made);
+ return made;
+}
+
+function sectionOf(doc: SweepDoc, f: Finding): SweepSection {
+ return doc.sections.find((s) => s.body.includes(f)) ?? refuse("that finding is no longer in the document");
+}
+
+const clone = (doc: SweepDoc): SweepDoc => structuredClone(doc);
+
+export async function applyReportOps(
+ input: SweepDoc,
+ ops: readonly unknown[],
+ ctx: ReportOpsContext = {},
+): Promise<ReportOpsResult> {
+ const doc = clone(input);
+ const applied: AppliedOp[] = [];
+ const refused: RefusedOp[] = [];
+ // ONE numbering for the whole batch.
+ const start = numberFindings(doc);
+ const byN = new Map(start.map((x) => [x.n, x.finding]));
+ const nOf = new Map(start.map((x) => [x.finding, x.n]));
+ const hadFindings = new Set(start.map((x) => x.section));
+ const mergedInto = new Map<Finding, Finding>();
+ const dropped = new Set<Finding>();
+
+ const label = (f: Finding) => (nOf.has(f) ? `finding ${nOf.get(f)}` : "the finding added in this batch");
+ const original = (v: unknown, what = "n"): Finding => {
+ const n = num(v);
+ if (n === null) return refuse(`${what} must be a finding number`);
+ return byN.get(n) ?? refuse(`no finding ${n} (the document has ${start.length})`);
+ };
+ // A finding by its batch-start number, following merges.
+ const at = (v: unknown, what = "n"): Finding => {
+ let f = original(v, what);
+ const seen = new Set<Finding>();
+ while (mergedInto.has(f)) {
+ if (seen.has(f)) refuse("a merge cycle");
+ seen.add(f);
+ f = mergedInto.get(f)!;
+ }
+ if (dropped.has(f)) refuse(`${label(f)} was dropped earlier in this batch`);
+ return f;
+ };
+ const text = (v: unknown, what: string): string =>
+ typeof v === "string" && v.trim() ? v.trim() : refuse(`${what} needs "text"`);
+
+ for (const [index, raw] of ops.entries()) {
+ const op = (raw && typeof raw === "object" ? raw : { op: String(raw) }) as ReportOp;
+ try {
+ switch (op.op) {
+ case "drop": {
+ const f = original(op.n);
+ if (mergedInto.has(f)) {
+ let to = f;
+ while (mergedInto.has(to)) to = mergedInto.get(to)!;
+ refuse(`finding ${nOf.get(f)} was merged into ${label(to)}; drop that one`);
+ }
+ if (dropped.has(f)) refuse(`finding ${nOf.get(f)} was already dropped in this batch`);
+ removeBlock(sectionOf(doc, f), f);
+ dropped.add(f);
+ break;
+ }
+ case "claim": {
+ const f = at(op.n);
+ const t = text(op.text, "claim");
+ const bad = claimProblem(t);
+ if (bad) refuse(bad);
+ f.claim = t;
+ if (!f.sep) f.sep = " ";
+ break;
+ }
+ case "merge": {
+ const src = at(op.n);
+ const target = op.into ?? op.id ?? op.after;
+ if (target === undefined) refuse('merge needs "into": the finding to fold it into');
+ const dst = at(target, "into");
+ if (src === dst) refuse("a finding cannot merge into itself");
+ if (op.text !== undefined && op.text !== "") {
+ const bad = claimProblem(op.text);
+ if (bad) refuse(bad);
+ }
+ if (typeof op.text === "string" && op.text.trim()) {
+ dst.claim = op.text.trim();
+ if (!dst.sep) dst.sep = " ";
+ }
+ // Every quote keeps its own link: the rest is appended verbatim.
+ dst.rest = `${dst.rest.trimEnd()} ${src.rest.trim()}`;
+ dst.continued.push(...src.continued);
+ removeBlock(sectionOf(doc, src), src);
+ mergedInto.set(src, dst);
+ break;
+ }
+ case "move": {
+ const f = at(op.n);
+ const title = typeof op.section === "string" && op.section.trim() ? op.section : refuse('move needs "section"');
+ const from = sectionOf(doc, f);
+ const to = sectionFor(doc, title);
+ if (from === to) refuse(`finding ${nOf.get(f)} is already in "${to.title}"`);
+ removeBlock(from, f);
+ insertFinding(to, f);
+ hadFindings.add(to);
+ break;
+ }
+ case "add": {
+ if (!ctx.checkQuote) refuse("adding a finding needs the quote checker, and this run has none");
+ const title = typeof op.section === "string" && op.section.trim() ? op.section : refuse('add needs "section"');
+ const claim = text(op.text, "add");
+ const bad = claimProblem(claim);
+ if (bad) refuse(`${bad} (put the words in "quote")`);
+ const quote = typeof op.quote === "string" ? op.quote.trim().replace(/^["“”]+|["“”]+$/g, "").trim() : "";
+ if (!quote) refuse("add needs the quote: the transcript's exact words");
+ if (QUOTE_MARK_RE.test(quote) || quote.includes("\n")) refuse("a quote is one passage, with no quotation marks inside");
+ const link = typeof op.link === "string" ? op.link.trim() : "";
+ const at_ = parseMomentLink(link);
+ if (!at_) refuse("add needs a moment link: <origin>/?v=<channel>%2F<id>&t=<seconds>");
+ if (ctx.origin && !link.startsWith(ctx.origin)) refuse(`the link must be on the article's origin ${ctx.origin}`);
+ const check = await ctx.checkQuote!({ ...at_!, quote });
+ if (!check.ok) {
+ refuse(`the quote is not the transcript's words within 90 s of ${at_!.second} s${check.why ? `: ${check.why}` : ""}`);
+ }
+ const name = ((await ctx.titleOf?.(at_!.channel, at_!.id)) ?? at_!.id).replace(/[[\]()]/g, "").trim().slice(0, 80);
+ const f: Finding = {
+ type: "finding",
+ bullet: "- ",
+ claim,
+ sep: ": ",
+ rest: `"${quote}" [${name} @ ${mmss(at_!.second)}](${link})`,
+ continued: [],
+ added: true,
+ };
+ const to = sectionFor(doc, title);
+ insertFinding(to, f);
+ hadFindings.add(to);
+ break;
+ }
+ case "section": {
+ const old = typeof op.section === "string" ? op.section.trim() : "";
+ const s = doc.sections.find((x) => x.title === old) ?? refuse(`no section "${old}"`);
+ const t = text(op.text, "section");
+ if (t !== old && doc.sections.some((x) => x.title === t)) refuse(`there is already a section "${t}"`);
+ s.title = t;
+ break;
+ }
+ case "title":
+ doc.title = text(op.text, "title");
+ doc.hasTitle = true;
+ break;
+ case "summary": {
+ doc.preamble = ["", text(op.text, "summary"), ""];
+ break;
+ }
+ default:
+ refuse(`no op "${String(op.op)}" — the ops are ${REPORT_OP_NAMES.join(", ")}`);
+ }
+ applied.push({ index, op });
+ } catch (e) {
+ if (!(e instanceof Refusal)) throw e;
+ refused.push({ index, op, why: e.message });
+ }
+ }
+ // A section this batch emptied of findings, with no text left, goes.
+ doc.sections = doc.sections.filter(
+ (s) => !hadFindings.has(s) || findingsOf(s).length > 0 || s.body.some((b) => b.type === "line" && b.text.trim()),
+ );
+ return { doc, applied, refused };
+}
+
+// Findings whose quoted run carries words between its quotes that are not a
+// joiner — a claim's words inside the quote (the quotes-in-claims shape:
+// `She "would never" sell the bakery, she says: "…" [link]`). A lint for a
+// generated sweep before it is converted; the ops never make one.
+export function quotedClaimProblems(doc: SweepDoc): { n: number; why: string }[] {
+ const out: { n: number; why: string }[] = [];
+ const JOINER = /^\s*(?:…|\.\.\.|,|;|—|-|and|and then|then|or)?\s*$/i;
+ for (const { n, finding } of numberFindings(doc)) {
+ // Each link's quoted run: the text from the previous link to it.
+ const rest = finding.rest;
+ let from = 0;
+ for (const link of rest.matchAll(new RegExp(LINK_RE.source, "g"))) {
+ const run = rest.slice(from, link.index);
+ from = link.index! + link[0].length;
+ const spans = [...run.matchAll(/"[^"\n]*"|“[^”\n]*”/g)];
+ for (let i = 1; i < spans.length; i++) {
+ const between = run.slice(spans[i - 1]!.index! + spans[i - 1]![0].length, spans[i]!.index);
+ if (!JOINER.test(between)) {
+ out.push({ n, why: `words outside the quotes ("${between.trim().slice(0, 60)}") are inside a link's quoted run` });
+ break;
+ }
+ }
+ }
+ }
+ return out;
+}
diff --git a/common/lib/report/draft/research/decide.ts b/common/lib/report/draft/research/decide.ts
@@ -0,0 +1,223 @@
+// RESEARCH ACQUISITIONS — what a research run (release 27 S3b/S11) may ask
+// the editor to fetch, and the one pure decision every ask goes through
+// before anything is enqueued.
+//
+// An acquisition is a PROPOSAL: an existing editor action and its arguments,
+// with the run's reason and evidence links. `decideAcquisition` answers
+// enqueue, needs approval, or refuse (with the reason), from the run's
+// AUTONOMY and LIMITS and what the run has already spent:
+//
+// propose every acquisition waits for the operator's yes or no.
+// limits an acquisition into an EXISTING channel runs on its own while it
+// is under the caps and its size is known; a new channel, a post
+// walk (when the limits say they need approval), a priority bump,
+// anything over a cap or of unknown size waits for approval.
+// auto everything runs on its own, through the editor, until a cap is
+// reached (then it waits) — and the approval flags still hold.
+//
+// THE STANDING RULES are checked first and refuse in every mode — they are
+// not the run's to relax:
+// - a new channel is created on NO site (create-channel never carries
+// `sites`);
+// - an X channel is never put on a site;
+// - no Twitch VOD URL: an expired VOD is never fetched again;
+// - nothing bypasses the editor's queues: no `queueKey` override, and only
+// the actions below, each an existing editor action.
+
+export type Autonomy = "propose" | "limits" | "auto";
+
+export const AUTONOMIES: readonly Autonomy[] = ["propose", "limits", "auto"];
+
+export type ResearchLimits = {
+ maxItemsPerRun: number;
+ maxGbPerRun: number;
+ maxTranscribeHours: number;
+ newChannelsNeedApproval: boolean;
+ postWalksNeedApproval: boolean;
+};
+
+export const DEFAULT_RESEARCH_LIMITS: ResearchLimits = {
+ maxItemsPerRun: 20,
+ maxGbPerRun: 5,
+ maxTranscribeHours: 6,
+ newChannelsNeedApproval: true,
+ postWalksNeedApproval: true,
+};
+
+// The editor actions a research run may ask for, by the name its tool and its
+// proposal carry. Each maps to ONE existing editor action (`priority-bump` is
+// `channel-priority` with tier "normal").
+export const ACQUISITION_ACTIONS = [
+ "import-archive-org",
+ "import-video",
+ "create-channel",
+ "fetch-posts",
+ "capture-posts",
+ "import-post",
+ "transcribe-one",
+ "priority-bump",
+ "persist-videos",
+] as const;
+
+export type AcquisitionAction = (typeof ACQUISITION_ACTIONS)[number];
+
+export const PROPOSAL_STATUSES = ["proposed", "approved", "rejected", "enqueued", "done", "failed"] as const;
+export type ProposalStatus = (typeof PROPOSAL_STATUSES)[number];
+
+// What the run expects an acquisition to cost, as far as it knows.
+export type AcquisitionEstimate = {
+ items?: number;
+ gb?: number;
+ transcribeHours?: number;
+};
+
+export type Proposal = {
+ id: string;
+ action: AcquisitionAction;
+ args: Record<string, unknown>;
+ reason: string;
+ evidence: string[];
+ estimate?: AcquisitionEstimate;
+ status: ProposalStatus;
+ jobId?: string;
+ // Why it waits, was refused or failed (the decision's or the editor's words).
+ note?: string;
+};
+
+export type Spent = { items: number; gb: number; transcribeHours: number };
+
+export const NOTHING_SPENT: Spent = { items: 0, gb: 0, transcribeHours: 0 };
+
+export type AcquisitionDecision =
+ | { decision: "enqueue" }
+ | { decision: "approval"; reason: string }
+ | { decision: "refuse"; reason: string };
+
+// ─── the standing rules ───
+
+const TWITCH_VOD = /^(?:https?:\/\/)?(?:[a-z0-9-]+\.)*twitch\.tv\/(?:videos\/\d+|[^/?#]+\/(?:v|video|videos)\/\d+)/i;
+const X_HOST = /^(?:https?:\/\/)?(?:[a-z0-9-]+\.)*(?:x\.com|twitter\.com)(?:[/:?#]|$)/i;
+
+// Every string anywhere in the args, depth-first.
+function strings(v: unknown, out: string[] = []): string[] {
+ if (typeof v === "string") out.push(v);
+ else if (Array.isArray(v)) for (const x of v) strings(x, out);
+ else if (v && typeof v === "object") for (const x of Object.values(v)) strings(x, out);
+ return out;
+}
+
+export const isTwitchVodUrl = (s: string) => TWITCH_VOD.test(s.trim());
+export const isXUrl = (s: string) => X_HOST.test(s.trim());
+
+function createChannelIsX(args: Record<string, unknown>): boolean {
+ const f = (args.fields ?? {}) as Record<string, unknown>;
+ const url = typeof f.url === "string" ? f.url : "";
+ const platform = typeof f.platform === "string" ? f.platform.toLowerCase() : "";
+ const fetcher = typeof f.postFetcher === "string" ? f.postFetcher.toLowerCase() : "";
+ return isXUrl(url) || platform === "x" || platform === "twitter" || fetcher.startsWith("x-");
+}
+
+// The standing rule a proposal breaks, or null.
+export function standingRuleRefusal(p: Pick<Proposal, "action" | "args">): string | null {
+ if (!(ACQUISITION_ACTIONS as readonly string[]).includes(p.action)) {
+ return `"${p.action}" is not an acquisition a research run may ask for (${ACQUISITION_ACTIONS.join(", ")})`;
+ }
+ if ("queueKey" in p.args) return "nothing bypasses the editor's queues: a queueKey override is not allowed";
+ const vod = strings(p.args).find(isTwitchVodUrl);
+ if (vod) return `a Twitch VOD is never fetched again (expired VODs are gone; look for the stream on archive.org or elsewhere): ${vod}`;
+ if (p.action === "create-channel") {
+ const sites = p.args.sites;
+ if (sites !== undefined && !(Array.isArray(sites) && sites.length === 0)) {
+ if (createChannelIsX(p.args)) return "an X channel is never put on a site";
+ return "a channel a research run creates goes on NO site; the operator adds it to one";
+ }
+ }
+ return null;
+}
+
+// ─── the decision ───
+
+// A walk over a social account's history (a full re-walk or the older walk).
+export const isPostWalk = (p: Pick<Proposal, "action" | "args">) =>
+ p.action === "fetch-posts" && (p.args.full === true || p.args.older === true);
+
+// What an acquisition costs against the caps; unknown where it downloads and
+// the run did not say. A channel created, a post fetch, a capture, a bump
+// cost no item; one post is one item.
+function cost(p: Pick<Proposal, "action" | "args" | "estimate">): { items: number; gb: number | null; hours: number | null } {
+ const e = p.estimate ?? {};
+ const listed = (k: string) => (Array.isArray(p.args[k]) ? (p.args[k] as unknown[]).length : undefined);
+ switch (p.action) {
+ case "import-archive-org":
+ case "import-video":
+ case "persist-videos":
+ return {
+ items: e.items ?? listed("items") ?? 1,
+ gb: e.gb ?? (p.args.dryRun === true ? 0 : null),
+ hours: 0,
+ };
+ case "import-post":
+ return { items: e.items ?? 1, gb: e.gb ?? 0, hours: 0 };
+ case "transcribe-one":
+ return { items: e.items ?? 0, gb: 0, hours: e.transcribeHours ?? null };
+ default:
+ return { items: e.items ?? 0, gb: e.gb ?? 0, hours: e.transcribeHours ?? 0 };
+ }
+}
+
+function overCap(p: Pick<Proposal, "action" | "args" | "estimate">, limits: ResearchLimits, spent: Spent): string | null {
+ const c = cost(p);
+ if (spent.items + c.items > limits.maxItemsPerRun) {
+ return `over the run's cap of ${limits.maxItemsPerRun} item(s) (${spent.items} so far, this is ${c.items})`;
+ }
+ if (c.gb === null) return "its size is not known";
+ if (spent.gb + c.gb > limits.maxGbPerRun) {
+ return `over the run's cap of ${limits.maxGbPerRun} GB (${spent.gb.toFixed(1)} so far, this is ${c.gb.toFixed(1)})`;
+ }
+ if (c.hours === null) return "its transcription length is not known";
+ if (spent.transcribeHours + c.hours > limits.maxTranscribeHours) {
+ return `over the run's cap of ${limits.maxTranscribeHours} h of transcription (${spent.transcribeHours.toFixed(1)} so far, this is ${c.hours.toFixed(1)})`;
+ }
+ return null;
+}
+
+export function decideAcquisition(
+ proposal: Pick<Proposal, "action" | "args" | "estimate">,
+ autonomy: Autonomy,
+ limits: ResearchLimits,
+ spentSoFar: Spent = NOTHING_SPENT,
+): AcquisitionDecision {
+ const broken = standingRuleRefusal(proposal);
+ if (broken) return { decision: "refuse", reason: broken };
+ if (!(AUTONOMIES as readonly string[]).includes(autonomy)) {
+ return { decision: "refuse", reason: `unknown autonomy "${String(autonomy)}"` };
+ }
+ if (autonomy === "propose") return { decision: "approval", reason: "this run proposes; the operator approves each acquisition" };
+ if (proposal.action === "create-channel" && limits.newChannelsNeedApproval) {
+ return { decision: "approval", reason: "a new channel needs the operator's approval" };
+ }
+ if (isPostWalk(proposal) && limits.postWalksNeedApproval) {
+ return { decision: "approval", reason: "a walk over an account's post history needs the operator's approval" };
+ }
+ if (autonomy === "limits") {
+ if (proposal.action === "create-channel") {
+ return { decision: "approval", reason: "under limits, only acquisitions into existing channels run on their own" };
+ }
+ if (proposal.action === "priority-bump") {
+ return { decision: "approval", reason: "a priority change is the operator's under limits" };
+ }
+ }
+ const over = overCap(proposal, limits, spentSoFar);
+ if (over) return { decision: "approval", reason: over };
+ return { decision: "enqueue" };
+}
+
+// What an enqueued proposal adds to the run's spend.
+export function spendOf(p: Pick<Proposal, "action" | "args" | "estimate">): Spent {
+ const c = cost(p);
+ return { items: c.items, gb: c.gb ?? 0, transcribeHours: c.hours ?? 0 };
+}
+
+export function addSpent(a: Spent, b: Spent): Spent {
+ return { items: a.items + b.items, gb: a.gb + b.gb, transcribeHours: a.transcribeHours + b.transcribeHours };
+}
diff --git a/common/lib/report/draft/research/research.test.ts b/common/lib/report/draft/research/research.test.ts
@@ -0,0 +1,237 @@
+// Research acquisitions: the decision over autonomy and limits, the standing
+// rules (each with its test), and the tools against a fake editor.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DEFAULT_RESEARCH_LIMITS,
+ decideAcquisition,
+ isTwitchVodUrl,
+ NOTHING_SPENT,
+ type Proposal,
+ type ResearchLimits,
+} from "./decide";
+import {
+ ACTION_SPECS,
+ acquisitionTools,
+ archiveReadTools,
+ newLedger,
+ rejectProposal,
+ runApprovedProposal,
+ type ResearchEditor,
+} from "./tools";
+
+const LIMITS: ResearchLimits = {
+ maxItemsPerRun: 3,
+ maxGbPerRun: 2,
+ maxTranscribeHours: 1,
+ newChannelsNeedApproval: true,
+ postWalksNeedApproval: true,
+};
+const OPEN: ResearchLimits = { ...LIMITS, newChannelsNeedApproval: false, postWalksNeedApproval: false };
+
+const p = (action: Proposal["action"], args: Record<string, unknown>, estimate?: Proposal["estimate"]) => ({
+ action,
+ args,
+ ...(estimate ? { estimate } : {}),
+});
+
+// A fake editor: answers each action, records every call.
+function fakeEditor(answer: (action: string, args: Record<string, unknown>) => Record<string, unknown> = () => ({ ok: true, jobId: "j1" })) {
+ const calls: { action: string; args: Record<string, unknown> }[] = [];
+ const editor: ResearchEditor = {
+ run: async (action, args) => {
+ calls.push({ action, args });
+ const a = answer(action, args);
+ if (a.ok === false) throw new Error(String(a.error));
+ return a;
+ },
+ };
+ return { editor, calls };
+}
+
+test("propose: everything waits for the operator", () => {
+ const d = decideAcquisition(p("import-video", { slug: "synth-kitchen", url: "https://video.example/v/1" }, { gb: 0.1 }), "propose", LIMITS);
+ assert.equal(d.decision, "approval");
+});
+
+test("limits: an import into an existing channel under the caps runs; over a cap, or of unknown size, it waits", () => {
+ const small = p("import-archive-org", { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026" }, { items: 2, gb: 0.3 });
+ assert.deepEqual(decideAcquisition(small, "limits", LIMITS), { decision: "enqueue" });
+ const spent = { items: 2, gb: 0.3, transcribeHours: 0 };
+ assert.match((decideAcquisition(small, "limits", LIMITS, spent) as { reason: string }).reason, /cap of 3 item\(s\) \(2 so far, this is 2\)/);
+ const big = p("import-video", { slug: "synth-kitchen", url: "https://video.example/v/2" }, { gb: 2.5 });
+ assert.match((decideAcquisition(big, "limits", LIMITS) as { reason: string }).reason, /cap of 2 GB/);
+ const unknown = p("import-video", { slug: "synth-kitchen", url: "https://video.example/v/3" });
+ assert.deepEqual(decideAcquisition(unknown, "limits", LIMITS), { decision: "approval", reason: "its size is not known" });
+ const tr = p("transcribe-one", { slug: "synth-kitchen", id: "x" }, { transcribeHours: 2 });
+ assert.match((decideAcquisition(tr, "limits", LIMITS) as { reason: string }).reason, /1 h of transcription/);
+ assert.equal(decideAcquisition(p("transcribe-one", { slug: "s", id: "x" }, { transcribeHours: 0.5 }), "limits", LIMITS).decision, "enqueue");
+ // A post into an existing channel is one item, no download size to guess.
+ assert.equal(decideAcquisition(p("import-post", { slug: "synth-social", url: "https://x.com/a/status/1" }), "limits", LIMITS).decision, "enqueue");
+});
+
+test("limits: new channels, post walks and priority bumps wait; auto runs them unless the limits say they need approval", () => {
+ const create = p("create-channel", { fields: { name: "Synth Other", handling: "youtube", url: "https://video.example/@other" } });
+ const walk = p("fetch-posts", { slug: "synth-social", older: true });
+ const fresh = p("fetch-posts", { slug: "synth-social" });
+ const bump = p("priority-bump", { slug: "synth-kitchen" });
+ assert.match((decideAcquisition(create, "limits", LIMITS) as { reason: string }).reason, /new channel needs the operator's approval/);
+ assert.match((decideAcquisition(create, "limits", OPEN) as { reason: string }).reason, /only acquisitions into existing channels/);
+ assert.match((decideAcquisition(walk, "limits", LIMITS) as { reason: string }).reason, /post history needs the operator's approval/);
+ assert.equal(decideAcquisition(walk, "limits", OPEN).decision, "enqueue");
+ assert.equal(decideAcquisition(fresh, "limits", LIMITS).decision, "enqueue");
+ assert.match((decideAcquisition(bump, "limits", LIMITS) as { reason: string }).reason, /priority change/);
+ assert.equal(decideAcquisition(create, "auto", LIMITS).decision, "approval");
+ assert.equal(decideAcquisition(create, "auto", OPEN).decision, "enqueue");
+ assert.equal(decideAcquisition(bump, "auto", LIMITS).decision, "enqueue");
+ // auto still stops at a cap.
+ assert.equal(decideAcquisition(p("import-video", { slug: "s", url: "https://v.example/1" }, { gb: 9 }), "auto", OPEN).decision, "approval");
+});
+
+test("standing rule: create-channel is always on NO site — refused with sites in every mode, even auto", () => {
+ const withSite = p("create-channel", { fields: { name: "Synth", handling: "youtube", url: "https://video.example/@s" }, sites: [{ siteId: "demo" }] });
+ for (const mode of ["propose", "limits", "auto"] as const) {
+ const d = decideAcquisition(withSite, mode, OPEN);
+ assert.equal(d.decision, "refuse", mode);
+ assert.match((d as { reason: string }).reason, /goes on NO site/);
+ }
+ assert.equal(decideAcquisition({ ...withSite, args: { ...withSite.args, sites: [] } }, "auto", OPEN).decision, "enqueue");
+});
+
+test("standing rule: an X channel never goes on a site", () => {
+ const x = p("create-channel", { fields: { name: "Synth (X)", handling: "transcribe", url: "https://x.com/synthbaker" }, sites: [{ siteId: "demo" }] });
+ const d = decideAcquisition(x, "auto", OPEN);
+ assert.deepEqual(d, { decision: "refuse", reason: "an X channel is never put on a site" });
+});
+
+test("standing rule: no Twitch VOD URL, anywhere in the args, in any mode", () => {
+ for (const url of ["https://www.twitch.tv/videos/123456789", "https://twitch.tv/somechannel/v/987", "twitch.tv/videos/1"]) {
+ assert.equal(isTwitchVodUrl(url), true, url);
+ const d = decideAcquisition(p("import-video", { slug: "s", url }, { gb: 0.1 }), "auto", OPEN);
+ assert.equal(d.decision, "refuse", url);
+ assert.match((d as { reason: string }).reason, /Twitch VOD is never fetched again/);
+ }
+ const nested = p("create-channel", { fields: { name: "T", handling: "youtube", url: "https://www.twitch.tv/videos/55" } });
+ assert.equal(decideAcquisition(nested, "auto", OPEN).decision, "refuse");
+ assert.equal(isTwitchVodUrl("https://www.twitch.tv/somechannel"), false);
+});
+
+test("standing rule: nothing bypasses the editor's queues — no queueKey, and only the listed actions", () => {
+ const d = decideAcquisition(p("fetch-posts", { slug: "s", queueKey: "fast-lane" }), "auto", OPEN);
+ assert.match((d as { reason: string }).reason, /nothing bypasses the editor's queues/);
+ const other = decideAcquisition({ action: "delete-channel" as never, args: { slug: "s" } }, "auto", OPEN);
+ assert.match((other as { reason: string }).reason, /is not an acquisition a research run may ask for/);
+ // Every tool reaches the editor through one of the existing ops actions.
+ const actions = Object.values(ACTION_SPECS).map((s) => s.editorAction).sort();
+ assert.deepEqual(actions, [
+ "capture-posts",
+ "channel-priority",
+ "create-channel",
+ "fetch-posts",
+ "import-archive-org",
+ "import-post",
+ "import-video",
+ "persist-videos",
+ "transcribe-one",
+ ]);
+});
+
+test("tools: one per action; limits mode enqueues an import through the editor, records it, and spends it", async () => {
+ const { editor, calls } = fakeEditor();
+ const ledger = newLedger();
+ const changes: number[] = [];
+ const tools = acquisitionTools({ editor, autonomy: "limits", limits: LIMITS, ledger, onChange: (l) => void changes.push(l.proposals.length) });
+ assert.deepEqual(tools.map((t) => t.name).sort(), Object.keys(ACTION_SPECS).sort());
+ const imp = tools.find((t) => t.name === "import-archive-org")!;
+ const out = await imp.run(
+ {
+ slug: "synth-kitchen",
+ item: "synth-kitchen-episodes-2026",
+ match: "\\.mp4$",
+ reason: "the bread day episode is not in the archive",
+ evidence: ["https://archive.org/details/synth-kitchen-episodes-2026"],
+ estimate: { items: 1, gb: 0.1 },
+ },
+ {},
+ );
+ assert.equal(out, "p01 import-archive-org: enqueued as job j1 — it runs on the editor's queue; follow it, do not repeat it.");
+ assert.deepEqual(calls, [{ action: "import-archive-org", args: { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026", match: "\\.mp4$" } }]);
+ assert.deepEqual(ledger.proposals[0], {
+ id: "p01",
+ action: "import-archive-org",
+ args: { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026", match: "\\.mp4$" },
+ reason: "the bread day episode is not in the archive",
+ evidence: ["https://archive.org/details/synth-kitchen-episodes-2026"],
+ estimate: { items: 1, gb: 0.1 },
+ status: "enqueued",
+ jobId: "j1",
+ });
+ assert.deepEqual(ledger.spent, { items: 1, gb: 0.1, transcribeHours: 0 });
+ assert.deepEqual(changes, [1]);
+});
+
+test("tools: a proposal that waits calls no editor; a refused one says so; the operator's yes runs it, past the autonomy", async () => {
+ const { editor, calls } = fakeEditor((action) => (action === "create-channel" ? { ok: true, slug: "synth-other", jobIds: [] } : { ok: true, jobId: "j9" }));
+ const ledger = newLedger();
+ const tools = acquisitionTools({ editor, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS, ledger });
+ const create = tools.find((t) => t.name === "create-channel")!;
+ const waits = await create.run(
+ { fields: { name: "Synth Other", handling: "youtube", url: "https://video.example/@other" }, reason: "the other kitchen is quoted" },
+ {},
+ );
+ assert.match(waits, /^p01 create-channel: proposed — waits for the operator's approval/);
+ const refused = await create.run(
+ { fields: { name: "Synth Other", handling: "youtube", url: "https://video.example/@other" }, sites: [{ siteId: "demo" }], reason: "x" },
+ {},
+ );
+ assert.match(refused, /^p02 create-channel: refused — a channel a research run creates goes on NO site/);
+ assert.equal(calls.length, 0);
+ // The yes: no `sites` reaches the editor — the body carries only the action's own keys.
+ const yes = await runApprovedProposal({ editor, ledger }, "p01");
+ assert.equal(yes.status, "done");
+ assert.deepEqual(calls, [{ action: "create-channel", args: { fields: { name: "Synth Other", handling: "youtube", url: "https://video.example/@other" } } }]);
+ await assert.rejects(runApprovedProposal({ editor, ledger }, "p02"), /p02 is rejected/);
+ // A no.
+ const vod = tools.find((t) => t.name === "import-video")!;
+ await vod.run({ slug: "s", url: "https://video.example/v/1", reason: "r" }, {});
+ assert.equal(rejectProposal(ledger, "p03").status, "rejected");
+});
+
+test("tools: the editor's refusal fails the proposal with its words", async () => {
+ const { editor } = fakeEditor(() => ({ ok: false, error: "x.com is held until 14:00 (rate limit)" }));
+ const ledger = newLedger();
+ const tools = acquisitionTools({ editor, autonomy: "auto", limits: OPEN, ledger });
+ await assert.rejects(
+ tools.find((t) => t.name === "import-post")!.run({ slug: "synth-social", url: "https://x.com/synthbaker/status/1", reason: "r" }, {}),
+ /p01 import-post: failed — the editor refused: x\.com is held until 14:00/,
+ );
+ assert.equal(ledger.proposals[0]!.status, "failed");
+ assert.deepEqual(ledger.spent, NOTHING_SPENT);
+});
+
+test("tools: priority-bump is channel-priority with tier normal", async () => {
+ const { editor, calls } = fakeEditor(() => ({ ok: true }));
+ const ledger = newLedger();
+ const bump = acquisitionTools({ editor, autonomy: "auto", limits: OPEN, ledger }).find((t) => t.name === "priority-bump")!;
+ assert.match(await bump.run({ slug: "synth-kitchen", operation: "transcription", reason: "its new imports need transcripts" }, {}), /done/);
+ assert.deepEqual(calls, [{ action: "channel-priority", args: { slugs: ["synth-kitchen"], tier: "normal", operation: "transcription" } }]);
+});
+
+test("archive reads go through the editor", async () => {
+ const { editor, calls } = fakeEditor((action) =>
+ action === "archive-search"
+ ? { ok: true, found: 1, items: [{ identifier: "synth-radio-tape-01", title: "Synth radio — the bakery call-in" }] }
+ : { ok: true, item: { identifier: "synth-radio-tape-01", files: [{ name: "tape1.flac", size: 300000000 }] } },
+ );
+ const [search, item] = archiveReadTools({ editor });
+ assert.equal(
+ await search!.run({ query: "bakery", limit: 5 }, {}),
+ "1 item(s) found:\n- synth-radio-tape-01 — Synth radio — the bakery call-in https://archive.org/details/synth-radio-tape-01",
+ );
+ assert.match(await item!.run({ item: "synth-radio-tape-01" }, {}), /tape1\.flac/);
+ assert.deepEqual(calls, [
+ { action: "archive-search", args: { query: "bakery", limit: 5 } },
+ { action: "archive-item", args: { item: "synth-radio-tape-01" } },
+ ]);
+});
diff --git a/common/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts
@@ -0,0 +1,342 @@
+// A research run's tools (release 27 S3b): the archive.org reads, and one
+// ACQUISITION tool per editor action a run may ask for. Every tool reaches
+// the editor through the injected `editor.run(action, args)` — the ops
+// actions, on the editor's own queues at each platform's pace — and nothing
+// else: no fetch, no yt-dlp, no gallery-dl here.
+//
+// An acquisition tool records a Proposal (its action, args, reason and
+// evidence) in the run's ledger, asks decideAcquisition, and then:
+// enqueue → editor.run; the proposal is `enqueued` with its job id (or
+// `failed`, with the editor's words);
+// approval → the proposal stays `proposed`, with why it waits;
+// refuse → the proposal is `rejected`, with the standing rule it broke.
+// The model is told which in one line. `runApprovedProposal` is what the
+// operator's yes runs (S11), through the same rules but past the autonomy.
+
+import type { AgentTool } from "../agentTool";
+import {
+ addSpent,
+ decideAcquisition,
+ NOTHING_SPENT,
+ spendOf,
+ standingRuleRefusal,
+ type AcquisitionAction,
+ type AcquisitionEstimate,
+ type Autonomy,
+ type Proposal,
+ type ResearchLimits,
+ type Spent,
+} from "./decide";
+
+// The editor, as a research run sees it: one ops action, its JSON answer.
+// A refusal is thrown (the editor's sentence as the message).
+export type ResearchEditor = {
+ run(action: string, args: Record<string, unknown>): Promise<Record<string, unknown>>;
+};
+
+export type ResearchLedger = {
+ proposals: Proposal[];
+ spent: Spent;
+};
+
+export type ResearchToolsContext = {
+ editor: ResearchEditor;
+ autonomy: Autonomy;
+ limits: ResearchLimits;
+ // The run's proposals and spend; the tools append and update in place.
+ ledger: ResearchLedger;
+ // Called after every change to the ledger (S11 writes proposals.json).
+ onChange?: (ledger: ResearchLedger) => void | Promise<void>;
+ // Proposal ids (default p01, p02, … after the ledger's).
+ nextId?: () => string;
+};
+
+export function newLedger(): ResearchLedger {
+ return { proposals: [], spent: { ...NOTHING_SPENT } };
+}
+
+// ─── each action's editor call ───
+
+type ActionSpec = {
+ action: AcquisitionAction;
+ // The ops action it runs.
+ editorAction: string;
+ description: string;
+ // The action's own arguments (JSON schema properties) and which are needed.
+ properties: Record<string, unknown>;
+ required: string[];
+ // The ops body from the tool's arguments.
+ body(args: Record<string, unknown>): Record<string, unknown>;
+};
+
+const str = { type: "string" };
+const bool = { type: "boolean" };
+const strList = { type: "array", items: { type: "string" } };
+
+const pick = (args: Record<string, unknown>, keys: readonly string[]) =>
+ Object.fromEntries(keys.filter((k) => args[k] !== undefined).map((k) => [k, args[k]]));
+
+export const ACTION_SPECS: Record<AcquisitionAction, ActionSpec> = {
+ "import-archive-org": {
+ action: "import-archive-org",
+ editorAction: "import-archive-org",
+ description:
+ "Import archive.org media into an existing channel, on archive.org's queue, paced: one item ({slug, item, files? | match?}) or several ({slug, items}). dryRun lists what it would get.",
+ properties: {
+ slug: str,
+ item: str,
+ items: { type: "array", items: {} },
+ files: strList,
+ match: str,
+ dryRun: bool,
+ },
+ required: ["slug"],
+ body: (a) => pick(a, ["slug", "item", "items", "files", "match", "dryRun"]),
+ },
+ "import-video": {
+ action: "import-video",
+ editorAction: "import-video",
+ description: "Import one video by its URL into an existing channel, on its platform's queue.",
+ properties: { slug: str, url: str },
+ required: ["slug", "url"],
+ body: (a) => pick(a, ["slug", "url"]),
+ },
+ "create-channel": {
+ action: "create-channel",
+ editorAction: "create-channel",
+ description:
+ "Create a channel (on NO site — the operator adds it to one): fields {name, handling: youtube|transcribe, url, platform?, sourceKind?, postFetcher?, socialHandle?}. fetchPlaylist / fetchPostsNow start its first fetch.",
+ properties: {
+ slug: str,
+ fields: { type: "object" },
+ fetchPlaylist: bool,
+ fetchPostsNow: bool,
+ },
+ required: ["fields"],
+ body: (a) => pick(a, ["slug", "fields", "fetchPlaylist", "fetchPostsNow"]),
+ },
+ "fetch-posts": {
+ action: "fetch-posts",
+ editorAction: "fetch-posts",
+ description:
+ "Fetch a social channel's posts on its platform's queue: new posts; full (re-walk the timeline) or older (walk back, to floor YYYY-MM-DD) are post walks.",
+ properties: { slug: str, full: bool, older: bool, floor: str, from: str, limit: { type: "integer" } },
+ required: ["slug"],
+ body: (a) => pick(a, ["slug", "full", "older", "floor", "from", "limit"]),
+ },
+ "capture-posts": {
+ action: "capture-posts",
+ editorAction: "capture-posts",
+ description: "Capture archived posts of a social channel: a screenshot and the attached media of each id.",
+ properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool },
+ required: ["slug", "ids"],
+ body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles"]),
+ },
+ "import-post": {
+ action: "import-post",
+ editorAction: "import-post",
+ description: "Import ONE post by its URL (an X status or a Bluesky post) into that platform's posts channel.",
+ properties: { slug: str, url: str },
+ required: ["slug", "url"],
+ body: (a) => pick(a, ["slug", "url"]),
+ },
+ "transcribe-one": {
+ action: "transcribe-one",
+ editorAction: "transcribe-one",
+ description: "Transcribe one held video of a channel on the transcription queue.",
+ properties: { slug: str, id: str },
+ required: ["slug", "id"],
+ body: (a) => pick(a, ["slug", "id"]),
+ },
+ "priority-bump": {
+ action: "priority-bump",
+ editorAction: "channel-priority",
+ description:
+ "Raise a channel to the normal tier (optionally for one operation: sync, transcription, download, digest, backfill), so its queued work runs.",
+ properties: { slug: str, operation: str },
+ required: ["slug"],
+ body: (a) => ({ slugs: [a.slug], tier: "normal", ...(a.operation !== undefined ? { operation: a.operation } : {}) }),
+ },
+ "persist-videos": {
+ action: "persist-videos",
+ editorAction: "persist-videos",
+ description: "Save specific held videos' source media to the saved-video store: items [{slug, id}].",
+ properties: { items: { type: "array", items: { type: "object" } }, format: str },
+ required: ["items"],
+ body: (a) => pick(a, ["items", "format"]),
+ },
+};
+
+const ESTIMATE_SCHEMA = {
+ type: "object",
+ description: "What it will cost, as far as you know: items, gb, transcribeHours.",
+ properties: { items: { type: "number" }, gb: { type: "number" }, transcribeHours: { type: "number" } },
+};
+
+const jobIdOf = (answer: Record<string, unknown>): string | undefined => {
+ if (typeof answer.jobId === "string") return answer.jobId;
+ const ids = answer.jobIds;
+ return Array.isArray(ids) && typeof ids[0] === "string" ? (ids as string[]).join(",") : undefined;
+};
+
+function nextIdFor(ledger: ResearchLedger): () => string {
+ return () => {
+ const n = ledger.proposals.reduce((m, p) => Math.max(m, Number(/^p(\d+)$/.exec(p.id)?.[1] ?? 0)), 0) + 1;
+ return `p${String(n).padStart(2, "0")}`;
+ };
+}
+
+// Run a proposal's editor action and record the outcome on it.
+async function enqueue(ctx: Pick<ResearchToolsContext, "editor" | "ledger">, p: Proposal): Promise<void> {
+ const spec = ACTION_SPECS[p.action];
+ try {
+ const answer = await ctx.editor.run(spec.editorAction, spec.body(p.args));
+ const jobId = jobIdOf(answer);
+ p.status = jobId ? "enqueued" : "done";
+ if (jobId) p.jobId = jobId;
+ delete p.note;
+ ctx.ledger.spent = addSpent(ctx.ledger.spent, spendOf(p));
+ } catch (e) {
+ p.status = "failed";
+ p.note = `the editor refused: ${(e as Error).message}`;
+ }
+}
+
+function describe(p: Proposal): string {
+ switch (p.status) {
+ case "enqueued":
+ return `${p.id} ${p.action}: enqueued as job ${p.jobId} — it runs on the editor's queue; follow it, do not repeat it.`;
+ case "done":
+ return `${p.id} ${p.action}: done.`;
+ case "proposed":
+ return `${p.id} ${p.action}: proposed — waits for the operator's approval (${p.note}).`;
+ case "rejected":
+ return `${p.id} ${p.action}: refused — ${p.note}. Do not ask again.`;
+ case "failed":
+ return `${p.id} ${p.action}: failed — ${p.note}.`;
+ default:
+ return `${p.id} ${p.action}: ${p.status}.`;
+ }
+}
+
+export function acquisitionTools(ctx: ResearchToolsContext): AgentTool[] {
+ const nextId = ctx.nextId ?? nextIdFor(ctx.ledger);
+ return Object.values(ACTION_SPECS).map((spec) => ({
+ name: spec.action,
+ description: `${spec.description} Every acquisition is checked against the run's autonomy and limits first; give the reason and the evidence links.`,
+ inputSchema: {
+ type: "object",
+ properties: {
+ ...spec.properties,
+ reason: { type: "string", description: "Why this acquisition is needed for the report." },
+ evidence: { type: "array", items: { type: "string" }, description: "Links that show why (search results, item pages, posts)." },
+ estimate: ESTIMATE_SCHEMA,
+ },
+ required: [...spec.required, "reason"],
+ additionalProperties: false,
+ },
+ run: async (input: Record<string, unknown>) => {
+ const { reason, evidence, estimate, ...rest } = (input ?? {}) as Record<string, unknown>;
+ const missing = spec.required.filter((k) => rest[k] === undefined || rest[k] === "");
+ if (missing.length) throw new Error(`${spec.action} needs ${missing.join(", ")}`);
+ const p: Proposal = {
+ id: nextId(),
+ action: spec.action,
+ args: rest,
+ reason: typeof reason === "string" ? reason.trim() : "",
+ evidence: Array.isArray(evidence) ? evidence.filter((e): e is string => typeof e === "string") : [],
+ ...(estimate && typeof estimate === "object" ? { estimate: estimate as AcquisitionEstimate } : {}),
+ status: "proposed",
+ };
+ if (!p.reason) throw new Error(`${spec.action} needs a reason`);
+ const d = decideAcquisition(p, ctx.autonomy, ctx.limits, ctx.ledger.spent);
+ ctx.ledger.proposals.push(p);
+ if (d.decision === "refuse") {
+ p.status = "rejected";
+ p.note = d.reason;
+ } else if (d.decision === "approval") {
+ p.note = d.reason;
+ } else {
+ await enqueue(ctx, p);
+ }
+ await ctx.onChange?.(ctx.ledger);
+ if (p.status === "failed") throw new Error(describe(p));
+ return describe(p);
+ },
+ }));
+}
+
+// What the operator's yes runs: the proposal's action through the editor,
+// past the run's autonomy and caps (the operator decided) — never past a
+// standing rule.
+export async function runApprovedProposal(
+ ctx: Pick<ResearchToolsContext, "editor" | "ledger" | "onChange">,
+ id: string,
+): Promise<Proposal> {
+ const p = ctx.ledger.proposals.find((x) => x.id === id);
+ if (!p) throw new Error(`no proposal ${id}`);
+ if (p.status !== "proposed" && p.status !== "approved") throw new Error(`${id} is ${p.status}, not waiting for approval`);
+ const broken = standingRuleRefusal(p);
+ if (broken) {
+ p.status = "rejected";
+ p.note = broken;
+ } else {
+ p.status = "approved";
+ await enqueue(ctx, p);
+ }
+ await ctx.onChange?.(ctx.ledger);
+ return p;
+}
+
+export function rejectProposal(ledger: ResearchLedger, id: string, why = "the operator said no"): Proposal {
+ const p = ledger.proposals.find((x) => x.id === id);
+ if (!p) throw new Error(`no proposal ${id}`);
+ if (p.status !== "proposed" && p.status !== "approved") throw new Error(`${id} is ${p.status}, not waiting for approval`);
+ p.status = "rejected";
+ p.note = why;
+ return p;
+}
+
+// ─── the archive.org reads ───
+
+export function archiveReadTools(ctx: Pick<ResearchToolsContext, "editor">): AgentTool[] {
+ return [
+ {
+ name: "archive-search",
+ description:
+ "Search archive.org (its advanced search syntax: words, title:(…), creator:(…), collection:…, date:[a TO b]); identifiers and titles. Read only, paced by the editor.",
+ inputSchema: {
+ type: "object",
+ properties: { query: str, limit: { type: "integer", description: "How many items (default 50, at most 500)." } },
+ required: ["query"],
+ additionalProperties: false,
+ },
+ run: async (input: { query?: unknown; limit?: unknown }) => {
+ const a = await ctx.editor.run("archive-search", {
+ query: String(input?.query ?? ""),
+ ...(typeof input?.limit === "number" ? { limit: input.limit } : {}),
+ });
+ const items = (a.items as { identifier: string; title?: string }[] | undefined) ?? [];
+ return (
+ `${a.found ?? items.length} item(s) found` +
+ (items.length ? `:\n${items.map((i) => `- ${i.identifier}${i.title ? ` — ${i.title}` : ""} https://archive.org/details/${i.identifier}`).join("\n")}` : ".")
+ );
+ },
+ },
+ {
+ name: "archive-item",
+ description:
+ "One archive.org item's files: name, format, size, length, which are media, and whether archive.org restricts it. Read only, paced by the editor.",
+ inputSchema: {
+ type: "object",
+ properties: { item: { type: "string", description: "The item's identifier." } },
+ required: ["item"],
+ additionalProperties: false,
+ },
+ run: async (input: { item?: unknown }) => {
+ const a = await ctx.editor.run("archive-item", { item: String(input?.item ?? "") });
+ return JSON.stringify(a.item ?? a, null, 1);
+ },
+ },
+ ];
+}
diff --git a/common/lib/report/draft/sweepModel.test.ts b/common/lib/report/draft/sweepModel.test.ts
@@ -0,0 +1,88 @@
+// The sweep.md model: byte-identical round trip over every fixture sweep,
+// and the claim / sep / rest split at the first quote.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, splitFinding } from "./sweepModel";
+
+const SWEEPS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/sweeps");
+
+test("round trip: parseSweep → renderSweep is byte-identical over every fixture sweep", async () => {
+ const files = (await readdir(SWEEPS)).filter((f) => f.endsWith(".md"));
+ assert.ok(files.length >= 6, files.join(","));
+ for (const f of files) {
+ const md = await readFile(path.join(SWEEPS, f), "utf8");
+ assert.equal(renderSweep(parseSweep(md)), md, f);
+ // And without the final newline.
+ assert.equal(renderSweep(parseSweep(md.trimEnd())), md.trimEnd(), `${f} (no final newline)`);
+ }
+});
+
+test("round trip: odd shapes — no title, lines before it, indented continuations, headings with extra spaces", () => {
+ for (const md of [
+ "",
+ "no title at all\n",
+ "intro\n# Title\n\n## A\n\n- x: \"q\" [l](https://a.example/?v=c%2Fv&t=1)\n continued line\n\ntext\n",
+ "# Spaced title \n\n## Spaced section \n\n* star: “curly” [l](https://a.example/?v=c%2Fv&t=2)\n",
+ "# T\n\n## S\n\n- \"starts with a quote\" [l](https://a.example/?v=c%2Fv&t=3)\n- a plain list item, no link\n",
+ ]) {
+ assert.equal(renderSweep(parseSweep(md)), md, JSON.stringify(md));
+ }
+});
+
+test("the model: title, preamble, sections in body order; findings only where a link is", async () => {
+ const doc = parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8"));
+ assert.equal(doc.title, "Paragraphs between findings");
+ // The preamble's bullets have no links: they are preamble lines, not findings.
+ assert.ok(doc.preamble.some((l) => l.startsWith("- **The second shop")));
+ assert.deepEqual(doc.sections.map((s) => s.title), ["The second shop", "Coverage"]);
+ const shop = doc.sections[0]!;
+ assert.deepEqual(
+ shop.body.filter((b) => b.type === "line" ? b.text.trim() : true).map((b) => (b.type === "line" ? b.text : `[F] ${b.claim}`)),
+ [
+ "She talks about it near the end of a long episode.",
+ "[F] She says it opened in the spring",
+ "### A sub-heading inside a section",
+ "The other kitchen mentions the recipe, not the shop.",
+ "[F] The other kitchen tried the recipe",
+ ],
+ );
+ assert.equal(numberFindings(doc).length, 2);
+});
+
+test("split: the claim, the separator, and the rest from the first quote before the first link", () => {
+ assert.deepEqual(splitFinding('She says she would not sell: "I would never sell" [Bread day @ 0:15](https://s.example/?v=a%2Fb&t=15)'), {
+ claim: "She says she would not sell",
+ sep: ": ",
+ rest: '"I would never sell" [Bread day @ 0:15](https://s.example/?v=a%2Fb&t=15)',
+ });
+ // No quote: cut at the link.
+ assert.deepEqual(splitFinding("A claim — [x @ 0:01](https://s.example/?v=a%2Fb&t=1)"), {
+ claim: "A claim",
+ sep: " — ",
+ rest: "[x @ 0:01](https://s.example/?v=a%2Fb&t=1)",
+ });
+ // A quote AFTER the first link does not move the cut.
+ assert.equal(splitFinding('Claim [x](https://s.example/?v=a%2Fb&t=1) then "late"').claim, "Claim");
+});
+
+test("quotes-in-claims: the split puts the claim's quoted words in the rest, never in the claim", async () => {
+ const doc = parseSweep(await readFile(path.join(SWEEPS, "quotes-in-claims.md"), "utf8"));
+ const fs = numberFindings(doc).map((x) => x.finding);
+ assert.deepEqual(fs.map((f) => f.claim), ["She", "The", "She says"]);
+ for (const f of fs) assert.doesNotMatch(f.claim, /["“”]/);
+ assert.deepEqual(quotesOf(fs[2]!), ["nobody sponsored", "nobody sponsored this kitchen"]);
+});
+
+test("the numbered view a model reads", async () => {
+ const doc = parseSweep(await readFile(path.join(SWEEPS, "basic.md"), "utf8"));
+ const view = numberedView(doc);
+ assert.match(view, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUMMARY: Scope: channel/);
+ assert.match(view, /\n## The bakery\n\[1\] She says she would not sell: "I would never sell the bakery to a chain" \[Bread day @ 0:15\]/);
+ assert.match(view, /\n\[6\] She will not discuss the lease: /);
+ const p = numberedView(parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8")));
+ assert.match(p, /## Coverage {2}\(coverage — keep\)/);
+});
diff --git a/common/lib/report/draft/sweepModel.ts b/common/lib/report/draft/sweepModel.ts
@@ -0,0 +1,193 @@
+// THE SWEEP.MD MODEL — a /sweep report as a document a revision can edit
+// with checked operations (./reportOps.ts), and write back unchanged where it
+// was not edited.
+//
+// The shape (what /sweep writes and convertSweep reads,
+// lib/report/convertSweep.ts):
+//
+// # <title>
+// <preamble: the summary, any lines before the first section>
+// ## <section>
+// - <claim>: "<quoted words>" [<label>](<link>) ← a FINDING
+// <paragraphs, sub-headings, blank lines> ← kept, in body order
+//
+// A FINDING is a list item (`- ` or `* `) inside a section that carries at
+// least one citing link. It is split at its FIRST quoted span before the
+// first link (or at the link when nothing is quoted): the CLAIM before it,
+// the separator, and the REST — the quotes and links — kept verbatim. That
+// cut is the rule convertSweep imposes: every quoted span between the
+// previous link and a link becomes that link's quote, so no quoted word may
+// sit in the editable claim, and nothing an op does touches a quote.
+//
+// `parseSweep` → `renderSweep` is BYTE-IDENTICAL for any input (every line,
+// blank lines and the final newline included; a test holds it over every
+// fixture sweep). Ops change the parts they name and nothing else.
+
+export type Finding = {
+ type: "finding";
+ // The list marker as written (`- `, `* `, with any indent).
+ bullet: string;
+ claim: string;
+ // What sat between the claim and the first quote (`: `, ` — `, ` `); may
+ // be empty.
+ sep: string;
+ // From the first quote (or link) to the end of the line, verbatim.
+ rest: string;
+ // Indented lines that continue the item, verbatim.
+ continued: string[];
+ // Set by the `add` op: a finding this revision wrote (its quote is checked
+ // again after convert, and dropped — never repaired — if it fails).
+ added?: true;
+};
+
+export type SweepLine = { type: "line"; text: string };
+
+export type SweepBlock = Finding | SweepLine;
+
+export type SweepSection = {
+ title: string;
+ // The heading line as written, when it is not exactly `## <title>`.
+ rawHeading?: string;
+ body: SweepBlock[];
+};
+
+export type SweepDoc = {
+ // Lines before the `# ` title (normally none).
+ lead: string[];
+ // The title, without `# `; empty when the document has no `# ` line.
+ title: string;
+ hasTitle: boolean;
+ rawTitle?: string;
+ // Every line between the title and the first section, verbatim.
+ preamble: string[];
+ sections: SweepSection[];
+};
+
+// A quoted span: straight or curly double quotes.
+export const QUOTED_RE = /"[^"\n]*"|“[^”\n]*”/g;
+// A citing link: a markdown link to an http(s) URL.
+export const LINK_RE = /\[[^\]\n]*\]\(https?:\/\/[^)\s]+\)/g;
+// Any quotation mark a claim may not carry.
+export const QUOTE_MARK_RE = /["“”]/;
+
+const BULLET_RE = /^(\s{0,3}[-*] )(.*)$/;
+const CONTINUED_RE = /^\s{2,}\S/;
+
+function firstMatch(re: RegExp, text: string, from = 0, to = text.length): RegExpExecArray | null {
+ const r = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`);
+ r.lastIndex = from;
+ const m = r.exec(text);
+ return m && m.index < to ? m : null;
+}
+
+export function hasLink(text: string): boolean {
+ return firstMatch(LINK_RE, text) !== null;
+}
+
+// A finding's text split at its first quote before its first link (the
+// stopgap's split_item): the claim (trailing ` :—-` moved into the
+// separator), the separator, and the rest.
+export function splitFinding(text: string): { claim: string; sep: string; rest: string } {
+ const link = firstMatch(LINK_RE, text);
+ const quote = link ? firstMatch(QUOTED_RE, text, 0, link.index) : null;
+ const cut = quote ? quote.index : link ? link.index : text.length;
+ const head = text.slice(0, cut);
+ const claim = head.replace(/[ :—-]+$/u, "");
+ return { claim, sep: head.slice(claim.length), rest: text.slice(cut) };
+}
+
+export function parseSweep(md: string): SweepDoc {
+ const lines = md.split("\n");
+ const doc: SweepDoc = { lead: [], title: "", hasTitle: false, preamble: [], sections: [] };
+ let section: SweepSection | null = null;
+ let last: Finding | null = null;
+ for (const line of lines) {
+ if (section === null && !doc.hasTitle && line.startsWith("# ")) {
+ doc.hasTitle = true;
+ doc.title = line.slice(2).trim();
+ if (line !== `# ${doc.title}`) doc.rawTitle = line;
+ continue;
+ }
+ if (line.startsWith("## ")) {
+ const title = line.slice(3).trim();
+ section = { title, body: [], ...(line !== `## ${title}` ? { rawHeading: line } : {}) };
+ doc.sections.push(section);
+ last = null;
+ continue;
+ }
+ if (section === null) {
+ (doc.hasTitle ? doc.preamble : doc.lead).push(line);
+ continue;
+ }
+ if (last && CONTINUED_RE.test(line)) {
+ last.continued.push(line);
+ continue;
+ }
+ const b = BULLET_RE.exec(line);
+ if (b && hasLink(b[2]!)) {
+ last = { type: "finding", bullet: b[1]!, ...splitFinding(b[2]!), continued: [] };
+ section.body.push(last);
+ continue;
+ }
+ last = null;
+ section.body.push({ type: "line", text: line });
+ }
+ return doc;
+}
+
+export function findingLines(f: Finding): string[] {
+ return [`${f.bullet}${f.claim}${f.sep}${f.rest}`, ...f.continued];
+}
+
+export function renderSweep(doc: SweepDoc): string {
+ const out: string[] = [...doc.lead];
+ if (doc.hasTitle) {
+ out.push(doc.rawTitle !== undefined && doc.rawTitle.slice(2).trim() === doc.title ? doc.rawTitle : `# ${doc.title}`);
+ }
+ out.push(...doc.preamble);
+ for (const s of doc.sections) {
+ out.push(s.rawHeading !== undefined && s.rawHeading.slice(3).trim() === s.title ? s.rawHeading : `## ${s.title}`);
+ for (const b of s.body) {
+ if (b.type === "line") out.push(b.text);
+ else out.push(...findingLines(b));
+ }
+ }
+ return out.join("\n");
+}
+
+export function findingsOf(section: SweepSection): Finding[] {
+ return section.body.filter((b): b is Finding => b.type === "finding");
+}
+
+// Every finding in document order, numbered from 1 — the numbering an op
+// batch is written against.
+export function numberFindings(doc: SweepDoc): { n: number; section: SweepSection; finding: Finding }[] {
+ const out: { n: number; section: SweepSection; finding: Finding }[] = [];
+ for (const section of doc.sections) {
+ for (const finding of findingsOf(section)) out.push({ n: out.length + 1, section, finding });
+ }
+ return out;
+}
+
+export const isCoverage = (s: SweepSection) => s.title.trim().toLowerCase() === "coverage";
+
+// The document as a model reads it: the title, the summary, each section
+// and each finding numbered `[n]` (the numbers an op batch uses).
+export function numberedView(doc: SweepDoc): string {
+ const numbers = new Map(numberFindings(doc).map((x) => [x.finding, x.n]));
+ const summary = doc.preamble.map((l) => l.trim()).filter(Boolean).join(" ");
+ const lines = [`TITLE: ${doc.title}`, `SUMMARY: ${summary}`];
+ for (const s of doc.sections) {
+ lines.push(`## ${s.title}${isCoverage(s) ? " (coverage — keep)" : ""}`);
+ for (const b of s.body) {
+ if (b.type === "finding") lines.push(`[${numbers.get(b)}] ${b.claim}${b.sep}${b.rest}`);
+ else if (b.text.trim()) lines.push(b.text);
+ }
+ }
+ return lines.join("\n");
+}
+
+// The quoted spans of a finding's rest, in order (without their marks).
+export function quotesOf(f: Finding): string[] {
+ return [...f.rest.matchAll(new RegExp(QUOTED_RE.source, "g"))].map((m) => m[0].slice(1, -1));
+}
diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -0,0 +1,133 @@
+// Video ops over the fixture manifests: trims within the fetched window,
+// clips only from the report's citations, narration through grounding.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { applyVideoOps, cutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps";
+
+const DRAFT = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft");
+const json = async (p: string) => JSON.parse(await readFile(path.join(DRAFT, p), "utf8"));
+const manifest: VideoManifest = await json("manifests/basic.video.manifest.json");
+const report = await json("reports/basic.report.json");
+const ids = (m: VideoManifest) => m.timeline.map((e) => e.id);
+
+test("drop, move (after an entry, or to the start), heading, title, subtitle", () => {
+ const r = applyVideoOps(
+ manifest,
+ [
+ { op: "drop", id: "c02" },
+ { op: "move", id: "c06", after: "the-bakery" },
+ { op: "move", id: "the-contest", after: "start" },
+ { op: "heading", id: "the-bakery", text: "The shop" },
+ { op: "title", text: "The baker, in her words" },
+ { op: "subtitle", text: "Two recordings" },
+ ],
+ { report },
+ );
+ assert.deepEqual(r.refused, []);
+ assert.deepEqual(ids(r.manifest), ["the-contest", "title", "the-bakery", "c06", "c01", "c03", "c04", "c05"]);
+ assert.equal(r.manifest.timeline.find((e) => e.id === "the-bakery")!.heading, "The shop");
+ assert.equal(r.manifest.title, "The baker, in her words");
+ assert.equal(r.manifest.subtitle, "Two recordings");
+ // The input is not touched.
+ assert.equal(manifest.timeline.length, 9);
+});
+
+test("trim: within the parent's window ±3 s; outside it is refused with the window", () => {
+ assert.equal(TRIM_SLACK_SECONDS, 3);
+ const r = applyVideoOps(
+ manifest,
+ [
+ { op: "trim", id: "c01", start: 12.5, end: 22 },
+ { op: "trim", id: "c03", start: 41, end: 49 },
+ { op: "trim", id: "c04", start: 11, end: 10 },
+ { op: "trim", id: "the-bakery", start: 1, end: 2 },
+ { op: "trim", id: "c05", start: "x", end: 3 },
+ ],
+ { report },
+ );
+ assert.deepEqual(r.applied.map((a) => a.index), [0]);
+ const c01 = r.manifest.timeline.find((e) => e.id === "c01")!;
+ assert.deepEqual([c01.start, c01.end], [12.5, 22]);
+ assert.match(r.refused[0]!.why, /outside the fetched window \(42\.00–52\.80 s\)/);
+ assert.match(r.refused[1]!.why, /start is before its end/);
+ assert.match(r.refused[2]!.why, /is a card, not a clip/);
+ assert.match(r.refused[3]!.why, /start and end in seconds/);
+ // A second revision is bounded by the PARENT cut, not by the trimmed one.
+ const again = applyVideoOps(r.manifest, [{ op: "trim", id: "c01", start: 11.5, end: 22.5 }], { report, parent: manifest });
+ assert.match(again.refused[0]!.why, /12\.00–22\.80/);
+});
+
+test("add_clip: only the report's own video citations, once each", () => {
+ const r = applyVideoOps(
+ manifest,
+ [
+ { op: "drop", id: "c02" },
+ { op: "add_clip", citation: "c02", after: "c01" },
+ { op: "add_clip", citation: "c03" },
+ { op: "add_clip", citation: "c99" },
+ { op: "trim", id: "c02", start: 22, end: 30 },
+ ],
+ { report: { ...report, citations: { ...report.citations, p01: { kind: "post", channel: "s", id: "1", quote: "x" } } } },
+ );
+ assert.deepEqual(r.applied.map((a) => a.index), [0, 1, 4]);
+ assert.match(r.refused[0]!.why, /"c03" is already in the cut/);
+ assert.match(r.refused[1]!.why, /no citation "c99"/);
+ assert.deepEqual(ids(r.manifest).slice(0, 4), ["title", "the-bakery", "c01", "c02"]);
+ const c02 = r.manifest.timeline.find((e) => e.id === "c02")!;
+ assert.deepEqual(
+ { channel: c02.channel, video: c02.video, start: c02.start, end: c02.end, quote: c02.quote },
+ { channel: "synth-kitchen", video: "bread-day-01", start: 22, end: 30, quote: "we never said that about the old oven" },
+ );
+ const post = applyVideoOps(manifest, [{ op: "add_clip", citation: "p01" }], {
+ report: { ...report, citations: { p01: { kind: "post", channel: "s", id: "1", quote: "x" } } },
+ });
+ assert.match(post.refused[0]!.why, /only a video citation becomes a clip/);
+});
+
+test("narration: through grounding — refused with its reasons, flagged with the lints, removed with an empty text", () => {
+ const r = applyVideoOps(
+ manifest,
+ [
+ { op: "narration", id: "the-bakery", text: "First, the bakery and the oven." },
+ { op: "narration", id: "the-contest", text: "She sold 7 pies to Megacorp. <sigh>" },
+ { op: "narration", id: "the-contest", text: "She says she would never sell the bakery to a chain." },
+ { op: "narration", id: "c01", text: "A clip." },
+ { op: "narration", id: "the-contest", text: "She did enter the contest this year." },
+ { op: "narration", id: "title", text: "" },
+ ],
+ { report },
+ );
+ assert.deepEqual(r.applied.map((a) => a.index), [0, 4, 5]);
+ assert.equal(r.manifest.timeline.find((e) => e.id === "the-bakery")!.narration!.text, "First, the bakery and the oven.");
+ assert.match(r.refused[0]!.why, /^narration refused: .*has a tag.*name “Megacorp”.*number 7/);
+ assert.match(r.refused[1]!.why, /repeats 6\+ words of a quote/);
+ assert.match(r.refused[2]!.why, /"c01" is a clip, not a card/);
+ // A reversed meaning is applied, and flagged.
+ assert.match(r.applied[1]!.warnings![0]!, /^negation mismatch/);
+ assert.equal(r.manifest.timeline.find((e) => e.id === "title")!.narration, undefined);
+});
+
+test("unknown ops and entries are refused with a reason", () => {
+ const r = applyVideoOps(manifest, [{ op: "spin" }, { op: "drop", id: "nope" }, { op: "move", id: "c01", after: "c01" }], {
+ report,
+ });
+ assert.deepEqual(r.applied, []);
+ assert.deepEqual(
+ r.refused.map((x) => x.why),
+ [
+ 'no op "spin" — the ops are drop, move, heading, narration, trim, add_clip, title, subtitle',
+ 'no entry "nope" in the cut',
+ "an entry cannot move after itself",
+ ],
+ );
+});
+
+test("the cut as a model reads it", () => {
+ const v = cutView(manifest);
+ assert.match(v, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUBTITLE: \n- card title \(title\) heading: /);
+ assert.match(v, /\n- clip c01 synth-kitchen\/bread-day-01 15–19\.8 s quote: "I would never sell the bakery to a chain"/);
+});
diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts
@@ -0,0 +1,212 @@
+// VIDEO OPS — a revision of a report video's cut (`video.manifest.json`), as
+// checked edit operations a model asks for and code applies (the stopgap's
+// revise.py, release 27 S2).
+//
+// drop {id} remove an entry
+// move {id, after} reorder: after another entry, or "start"
+// heading {id, text} a card's on-screen heading
+// narration {id, text} a card's spoken narration ("" removes it) — through grounding
+// trim {id, start, end} a clip's in/out, within the fetched window ±3 s
+// add_clip {citation, after?} a clip for a video citation of the report not in the cut
+// title {text} / subtitle {text}
+//
+// The rules, in code:
+// - A narration passes ./grounding.ts's hard checks, or the op is refused
+// with them; its soft warnings come back with the result.
+// - A trim stays within the window already fetched: the PARENT cut's clip
+// (the one the revision started from) ±TRIM_SLACK_SECONDS. A clip added in
+// this revision is bounded by its own citation's span.
+// - add_clip only takes the report's own VIDEO citations, once each.
+// - Every refusal carries its reason, and refuses that op only. Ops name
+// entries by id, so a batch is not renumbered by its own drops.
+//
+// Pure: the manifest in, a new one out.
+
+import { checkNarration, groundingInputOf, type GroundingInput } from "./grounding";
+
+export const VIDEO_OP_NAMES = ["drop", "move", "heading", "narration", "trim", "add_clip", "title", "subtitle"] as const;
+
+export const TRIM_SLACK_SECONDS = 3;
+
+export type ManifestEntry = {
+ type: string;
+ id: string;
+ style?: string;
+ heading?: string;
+ narration?: { text: string } & Record<string, unknown>;
+ channel?: string;
+ video?: string;
+ start?: number;
+ end?: number;
+ cite?: number;
+ quote?: string;
+} & Record<string, unknown>;
+
+export type VideoManifest = { title?: string; subtitle?: string; timeline: ManifestEntry[] } & Record<string, unknown>;
+
+type CitationLike = { kind: string; channel?: string; id?: string; start?: number; end?: number; quote?: string };
+
+export type ReportForVideo = Parameters<typeof groundingInputOf>[0] & {
+ citations?: Record<string, CitationLike | undefined> | null;
+};
+
+export type VideoOp = { op: string } & Record<string, unknown>;
+export type AppliedVideoOp = { index: number; op: VideoOp; warnings?: string[] };
+export type RefusedVideoOp = { index: number; op: VideoOp; why: string };
+
+export type VideoOpsContext = {
+ // The report the cut is made from: its citations, and the text grounding
+ // checks a narration against.
+ report: ReportForVideo;
+ // The cut the revision started from (its clips' windows bound a trim);
+ // default: the manifest passed in.
+ parent?: VideoManifest;
+ // Grounding's input; default: from the report.
+ grounding?: GroundingInput;
+};
+
+export type VideoOpsResult = { manifest: VideoManifest; applied: AppliedVideoOp[]; refused: RefusedVideoOp[] };
+
+class Refusal extends Error {}
+const refuse = (why: string): never => {
+ throw new Refusal(why);
+};
+
+const str = (v: unknown, what: string): string =>
+ typeof v === "string" ? v : refuse(`${what} must be text`);
+
+export function applyVideoOps(input: VideoManifest, ops: readonly unknown[], ctx: VideoOpsContext): VideoOpsResult {
+ const manifest = structuredClone(input);
+ if (!Array.isArray(manifest.timeline)) manifest.timeline = [];
+ const parent = ctx.parent ?? input;
+ const parentClips = new Map(
+ (parent.timeline ?? []).filter((e) => e.type === "clip").map((e) => [e.id, e] as const),
+ );
+ const grounding = ctx.grounding ?? groundingInputOf(ctx.report);
+ const citations = ctx.report.citations ?? {};
+ const applied: AppliedVideoOp[] = [];
+ const refused: RefusedVideoOp[] = [];
+
+ for (const [index, raw] of ops.entries()) {
+ const op = (raw && typeof raw === "object" ? raw : { op: String(raw) }) as VideoOp;
+ const tl = manifest.timeline;
+ const entry = (v: unknown): ManifestEntry => {
+ const id = str(v, "id");
+ return tl.find((e) => e.id === id) ?? refuse(`no entry "${id}" in the cut`);
+ };
+ const card = (v: unknown): ManifestEntry => {
+ const e = entry(v);
+ return e.type === "card" ? e : refuse(`"${e.id}" is a ${e.type}, not a card`);
+ };
+ let warnings: string[] | undefined;
+ try {
+ switch (op.op) {
+ case "drop":
+ tl.splice(tl.indexOf(entry(op.id)), 1);
+ break;
+ case "move": {
+ const e = entry(op.id);
+ const after = str(op.after, "after");
+ if (after === e.id) refuse("an entry cannot move after itself");
+ const anchor = after === "start" ? null : entry(after);
+ tl.splice(tl.indexOf(e), 1);
+ tl.splice(anchor ? tl.indexOf(anchor) + 1 : 0, 0, e);
+ break;
+ }
+ case "heading": {
+ const c = card(op.id);
+ const t = str(op.text, "text").trim();
+ if (!t) refuse("a heading needs its text");
+ c.heading = t;
+ break;
+ }
+ case "narration": {
+ const c = card(op.id);
+ const t = str(op.text, "text").replace(/\s+/g, " ").trim();
+ if (!t) {
+ delete c.narration;
+ break;
+ }
+ const g = checkNarration(t, grounding);
+ if (g.hard.length) refuse(`narration refused: ${g.hard.join("; ")}`);
+ c.narration = { text: t };
+ if (g.soft.length) warnings = g.soft;
+ break;
+ }
+ case "trim": {
+ const e = entry(op.id);
+ if (e.type !== "clip") refuse(`"${e.id}" is a ${e.type}, not a clip`);
+ const s = Number(op.start);
+ const en = Number(op.end);
+ if (!Number.isFinite(s) || !Number.isFinite(en)) refuse("trim needs start and end in seconds");
+ if (!(s < en)) refuse("a trim's start is before its end");
+ const bound = parentClips.get(e.id) ?? e;
+ const lo = (bound.start ?? 0) - TRIM_SLACK_SECONDS;
+ const hi = (bound.end ?? 0) + TRIM_SLACK_SECONDS;
+ if (s < lo || en > hi) refuse(`outside the fetched window (${lo.toFixed(2)}–${hi.toFixed(2)} s)`);
+ e.start = s;
+ e.end = en;
+ break;
+ }
+ case "add_clip": {
+ const cid = str(op.citation, "citation");
+ const c = citations[cid] ?? refuse(`no citation "${cid}" in the report`);
+ if (c.kind !== "video") refuse(`only a video citation becomes a clip ("${cid}" is a ${c.kind})`);
+ if (tl.some((x) => x.id === cid)) refuse(`"${cid}" is already in the cut`);
+ if (typeof c.start !== "number" || typeof c.end !== "number" || !c.channel || !c.id) {
+ refuse(`citation "${cid}" has no span`);
+ }
+ const e: ManifestEntry = {
+ type: "clip",
+ id: cid,
+ channel: c.channel!,
+ video: c.id!,
+ start: c.start!,
+ end: c.end!,
+ cite: Math.floor(c.start!),
+ quote: c.quote ?? "",
+ };
+ const after = op.after === undefined || op.after === null || op.after === "" ? null : str(op.after, "after");
+ const anchor = after === null || after === "end" ? null : after === "start" ? "start" : entry(after);
+ tl.splice(anchor === null ? tl.length : anchor === "start" ? 0 : tl.indexOf(anchor) + 1, 0, e);
+ // A clip added here is bounded by its own citation.
+ parentClips.set(cid, e);
+ break;
+ }
+ case "title":
+ case "subtitle": {
+ const t = str(op.text, "text").trim();
+ if (op.op === "title" && !t) refuse("a title needs its text");
+ manifest[op.op] = t;
+ break;
+ }
+ default:
+ refuse(`no op "${String(op.op)}" — the ops are ${VIDEO_OP_NAMES.join(", ")}`);
+ }
+ applied.push({ index, op, ...(warnings ? { warnings } : {}) });
+ } catch (e) {
+ if (!(e instanceof Refusal)) throw e;
+ refused.push({ index, op, why: e.message });
+ }
+ }
+ return { manifest, applied, refused };
+}
+
+// The cut as a model reads it.
+export function cutView(m: VideoManifest): string {
+ const lines = [`TITLE: ${m.title ?? ""}`, `SUBTITLE: ${m.subtitle ?? ""}`];
+ for (const e of m.timeline ?? []) {
+ if (e.type === "card") {
+ const n = e.narration?.text ?? "";
+ lines.push(
+ `- card ${e.id} (${e.style ?? ""}) heading: ${JSON.stringify(e.heading ?? "")}` +
+ (n ? ` narration: ${JSON.stringify(n)}` : ""),
+ );
+ } else if (e.type === "clip") {
+ lines.push(`- clip ${e.id} ${e.channel}/${e.video} ${e.start}–${e.end} s quote: ${JSON.stringify(e.quote ?? "")}`);
+ } else {
+ lines.push(`- ${e.type} ${e.id}`);
+ }
+ }
+ return lines.join("\n");
+}
diff --git a/common/lib/web/fetchPage.ts b/common/lib/web/fetchPage.ts
@@ -0,0 +1,217 @@
+// WEB FETCH — one web page as readable text, through the pacer (release 27
+// D7). Read only, and fenced:
+// - http and https only;
+// - never a private, loopback, link-local or unspecified host — by name
+// (`localhost`, `*.local`, `*.internal`) or by address, the name resolved
+// first so a public name pointing inside is refused too; every redirect hop
+// is checked the same way (at most WEB_FETCH_MAX_REDIRECTS). A test opens
+// the fence with `allowPrivate`;
+// - text only (HTML, plain text, JSON, XML); a PDF, an image or a video is
+// refused, not downloaded;
+// - the body read up to WEB_FETCH_MAX_BYTES, the text cut at `maxChars`.
+//
+// A page is context for a model, never evidence: nothing here cites it.
+
+import { lookup } from "node:dns/promises";
+import { isIP } from "node:net";
+import { decodeEntities } from "../../social/htmlReader";
+import { webPacer, WebRequestError, type WebPacer } from "./pacer";
+
+export const WEB_FETCH_DEFAULT_CHARS = 12_000;
+export const WEB_FETCH_MAX_CHARS = 60_000;
+export const WEB_FETCH_MAX_BYTES = 2_000_000;
+export const WEB_FETCH_MAX_REDIRECTS = 5;
+
+export type WebPage = {
+ url: string;
+ // Where the last redirect landed.
+ finalUrl: string;
+ status: number;
+ contentType: string;
+ title?: string;
+ text: string;
+ truncated: boolean;
+};
+
+export type WebFetchOptions = {
+ maxChars?: number;
+ pacer?: WebPacer;
+ signal?: AbortSignal;
+ // Tests only: let a loopback fake server through the fence.
+ allowPrivate?: boolean;
+ // Name → addresses (default: the system resolver).
+ resolve?: (host: string) => Promise<string[]>;
+};
+
+// ─── the fence ───
+
+function ipv4Private(ip: string): boolean {
+ const p = ip.split(".").map(Number);
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
+ const [a, b] = p as [number, number, number, number];
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 192 && b === 0 && p[2] === 0) ||
+ (a === 198 && (b === 18 || b === 19)) ||
+ a >= 224
+ );
+}
+
+function ipv6Private(ip: string): boolean {
+ const s = ip.toLowerCase().replace(/^\[|\]$/g, "");
+ if (s === "::" || s === "::1") return true;
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(s);
+ if (mapped) return ipv4Private(mapped[1]!);
+ return /^(fc|fd|fe[89ab])/.test(s) || s.startsWith("ff");
+}
+
+// An address no web fetch may reach.
+export function isPrivateAddress(ip: string): boolean {
+ const v = isIP(ip.replace(/^\[|\]$/g, ""));
+ if (v === 4) return ipv4Private(ip);
+ if (v === 6) return ipv6Private(ip);
+ return true;
+}
+
+const PRIVATE_NAME = /(^|\.)(localhost|local|internal|lan|home|localdomain)$/i;
+
+const defaultResolve = async (host: string) => (await lookup(host, { all: true, verbatim: true })).map((a) => a.address);
+
+// The reason `url` may not be fetched, or null.
+export async function fetchRefusal(
+ url: string,
+ opts: Pick<WebFetchOptions, "allowPrivate" | "resolve"> = {},
+): Promise<string | null> {
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return `"${url}" is not a URL`;
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") return `only http and https pages are read (not ${u.protocol})`;
+ if (u.username || u.password) return "a URL with credentials in it is not read";
+ if (opts.allowPrivate) return null;
+ const host = u.hostname.replace(/^\[|\]$/g, "");
+ if (PRIVATE_NAME.test(host)) return `${host} is a private host`;
+ if (isIP(host)) return isPrivateAddress(host) ? `${host} is a private address` : null;
+ let addrs: string[];
+ try {
+ addrs = await (opts.resolve ?? defaultResolve)(host);
+ } catch (e) {
+ return `${host} does not resolve (${(e as Error).message})`;
+ }
+ if (addrs.length === 0) return `${host} does not resolve`;
+ const inside = addrs.find(isPrivateAddress);
+ return inside ? `${host} resolves to a private address (${inside})` : null;
+}
+
+// ─── the page as text ───
+
+const TEXT_TYPES = /^(text\/|application\/(json|xml|xhtml\+xml|rss\+xml|atom\+xml|ld\+json))/i;
+
+export function htmlToReadableText(html: string): { title?: string; text: string } {
+ const titleM = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
+ const title = titleM ? decodeEntities(titleM[1]!.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim() : undefined;
+ let body = html
+ .replace(/<!--[\s\S]*?-->/g, " ")
+ .replace(/<(script|style|noscript|svg|template|iframe|head|title)\b[^>]*>[\s\S]*?<\/\1>/gi, " ")
+ .replace(/<(nav|footer)\b[^>]*>[\s\S]*?<\/\1>/gi, " ");
+ body = body
+ .replace(/<br\s*\/?>/gi, "\n")
+ .replace(/<\/(p|div|li|h[1-6]|blockquote|tr|section|article|header|pre|table|ul|ol|dd|dt)>/gi, "\n")
+ .replace(/<li\b[^>]*>/gi, "- ")
+ .replace(/<[^>]+>/g, " ");
+ const text = decodeEntities(body)
+ .replace(/ /g, " ")
+ .split("\n")
+ .map((l) => l.replace(/[ \t\r\f\v]+/g, " ").trim())
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+ return { ...(title ? { title } : {}), text };
+}
+
+async function readCapped(res: Response, maxBytes: number): Promise<string> {
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let n = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ n += value.byteLength;
+ if (n >= maxBytes) {
+ await reader.cancel().catch(() => {});
+ break;
+ }
+ }
+ return new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes));
+}
+
+export async function webFetch(url: string, opts: WebFetchOptions = {}): Promise<WebPage> {
+ const maxChars = Math.min(WEB_FETCH_MAX_CHARS, Math.max(200, Math.floor(opts.maxChars ?? WEB_FETCH_DEFAULT_CHARS)));
+ const pacer = opts.pacer ?? webPacer;
+ let at = url.trim();
+ for (let hop = 0; ; hop++) {
+ const refusal = await fetchRefusal(at, opts);
+ if (refusal) throw new WebRequestError(refusal, null);
+ const step = await pacer.request(
+ at,
+ {
+ method: "GET",
+ redirect: "manual",
+ headers: { accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5" },
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ },
+ async (res): Promise<{ redirect: string } | { page: WebPage }> => {
+ if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
+ await res.body?.cancel().catch(() => {});
+ return { redirect: new URL(res.headers.get("location")!, at).toString() };
+ }
+ if (!res.ok) {
+ await res.body?.cancel().catch(() => {});
+ throw new WebRequestError(`${new URL(at).host} answered HTTP ${res.status}`, res.status);
+ }
+ const contentType = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();
+ if (contentType && !TEXT_TYPES.test(contentType)) {
+ await res.body?.cancel().catch(() => {});
+ throw new WebRequestError(`not a text page (${contentType}) — only pages are read here`, res.status);
+ }
+ const raw = await readCapped(res, WEB_FETCH_MAX_BYTES);
+ const html = /html|xml/.test(contentType) || (!contentType && /^\s*</.test(raw));
+ const read = html ? htmlToReadableText(raw) : { text: raw.replace(/\r\n/g, "\n").trim() };
+ const truncated = read.text.length > maxChars;
+ return {
+ page: {
+ url,
+ finalUrl: at,
+ status: res.status,
+ contentType: contentType || (html ? "text/html" : "text/plain"),
+ ...(read.title ? { title: read.title } : {}),
+ text: truncated ? read.text.slice(0, maxChars) : read.text,
+ truncated,
+ },
+ };
+ },
+ );
+ if ("page" in step) return step.page;
+ if (hop + 1 > WEB_FETCH_MAX_REDIRECTS) {
+ throw new WebRequestError(`more than ${WEB_FETCH_MAX_REDIRECTS} redirects from ${url}`, null);
+ }
+ at = step.redirect;
+ }
+}
+
+export function formatPage(p: WebPage): string {
+ return (
+ `${p.title ? `# ${p.title}\n` : ""}${p.finalUrl}\n\n${p.text}` +
+ (p.truncated ? `\n\n(cut at ${p.text.length} characters)` : "")
+ );
+}
diff --git a/common/lib/web/pacer.ts b/common/lib/web/pacer.ts
@@ -0,0 +1,150 @@
+// THE WEB PACER — every web request a generation run makes (search and page
+// reads, release 27 D7) goes through ONE in-process queue: one request at a
+// time, at least WEB_MIN_GAP_MS between one request's end and the next's
+// start, a plain user agent, and a back-off on 429 / 503 (Retry-After when
+// the server gives one, else doubling from WEB_BACKOFF_BASE_MS) before the
+// request is tried again, at most WEB_MAX_ATTEMPTS times. Polite scraping:
+// one stream, real gaps, back off when told.
+//
+// The editor's `web-search` / `web-fetch` actions and a job's agent tools
+// share the process's pacer (`webPacer`), so two callers in one editor never
+// make two streams.
+
+export const WEB_MIN_GAP_MS = 3_000;
+export const WEB_BACKOFF_BASE_MS = 10_000;
+export const WEB_BACKOFF_MAX_MS = 120_000;
+export const WEB_MAX_ATTEMPTS = 3;
+export const WEB_TIMEOUT_MS = 30_000;
+export const WEB_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0";
+
+const BACK_OFF = new Set([429, 503]);
+
+export type WebPacerDeps = {
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
+ now?: () => number;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+};
+
+export type WebPacerOpts = {
+ minGapMs?: number;
+ backoffBaseMs?: number;
+ backoffMaxMs?: number;
+ maxAttempts?: number;
+ timeoutMs?: number;
+};
+
+export class WebRequestError extends Error {
+ constructor(
+ message: string,
+ readonly status: number | null,
+ ) {
+ super(message);
+ this.name = "WebRequestError";
+ }
+}
+
+function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));
+ const t = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(t);
+ reject(signal?.reason ?? new Error("aborted"));
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+function retryAfterMs(value: string | null, nowMs: number): number | null {
+ if (!value) return null;
+ const v = value.trim();
+ if (/^\d+$/.test(v)) return Number(v) * 1000;
+ const at = Date.parse(v);
+ return Number.isFinite(at) ? Math.max(0, at - nowMs) : null;
+}
+
+export class WebPacer {
+ private readonly deps: Required<WebPacerDeps>;
+ private readonly opts: Required<WebPacerOpts>;
+ private chain: Promise<unknown> = Promise.resolve();
+ private lastDoneAt = -Infinity;
+ // Every attempt sent, with when it started (tests and logs).
+ readonly sent: { url: string; at: number }[] = [];
+
+ constructor(deps: WebPacerDeps = {}, opts: WebPacerOpts = {}) {
+ this.deps = {
+ fetch: deps.fetch ?? ((url, init) => fetch(url, init)),
+ now: deps.now ?? (() => Date.now()),
+ sleep: deps.sleep ?? defaultSleep,
+ };
+ this.opts = {
+ minGapMs: opts.minGapMs ?? WEB_MIN_GAP_MS,
+ backoffBaseMs: opts.backoffBaseMs ?? WEB_BACKOFF_BASE_MS,
+ backoffMaxMs: opts.backoffMaxMs ?? WEB_BACKOFF_MAX_MS,
+ maxAttempts: opts.maxAttempts ?? WEB_MAX_ATTEMPTS,
+ timeoutMs: opts.timeoutMs ?? WEB_TIMEOUT_MS,
+ };
+ }
+
+ // Run `fn` after every earlier request (and its gap) has finished.
+ private serial<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.chain.then(fn, fn);
+ this.chain = run.catch(() => {});
+ return run;
+ }
+
+ // One request through the queue. `read` consumes the response inside the
+ // queue's turn (so a body is read before the next request starts). A 429
+ // or 503 backs off and retries; any other answer is handed to `read`.
+ request<T>(
+ url: string,
+ init: Omit<RequestInit, "signal"> & { signal?: AbortSignal },
+ read: (res: Response) => Promise<T>,
+ ): Promise<T> {
+ return this.serial(async () => {
+ for (let attempt = 1; ; attempt++) {
+ const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now();
+ if (wait > 0) await this.deps.sleep(wait, init.signal);
+ this.sent.push({ url, at: this.deps.now() });
+ let res: Response;
+ try {
+ const timeout = AbortSignal.timeout(this.opts.timeoutMs);
+ res = await this.deps.fetch(url, {
+ ...init,
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
+ headers: { "user-agent": WEB_USER_AGENT, "accept-language": "en", ...(init.headers as Record<string, string>) },
+ });
+ } catch (e) {
+ this.lastDoneAt = this.deps.now();
+ if (init.signal?.aborted) throw e;
+ throw new WebRequestError(`${new URL(url).host} did not answer: ${(e as Error).message}`, null);
+ }
+ if (BACK_OFF.has(res.status)) {
+ await res.body?.cancel().catch(() => {});
+ this.lastDoneAt = this.deps.now();
+ if (attempt >= this.opts.maxAttempts) {
+ throw new WebRequestError(
+ `${new URL(url).host} answered HTTP ${res.status} ${attempt} times — backing off; try later`,
+ res.status,
+ );
+ }
+ const told = retryAfterMs(res.headers.get("retry-after"), this.deps.now());
+ const backoff = Math.min(this.opts.backoffMaxMs, told ?? this.opts.backoffBaseMs * 2 ** (attempt - 1));
+ await this.deps.sleep(backoff, init.signal);
+ continue;
+ }
+ try {
+ return await read(res);
+ } finally {
+ this.lastDoneAt = this.deps.now();
+ }
+ }
+ });
+ }
+}
+
+// The process's pacer: the editor's actions and every job's tools share it.
+export const webPacer = new WebPacer();
diff --git a/common/lib/web/search.ts b/common/lib/web/search.ts
@@ -0,0 +1,80 @@
+// WEB SEARCH — DuckDuckGo's HTML endpoint, read once per query through the
+// pacer (release 27 D7: no service to run). Read only: titles, URLs and
+// snippets. The endpoint is injectable (`searchUrl`) for tests and for the
+// settings' web provider (S6).
+
+import { decodeEntities } from "../../social/htmlReader";
+import { webPacer, WebRequestError, type WebPacer } from "./pacer";
+
+export const DUCKDUCKGO_HTML_URL = "https://html.duckduckgo.com/html/";
+export const WEB_SEARCH_DEFAULT_RESULTS = 6;
+export const WEB_SEARCH_MAX_RESULTS = 20;
+
+export type WebSearchResult = { title: string; url: string; snippet: string };
+
+export type WebSearchOptions = {
+ // How many results (default 6, at most 20).
+ n?: number;
+ searchUrl?: string;
+ pacer?: WebPacer;
+ signal?: AbortSignal;
+};
+
+const strip = (html: string) => decodeEntities(html.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim();
+
+// A result link: DuckDuckGo wraps it in a redirect (`/l/?uddg=<url>`).
+function unwrap(href: string): string {
+ const h = decodeEntities(href);
+ const m = /[?&]uddg=([^&]+)/.exec(h);
+ const url = m ? decodeURIComponent(m[1]!) : h.startsWith("//") ? `https:${h}` : h;
+ return url;
+}
+
+// The results of one DuckDuckGo HTML page.
+export function parseDuckDuckGoHtml(html: string, n = WEB_SEARCH_DEFAULT_RESULTS): WebSearchResult[] {
+ const out: WebSearchResult[] = [];
+ const anchor = /<a\b[^>]*class="[^"]*\bresult__a\b[^"]*"[^>]*>/g;
+ const starts = [...html.matchAll(anchor)];
+ for (let i = 0; i < starts.length && out.length < n; i++) {
+ const tag = starts[i]![0];
+ const from = starts[i]!.index! + tag.length;
+ const to = i + 1 < starts.length ? starts[i + 1]!.index! : html.length;
+ const chunk = html.slice(from, to);
+ const href = /\bhref="([^"]*)"/.exec(tag)?.[1];
+ if (!href) continue;
+ const url = unwrap(href);
+ if (!/^https?:\/\//i.test(url)) continue;
+ // Ads go through DuckDuckGo's own y.js; they are not results.
+ if (/duckduckgo\.com\/y\.js/.test(url)) continue;
+ const title = strip(chunk.slice(0, chunk.indexOf("</a>") >= 0 ? chunk.indexOf("</a>") : chunk.length));
+ const sn = /class="[^"]*\bresult__snippet\b[^"]*"[^>]*>([\s\S]*?)<\/(?:a|div|td)>/.exec(chunk);
+ out.push({ title, url, snippet: sn ? strip(sn[1]!) : "" });
+ }
+ return out;
+}
+
+export async function webSearch(query: string, opts: WebSearchOptions = {}): Promise<WebSearchResult[]> {
+ const q = query.trim();
+ if (!q) throw new WebRequestError("web search needs a query", null);
+ const n = Math.min(WEB_SEARCH_MAX_RESULTS, Math.max(1, Math.floor(opts.n ?? WEB_SEARCH_DEFAULT_RESULTS)));
+ const pacer = opts.pacer ?? webPacer;
+ const url = opts.searchUrl ?? DUCKDUCKGO_HTML_URL;
+ return pacer.request(
+ url,
+ {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "text/html" },
+ body: new URLSearchParams({ q }).toString(),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ },
+ async (res) => {
+ if (!res.ok) throw new WebRequestError(`the search answered HTTP ${res.status}`, res.status);
+ return parseDuckDuckGoHtml(await res.text(), n);
+ },
+ );
+}
+
+export function formatSearchResults(results: readonly WebSearchResult[]): string {
+ if (results.length === 0) return "(no results)";
+ return results.map((r) => `- ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ""}`).join("\n");
+}
diff --git a/common/lib/web/tools.ts b/common/lib/web/tools.ts
@@ -0,0 +1,71 @@
+// The web as agent tools (release 27 D7): `web_search` and `web_fetch`, read
+// only, through the process's pacer. For the local model; a Claude run uses
+// the API's own server-side search and may take `web_fetch` from here.
+
+import type { AgentTool } from "../report/draft/agentTool";
+import type { WebPacer } from "./pacer";
+import { formatPage, webFetch, WEB_FETCH_DEFAULT_CHARS, WEB_FETCH_MAX_CHARS } from "./fetchPage";
+import { formatSearchResults, webSearch, WEB_SEARCH_DEFAULT_RESULTS, WEB_SEARCH_MAX_RESULTS } from "./search";
+
+export type WebToolsOptions = {
+ pacer?: WebPacer;
+ // The search endpoint (default DuckDuckGo's HTML page).
+ searchUrl?: string;
+ // Tests only: let a loopback fake server through web_fetch's fence.
+ allowPrivate?: boolean;
+ resolve?: (host: string) => Promise<string[]>;
+};
+
+export function webTools(opts: WebToolsOptions = {}): AgentTool[] {
+ return [
+ {
+ name: "web_search",
+ description:
+ "Search the web (DuckDuckGo): titles, URLs and snippets. Read only, paced (one request at a time, a few " +
+ "seconds apart). For context — a web page is never cited as what someone said.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: { type: "string", description: "What to search for." },
+ n: { type: "integer", description: `How many results (default ${WEB_SEARCH_DEFAULT_RESULTS}, at most ${WEB_SEARCH_MAX_RESULTS}).` },
+ },
+ required: ["query"],
+ additionalProperties: false,
+ },
+ run: async (input: { query?: unknown; n?: unknown }, ctx) =>
+ formatSearchResults(
+ await webSearch(String(input?.query ?? ""), {
+ ...(typeof input?.n === "number" ? { n: input.n } : {}),
+ ...(opts.searchUrl ? { searchUrl: opts.searchUrl } : {}),
+ ...(opts.pacer ? { pacer: opts.pacer } : {}),
+ ...(ctx?.signal ? { signal: ctx.signal } : {}),
+ }),
+ ),
+ },
+ {
+ name: "web_fetch",
+ description:
+ "Read one web page (http or https, public hosts only) as plain text, cut to max_chars. Read only, paced. " +
+ "For context — a web page is never cited as what someone said.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ url: { type: "string", description: "The page's URL." },
+ max_chars: { type: "integer", description: `Characters of text (default ${WEB_FETCH_DEFAULT_CHARS}, at most ${WEB_FETCH_MAX_CHARS}).` },
+ },
+ required: ["url"],
+ additionalProperties: false,
+ },
+ run: async (input: { url?: unknown; max_chars?: unknown }, ctx) =>
+ formatPage(
+ await webFetch(String(input?.url ?? ""), {
+ ...(typeof input?.max_chars === "number" ? { maxChars: input.max_chars } : {}),
+ ...(opts.pacer ? { pacer: opts.pacer } : {}),
+ ...(opts.allowPrivate ? { allowPrivate: true } : {}),
+ ...(opts.resolve ? { resolve: opts.resolve } : {}),
+ ...(ctx?.signal ? { signal: ctx.signal } : {}),
+ }),
+ ),
+ },
+ ];
+}
diff --git a/common/lib/web/web.test.ts b/common/lib/web/web.test.ts
@@ -0,0 +1,164 @@
+// The web module against a fake web on loopback: the pacer (one at a time,
+// 3 s gaps, back-off), DuckDuckGo's HTML read, the page reader and its fence.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { startFakeWeb, type FakeWeb } from "../../testing/web/fakeWeb.mjs";
+import { WebPacer, WebRequestError, WEB_MIN_GAP_MS } from "./pacer";
+import { parseDuckDuckGoHtml, webSearch } from "./search";
+import { fetchRefusal, htmlToReadableText, isPrivateAddress, webFetch } from "./fetchPage";
+import { webTools } from "./tools";
+
+let web: FakeWeb;
+before(async () => {
+ web = await startFakeWeb({
+ results: {
+ "second shop": [
+ { title: "The second shop opens", url: "https://news.example/shop?id=1&x=2", snippet: "It opened in the <b>spring</b>." },
+ { title: "Bakery & co", url: "https://bakery.example/", snippet: "" },
+ { title: "Third", url: "https://third.example/", snippet: "three" },
+ ],
+ },
+ });
+});
+after(() => web.close());
+
+// A pacer on a fake clock: sleeping advances it, and every sleep is recorded.
+function clockPacer(opts: ConstructorParameters<typeof WebPacer>[1] = {}) {
+ let now = 1_000_000;
+ const sleeps: number[] = [];
+ const pacer = new WebPacer(
+ {
+ now: () => now,
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ now += ms;
+ },
+ },
+ opts,
+ );
+ return { pacer, sleeps, advance: (ms: number) => (now += ms) };
+}
+
+const page = (p: string, pacer: WebPacer) => webFetch(web.url(p), { pacer, allowPrivate: true });
+
+test("pacer: one request at a time, at least 3 s between them", async () => {
+ const { pacer, sleeps } = clockPacer();
+ assert.equal(WEB_MIN_GAP_MS, 3000);
+ let inFlight = 0;
+ let most = 0;
+ const pacerFetch = new WebPacer(
+ {
+ now: () => 0,
+ sleep: async () => {},
+ fetch: async (url, init) => {
+ inFlight++;
+ most = Math.max(most, inFlight);
+ await new Promise((r) => setTimeout(r, 15));
+ inFlight--;
+ return fetch(url, init);
+ },
+ },
+ {},
+ );
+ await Promise.all([page("/page/a", pacerFetch), page("/page/b", pacerFetch), page("/text", pacerFetch)]);
+ assert.equal(most, 1, "never two at once");
+ // On the fake clock: the second and third each waited the full gap.
+ await Promise.all([page("/page/a", pacer), page("/page/b", pacer), page("/text", pacer)]);
+ assert.deepEqual(sleeps, [3000, 3000]);
+ assert.equal(pacer.sent.length, 3);
+ assert.ok(pacer.sent[1]!.at - pacer.sent[0]!.at >= 3000);
+ assert.ok(web.requests.every((r) => /Firefox/.test(r.ua ?? "")), "a plain user agent");
+});
+
+test("pacer: a 429 backs off (Retry-After) and retries; a 503 that persists fails after three tries, backing off each time", async () => {
+ const { pacer, sleeps } = clockPacer();
+ const p = await page("/busy", pacer);
+ assert.match(p.text, /second shop opened/);
+ assert.deepEqual(sleeps, [1000, 2000], "Retry-After: 1, then the rest of the 3 s gap");
+ const down = clockPacer();
+ await assert.rejects(page("/down", down.pacer), (e: Error) => e instanceof WebRequestError && /HTTP 503 3 times — backing off/.test(e.message));
+ assert.deepEqual(down.sleeps, [10000, 20000]);
+});
+
+test("search: DuckDuckGo's HTML read — links unwrapped, ads skipped, snippets as text, n results", async () => {
+ const { pacer } = clockPacer();
+ const r = await webSearch("second shop", { searchUrl: web.searchUrl, pacer, n: 2 });
+ assert.deepEqual(r, [
+ { title: "The second shop opens", url: "https://news.example/shop?id=1&x=2", snippet: "It opened in the spring." },
+ { title: "Bakery & co", url: "https://bakery.example/", snippet: "" },
+ ]);
+ assert.deepEqual(await webSearch("nothing here", { searchUrl: web.searchUrl, pacer }), []);
+ await assert.rejects(webSearch(" ", { searchUrl: web.searchUrl, pacer }), /needs a query/);
+ const posted = web.requests.filter((x) => x.path === "/html/");
+ assert.equal(posted[0]!.method, "POST");
+ assert.equal(new URLSearchParams(posted[0]!.body).get("q"), "second shop");
+ assert.deepEqual(parseDuckDuckGoHtml("<html>no results</html>"), []);
+});
+
+test("fetch: a page as readable text — title, no script, style, nav or footer, entities decoded", async () => {
+ const { pacer } = clockPacer();
+ const p = await page("/page/a", pacer);
+ assert.equal(p.title, "The bakery & the oven");
+ assert.equal(p.contentType, "text/html");
+ assert.match(p.text, /^The bakery\nThe second shop opened in the spring\.\n+It is a small place with a big oven\.\n- bread\n- pies/);
+ assert.doesNotMatch(p.text, /tracking|color:red|Home \| About|footer text/);
+ assert.equal(p.truncated, false);
+ const t = await page("/text", pacer);
+ assert.equal(t.text, "plain words\nsecond line");
+ const long = await webFetch(web.url("/long"), { pacer, allowPrivate: true, maxChars: 500 });
+ assert.equal(long.truncated, true);
+ assert.equal(long.text.length, 500);
+});
+
+test("fetch: redirects followed (each hop fenced), at most five; a PDF is refused, not read", async () => {
+ const { pacer } = clockPacer();
+ const p = await page(`/redirect?to=${encodeURIComponent("/page/x")}`, pacer);
+ assert.equal(p.finalUrl, web.url("/page/x"));
+ assert.match(p.text, /The bakery/);
+ await assert.rejects(page("/loop", pacer), /more than 5 redirects/);
+ await assert.rejects(page("/pdf", pacer), /not a text page \(application\/pdf\)/);
+ await assert.rejects(page("/missing", pacer), /answered HTTP 404/);
+});
+
+test("the fence: http(s) only, no private or loopback host by name, address or resolution", async () => {
+ const pub = async () => ["93.184.216.34"];
+ const inside = async () => ["10.1.2.3"];
+ assert.match((await fetchRefusal("file:///etc/passwd"))!, /only http and https/);
+ assert.match((await fetchRefusal("ftp://example.com/x"))!, /only http and https/);
+ assert.match((await fetchRefusal("not a url"))!, /is not a URL/);
+ assert.match((await fetchRefusal("http://user:pw@example.com/"))!, /credentials/);
+ assert.match((await fetchRefusal("http://localhost:3001/api/ops/settings"))!, /private host/);
+ assert.match((await fetchRefusal("http://printer.local/"))!, /private host/);
+ assert.match((await fetchRefusal("http://127.0.0.1:3001/"))!, /private address/);
+ assert.match((await fetchRefusal("http://[::1]/"))!, /private address/);
+ assert.match((await fetchRefusal("http://169.254.169.254/latest/meta-data"))!, /private address/);
+ assert.match((await fetchRefusal("https://sneaky.example/", { resolve: inside }))!, /resolves to a private address \(10\.1\.2\.3\)/);
+ assert.equal(await fetchRefusal("https://example.com/", { resolve: pub }), null);
+ assert.equal(await fetchRefusal("http://127.0.0.1:9/", { allowPrivate: true }), null);
+ // The fake web is on loopback: without the test option, refused before any request.
+ const { pacer } = clockPacer();
+ const before = web.requests.length;
+ await assert.rejects(webFetch(web.url("/page/a"), { pacer }), /private address/);
+ assert.equal(web.requests.length, before);
+ for (const ip of ["10.0.0.1", "172.16.0.1", "172.31.255.255", "192.168.1.1", "127.0.0.1", "0.0.0.0", "100.64.0.1", "fd00::1", "fe80::1", "::ffff:192.168.0.1"]) {
+ assert.equal(isPrivateAddress(ip), true, ip);
+ }
+ for (const ip of ["93.184.216.34", "8.8.8.8", "172.32.0.1", "2606:4700::1111"]) assert.equal(isPrivateAddress(ip), false, ip);
+});
+
+test("htmlToReadableText keeps paragraphs apart", () => {
+ assert.deepEqual(htmlToReadableText("<title>T</title><p>a</p><p>b&c</p>"), { title: "T", text: "a\nb&c" });
+});
+
+test("the agent tools: web_search and web_fetch, in the AgentTool shape", async () => {
+ const { pacer } = clockPacer();
+ const tools = webTools({ pacer, searchUrl: web.searchUrl, allowPrivate: true });
+ assert.deepEqual(tools.map((t) => t.name), ["web_search", "web_fetch"]);
+ const s = await tools[0]!.run({ query: "second shop", n: 1 }, {});
+ assert.equal(s, "- The second shop opens\n https://news.example/shop?id=1&x=2\n It opened in the spring.");
+ const f = await tools[1]!.run({ url: web.url("/page/a"), max_chars: 300 }, {});
+ assert.match(f, /^# The bakery & the oven\nhttp:\/\/127\.0\.0\.1:\d+\/page\/a\n\nThe bakery\n/);
+ // Without the test option the tool keeps the fence.
+ await assert.rejects(webTools({ pacer })[1]!.run({ url: web.url("/page/a") }, {}), /private address/);
+});
diff --git a/common/package.json b/common/package.json
@@ -53,7 +53,7 @@
"./testing/*": "./testing/*"
},
"scripts": {
- "test": "tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\""
+ "test": "tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\" \"lib/*/*/*/*.test.ts\""
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1080.0",
diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts
@@ -23,6 +23,8 @@ import {
} from "../lib/posts";
import {
registerSocialFetcher,
+ type OnePostFetchInput,
+ type OnePostFetchResult,
type PostFetchInput,
type PostFetchResult,
type SocialFetcher,
@@ -538,4 +540,25 @@ blueskyFetcher.checkAvailability = async ({ ids, handle, signal, onLog }) => {
return out;
};
+// ONE post by its URL or AT-URI (release 27 S3b, import-post):
+// app.bsky.feed.getPosts with its one AT-URI — the public AppView, no login —
+// normalized as a timeline item is. A handle is resolved to its DID first.
+// No post in the answer: the post is gone (or never was).
+blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFetchInput): Promise<OnePostFetchResult> => {
+ if (post.platform !== "bluesky") return { post: null, error: "not a Bluesky post" };
+ try {
+ const did = post.actor.startsWith("did:") ? post.actor : await resolveHandle(post.actor, signal);
+ const uri = `at://${did}/app.bsky.feed.post/${post.id}`;
+ onLog?.(`Reading ${uri}`);
+ const body = await getJson<{ posts?: BskyPostView[] }>(
+ `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
+ signal,
+ );
+ const view = (body.posts ?? []).find((v) => rkeyFromAtUri(v.uri) === post.id);
+ return { post: view ? normalizeBlueskyItem({ post: view }, channelSlug) : null };
+ } catch (err) {
+ return { post: null, error: (err as Error).message };
+ }
+};
+
registerSocialFetcher(blueskyFetcher);
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -242,6 +242,23 @@ export type PostCaptureResult = {
stoppedEarly?: string;
};
+// Input for importing ONE post by its URL (`SocialFetcher.fetchOne`, release
+// 27 S3b's import-post): the post as the platform names it, and a normal
+// fetch's login, signal and log.
+export type OnePostFetchInput = Pick<
+ PostFetchInput,
+ "channelSlug" | "cookies" | "cookieSource" | "browserCookies" | "signal" | "onLog"
+> & {
+ post: PostUrlRef;
+};
+
+export type OnePostFetchResult = {
+ // The post (null when the platform has no such post, or no longer shows it).
+ post: Post | null;
+ needsCookies?: boolean;
+ error?: string;
+};
+
export type SocialFetcher = {
id: string;
label: string;
@@ -268,6 +285,9 @@ export type SocialFetcher = {
// post, gallery-dl downloads its media). A fetcher without it cannot, and
// the capture refuses its channel by name.
captureByIds?(input: PostCaptureInput): Promise<PostCaptureResult>;
+ // Optional: read ONE post by its URL (import-post). A fetcher without it
+ // cannot, and the import refuses its channel by name.
+ fetchOne?(input: OnePostFetchInput): Promise<OnePostFetchResult>;
};
// Populated by registerSocialFetcher() from each fetcher module. Indirection
@@ -383,3 +403,53 @@ export function handleFromAccountUrl(input: string): string | null {
if (RESERVED.has(first.toLowerCase())) return null;
return /^[A-Za-z0-9._-]+$/.test(first) ? first : null;
}
+
+// ---------------------------------------------------------------------------
+// One post's URL (release 27 S3b, import-post)
+// ---------------------------------------------------------------------------
+
+// A post named by its URL: an X status (`x.com/<handle>/status/<id>`, also
+// twitter.com, mobile., `i/web/status/<id>`) or a Bluesky post
+// (`bsky.app/profile/<handle|did>/post/<rkey>`, or its `at://` URI).
+export type PostUrlRef =
+ | { platform: "twitter"; id: string; handle?: string; url: string }
+ | { platform: "bluesky"; id: string; actor: string; url: string };
+
+export function parsePostUrl(input: string): PostUrlRef | null {
+ const raw = input.trim();
+ const at = /^at:\/\/([^/]+)\/app\.bsky\.feed\.post\/([A-Za-z0-9._~:-]+)$/.exec(raw);
+ if (at) {
+ return { platform: "bluesky", id: at[2]!, actor: at[1]!, url: `https://bsky.app/profile/${at[1]}/post/${at[2]}` };
+ }
+ let u: URL;
+ try {
+ u = new URL(raw);
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ const host = u.hostname.toLowerCase().replace(/^(www|mobile)\./, "");
+ const seg = u.pathname.split("/").filter(Boolean).map((x) => decodeURIComponent(x));
+ if (host === "x.com" || host === "twitter.com") {
+ // /<handle>/status/<id>[/photo/1…] or /i/web/status/<id> or /i/status/<id>
+ const k = seg.indexOf("status");
+ const id = k >= 1 ? seg[k + 1] : undefined;
+ if (!id || !/^\d{1,25}$/.test(id)) return null;
+ const handle = k === 1 && seg[0] !== "i" ? seg[0]!.replace(/^@/, "") : undefined;
+ if (handle !== undefined && !/^[A-Za-z0-9_]{1,30}$/.test(handle)) return null;
+ return {
+ platform: "twitter",
+ id,
+ ...(handle ? { handle } : {}),
+ url: handle ? `https://x.com/${handle}/status/${id}` : `https://x.com/i/web/status/${id}`,
+ };
+ }
+ if (host === "bsky.app") {
+ if (seg[0] !== "profile" || seg[2] !== "post" || !seg[1] || !seg[3]) return null;
+ const actor = seg[1].replace(/^@/, "");
+ const id = seg[3];
+ if (!/^[A-Za-z0-9._~:-]+$/.test(id) || !/^[A-Za-z0-9._:-]+$/.test(actor)) return null;
+ return { platform: "bluesky", id, actor, url: `https://bsky.app/profile/${actor}/post/${id}` };
+ }
+ return null;
+}
diff --git a/common/social/importPost.test.ts b/common/social/importPost.test.ts
@@ -0,0 +1,183 @@
+// import-post (release 27 S3b): one post by its URL into the posts archive of
+// a channel of that platform, through a fake fetcher. Every name is invented.
+//
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test social/importPost.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type { Post } from "../lib/posts";
+
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "import-post-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+writeFileSync(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }) + "\n");
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+// A fake gallery-dl: records its argv, prints the status it is asked for and
+// the post that status quotes, as gallery-dl's jsonl tuples (ids unquoted).
+const FAKE_BIN = path.join(ROOT, "fake-gallery-dl.mjs");
+const ARGV_FILE = path.join(ROOT, "fake-gallery-dl.argv.json");
+writeFileSync(
+ FAKE_BIN,
+ `#!/usr/bin/env node
+import { writeFileSync } from "node:fs";
+writeFileSync(${JSON.stringify(ARGV_FILE)}, JSON.stringify(process.argv.slice(2)));
+const tweet = (id, name, content) => JSON.stringify([2, { tweet_id: id, conversation_id: id, date: "2026-02-11 12:00:00", content, author: { name, nick: name }, user: { name, nick: name } }]).replace(/"tweet_id":"(\\d+)"/, '"tweet_id":$1');
+console.log(tweet("1700000000000000077", "synthbaker", "The second shop opens in the spring."));
+console.log(tweet("1700000000000000066", "someoneelse", "a quoted post"));
+`,
+ { mode: 0o755 },
+);
+process.env.GALLERY_DL_BIN = FAKE_BIN;
+
+const channel = (slug: string, config: Record<string, unknown>) => {
+ mkdirSync(path.join(ROOT, "channels", slug), { recursive: true });
+ writeFileSync(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config));
+};
+channel("synth-social", { name: "Synth (X)", handling: "transcribe", sourceKind: "social", url: "https://x.com/synthbaker", postFetcher: "fake-x" });
+channel("synth-sky", { name: "Synth (Bluesky)", handling: "transcribe", sourceKind: "social", url: "https://bsky.app/profile/synthbaker.bsky.social", postFetcher: "fake-bsky" });
+channel("synth-kitchen", { name: "Synth Kitchen", handling: "youtube", url: "https://video.example/@synth-kitchen" });
+
+const { getPaths } = await import("../lib/paths");
+const { readAllPosts } = await import("../lib/posts-server");
+const { parsePostUrl } = await import("./fetchers");
+const { importPost, planImportPost, NOT_A_POST_URL } = await import("./importPost");
+const { xGalleryDlFetcher } = await import("./xGalleryDlFetcher");
+const { readFileSync } = await import("node:fs");
+type Fetcher = import("./fetchers").SocialFetcher;
+
+const paths = getPaths();
+
+const post = (id: string, author: string, platform: Post["platform"] = "twitter"): Post => ({
+ id,
+ slug: `synth-social/${id}`,
+ channelSlug: "synth-social",
+ author,
+ createdAt: "2026-02-11T12:00:00.000Z",
+ uploadDate: "20260211",
+ text: "No, I did not enter the pie contest.",
+ url: `https://x.com/${author}/status/${id}`,
+ platform,
+ isReply: false,
+ isRepost: false,
+ links: [],
+});
+
+function fakeFetcher(platform: "twitter" | "bluesky", answer: (id: string) => Post | null, one = true) {
+ const asked: string[] = [];
+ const f: Fetcher = {
+ id: `fake-${platform}`,
+ label: `Fake ${platform}`,
+ platform,
+ detect: () => false,
+ fields: {},
+ probe: async () => ({ ok: true }),
+ fetch: async () => ({ posts: [], complete: true }),
+ ...(one
+ ? {
+ fetchOne: async ({ post: ref }) => {
+ asked.push(ref.url);
+ return { post: answer(ref.id) };
+ },
+ }
+ : {}),
+ };
+ return { f, asked };
+}
+
+test("post URLs: X statuses and Bluesky posts, nothing else", () => {
+ assert.deepEqual(parsePostUrl("https://twitter.com/SynthBaker/status/1700000000000000001?s=20"), {
+ platform: "twitter",
+ id: "1700000000000000001",
+ handle: "SynthBaker",
+ url: "https://x.com/SynthBaker/status/1700000000000000001",
+ });
+ assert.deepEqual(parsePostUrl("https://x.com/i/web/status/17"), { platform: "twitter", id: "17", url: "https://x.com/i/web/status/17" });
+ assert.deepEqual(parsePostUrl("https://bsky.app/profile/synthbaker.bsky.social/post/3kabc"), {
+ platform: "bluesky",
+ id: "3kabc",
+ actor: "synthbaker.bsky.social",
+ url: "https://bsky.app/profile/synthbaker.bsky.social/post/3kabc",
+ });
+ assert.equal(parsePostUrl("at://did:plc:abc/app.bsky.feed.post/3kxyz")?.platform, "bluesky");
+ for (const bad of ["https://x.com/synthbaker", "https://x.com/a/status/notanid", "https://video.example/v/1", "nonsense"]) {
+ assert.equal(parsePostUrl(bad), null, bad);
+ }
+});
+
+test("refused before any read: not a post URL, not a posts channel, another platform's channel, another account's post, a fetcher that cannot", async () => {
+ const { f: x, asked } = fakeFetcher("twitter", () => null);
+ const { f: noOne } = fakeFetcher("twitter", () => null, false);
+ const plan = (slug: string, url: string, fetcher = x) => planImportPost(paths, slug, url, { fetcherFor: () => fetcher });
+ assert.deepEqual(await plan("synth-social", "https://video.example/v/1"), { ok: false, error: NOT_A_POST_URL });
+ assert.match((await plan("synth-kitchen", "https://x.com/synthbaker/status/1") as { error: string }).error, /synth-kitchen is not a posts channel/);
+ assert.match((await plan("nope", "https://x.com/synthbaker/status/1") as { error: string }).error, /No such channel: nope/);
+ assert.match(
+ (await plan("synth-social", "https://bsky.app/profile/synthbaker.bsky.social/post/3kabc") as { error: string }).error,
+ /synth-social is an X posts channel, not a Bluesky one: import a Bluesky post into a Bluesky channel/,
+ );
+ assert.match((await plan("synth-social", "https://x.com/someoneelse/status/1") as { error: string }).error, /the post is @someoneelse's; synth-social archives @synthbaker's posts/);
+ assert.match((await plan("synth-social", "https://x.com/synthbaker/status/1", noOne) as { error: string }).error, /cannot import one post/);
+ assert.equal((await plan("synth-social", "https://x.com/SYNTHBAKER/status/1")).ok, true, "handles compare without case");
+ assert.deepEqual(asked, []);
+});
+
+test("an X post: read through the channel's fetcher and written to its archive; a second import reads nothing", async () => {
+ const { f, asked } = fakeFetcher("twitter", (id) => post(id, "synthbaker"));
+ const logs: string[] = [];
+ const r = await importPost({
+ paths,
+ slug: "synth-social",
+ url: "https://x.com/synthbaker/status/1700000000000000001",
+ settings: {},
+ onLog: (l) => logs.push(l),
+ fetcherFor: () => f,
+ });
+ assert.equal(r.ok, true, r.error);
+ assert.equal(r.written, 1);
+ assert.deepEqual(r.post, { id: "1700000000000000001", url: "https://x.com/synthbaker/status/1700000000000000001", author: "synthbaker", createdAt: "2026-02-11T12:00:00.000Z" });
+ assert.deepEqual(asked, ["https://x.com/synthbaker/status/1700000000000000001"]);
+ const archived = await readAllPosts(path.join(ROOT, "channels", "synth-social"));
+ assert.deepEqual(archived.map((p) => p.id), ["1700000000000000001"]);
+ const again = await importPost({ paths, slug: "synth-social", url: "https://x.com/synthbaker/status/1700000000000000001", settings: {}, fetcherFor: () => f });
+ assert.equal(again.already, true);
+ assert.equal(asked.length, 1, "not read again");
+});
+
+test("an X status URL with no handle: the post's author is checked after the read, and another account's is not written", async () => {
+ const { f } = fakeFetcher("twitter", (id) => post(id, "someoneelse"));
+ const r = await importPost({ paths, slug: "synth-social", url: "https://x.com/i/web/status/1700000000000000009", settings: {}, fetcherFor: () => f });
+ assert.equal(r.ok, false);
+ assert.match(r.error!, /the post is @someoneelse's; synth-social archives @synthbaker's posts — nothing written/);
+ const archived = await readAllPosts(path.join(ROOT, "channels", "synth-social"));
+ assert.ok(!archived.some((p) => p.id === "1700000000000000009"));
+});
+
+test("a post the platform does not have is a failure, in words", async () => {
+ const { f } = fakeFetcher("bluesky", () => null);
+ const r = await importPost({ paths, slug: "synth-sky", url: "https://bsky.app/profile/synthbaker.bsky.social/post/3kgone", settings: {}, fetcherFor: () => f });
+ assert.equal(r.ok, false);
+ assert.match(r.error!, /no post 3kgone/);
+});
+
+test("X through gallery-dl: the status URL is what it reads, and the one post it names is picked out of what it printed", async () => {
+ const ref = parsePostUrl("https://x.com/synthbaker/status/1700000000000000077")!;
+ const r = await xGalleryDlFetcher.fetchOne!({ post: ref, channelSlug: "synth-social", signal: new AbortController().signal });
+ assert.equal(r.error, undefined);
+ assert.equal(r.post?.id, "1700000000000000077");
+ assert.equal(r.post?.author, "synthbaker");
+ assert.equal(r.post?.text, "The second shop opens in the spring.");
+ const argv = JSON.parse(readFileSync(ARGV_FILE, "utf8")) as string[];
+ assert.equal(argv[argv.length - 1], "https://x.com/synthbaker/status/1700000000000000077");
+ assert.ok(argv.includes("--no-download"), "metadata only");
+ // And through the import, on a channel whose fetcher is gallery-dl's.
+ channel("synth-gdl", { name: "Synth (X)", handling: "transcribe", sourceKind: "social", url: "https://x.com/synthbaker" });
+ const imp = await importPost({ paths, slug: "synth-gdl", url: "https://x.com/synthbaker/status/1700000000000000077", settings: {} });
+ assert.equal(imp.ok, true, imp.error);
+ const archived = await readAllPosts(path.join(ROOT, "channels", "synth-gdl"));
+ assert.deepEqual(archived.map((p) => p.id), ["1700000000000000077"], "the quoted post is not written");
+});
diff --git a/common/social/importPost.ts b/common/social/importPost.ts
@@ -0,0 +1,165 @@
+// IMPORT ONE POST (release 27 S3b, the editor's `import-post`): one X status
+// or one Bluesky post, by its URL, into the posts archive of a channel that
+// archives THAT account on THAT platform — through the channel's own fetcher
+// (`SocialFetcher.fetchOne`: gallery-dl on the status URL for X, the public
+// AppView for Bluesky), with the channel's login, written as a fetch writes
+// (lib/posts-server.ts writePosts: the month shards and the posts archive).
+//
+// Refused before any request, with the sentence a caller shows:
+// - a URL that is not an X status or a Bluesky post;
+// - no such channel, or one that is not a posts channel;
+// - a posts channel of another platform, or whose fetcher cannot read one
+// post;
+// - a post the URL names as another account's (and, after the read, one the
+// platform says is another account's);
+// - the platform held or cooling down after a rate limit (the same holds a
+// manual download respects) — polite, and the editor runs the read on the
+// platform's queue, so it never runs beside a fetch of the same source.
+// A post already archived is not read again.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Post } from "../lib/posts";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { isSocialChannel } from "../lib/channelConfig";
+import { readChannelConfig } from "../controller/channels";
+import { alwaysCookies, resolveCookiePolicy, type CookiePolicyInputs } from "../lib/cookiePolicy";
+import { readSeenPostIds, writePosts } from "../lib/posts-server";
+import { heldPlatformRefusal, platformCooldownRemainingMs } from "../jobs/downloadBackoff";
+import {
+ handleFromAccountUrl,
+ parsePostUrl,
+ resolveSocialFetcher,
+ type PostUrlRef,
+ type SocialFetcher,
+} from "./fetchers";
+import { resolveXCookieSourceFor, type XLoginSettings } from "./xBrowserLogin";
+// The built-in fetchers register themselves on import, in fetchPosts' order.
+import "./blueskyFetcher";
+import "./xGalleryDlFetcher";
+import "./xPlaywrightFetcher";
+import "./xNitterFetcher";
+import "./xenforoFetcher";
+
+export const IMPORT_POST_RESULT_MARKER = "@@import-post ";
+
+export const NOT_A_POST_URL =
+ "not a post URL: give an X status (https://x.com/<handle>/status/<id>) or a Bluesky post " +
+ "(https://bsky.app/profile/<handle>/post/<id>, or its at:// URI)";
+
+const PLATFORM_LABEL: Record<string, string> = { twitter: "X", bluesky: "Bluesky", xenforo: "forum" };
+
+export type ImportPostPlan = {
+ config: ChannelConfig;
+ fetcher: SocialFetcher;
+ ref: PostUrlRef;
+ handle: string;
+};
+
+const sameAccount = (a: string, b: string) => a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase();
+
+// Everything checked before a job: the plan, or the refusal. `fetcherFor`
+// is injectable for tests (default: the channel's own, as a fetch resolves it).
+export async function planImportPost(
+ paths: Paths,
+ slug: string,
+ url: string,
+ opts: { fetcherFor?: (config: ChannelConfig) => SocialFetcher | undefined } = {},
+): Promise<{ ok: true; plan: ImportPostPlan } | { ok: false; error: string; info?: boolean }> {
+ const ref = parsePostUrl(url);
+ if (!ref) return { ok: false, error: NOT_A_POST_URL };
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `No such channel: ${slug}` };
+ if (!isSocialChannel(config)) {
+ return { ok: false, error: `${slug} is not a posts channel; import-post imports into a channel that archives an account's posts` };
+ }
+ const fetcher = (opts.fetcherFor ?? ((c) => resolveSocialFetcher(c.postFetcher, c.url)))(config);
+ if (!fetcher) return { ok: false, error: `${slug} has no post fetcher` };
+ const want = PLATFORM_LABEL[ref.platform] ?? ref.platform;
+ const have = PLATFORM_LABEL[fetcher.platform] ?? fetcher.platform;
+ const an = (w: string) => `${/^[aeiox]/i.test(w) ? "an" : "a"} ${w}`;
+ if (fetcher.platform !== ref.platform) {
+ return {
+ ok: false,
+ error: `${slug} is ${an(have)} posts channel, not ${an(want)} one: import ${an(want)} post into ${an(want)} channel`,
+ };
+ }
+ if (!fetcher.fetchOne) return { ok: false, error: `${slug}'s fetcher (${fetcher.label}) cannot import one post` };
+ const handle = config.socialHandle ?? handleFromAccountUrl(config.url ?? "") ?? "";
+ if (!handle) return { ok: false, error: `Could not determine an account handle for ${slug}` };
+ const named = ref.platform === "twitter" ? ref.handle : ref.actor.startsWith("did:") ? undefined : ref.actor;
+ if (named && !sameAccount(named, handle)) {
+ return { ok: false, error: `the post is @${named}'s; ${slug} archives @${handle}'s posts` };
+ }
+ return { ok: true, plan: { config, fetcher, ref, handle } };
+}
+
+// The platform's hold or cooldown, as a manual download meets it, or null.
+export async function importPostHeld(paths: Paths, platform: string): Promise<string | null> {
+ const held = await heldPlatformRefusal(platform, "This post import", paths);
+ if (held) return held;
+ const ms = await platformCooldownRemainingMs(platform, paths);
+ return ms > 0
+ ? `${platform} is in a rate-limit cooldown (${Math.ceil(ms / 1000)}s remaining); the post import will run once it ends`
+ : null;
+}
+
+export type ImportPostResult = {
+ ok: boolean;
+ slug: string;
+ url: string;
+ id: string;
+ written: number;
+ // The post was already in the archive; nothing was read.
+ already?: boolean;
+ post?: Pick<Post, "id" | "url" | "author" | "createdAt">;
+ needsCookies?: boolean;
+ error?: string;
+};
+
+export async function importPost(opts: {
+ paths: Paths;
+ slug: string;
+ url: string;
+ settings: CookiePolicyInputs & XLoginSettings;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ fetcherFor?: (config: ChannelConfig) => SocialFetcher | undefined;
+}): Promise<ImportPostResult> {
+ const log = (line: string) => opts.onLog?.(line);
+ const planned = await planImportPost(opts.paths, opts.slug, opts.url, opts.fetcherFor ? { fetcherFor: opts.fetcherFor } : {});
+ const base = { slug: opts.slug, url: opts.url, id: parsePostUrl(opts.url)?.id ?? "", written: 0 };
+ if (!planned.ok) return { ...base, ok: false, error: planned.error };
+ const { config, fetcher, ref, handle } = planned.plan;
+ const channelRoot = path.join(opts.paths.channelsDir, opts.slug);
+ if ((await readSeenPostIds(channelRoot)).has(ref.id)) {
+ log(`Post ${ref.id} is already in ${opts.slug}'s archive; nothing to read.`);
+ return { ...base, ok: true, already: true };
+ }
+ const policy = resolveCookiePolicy(opts.settings, config);
+ const xLogin =
+ fetcher.platform === "twitter" ? await resolveXCookieSourceFor(opts.paths, opts.settings, policy.cookies) : undefined;
+ log(`Reading ${ref.url} via ${fetcher.label} for ${opts.slug} (@${handle}).`);
+ const res = await fetcher.fetchOne!({
+ post: ref,
+ channelSlug: opts.slug,
+ signal: opts.signal ?? new AbortController().signal,
+ onLog: log,
+ ...(alwaysCookies(policy) !== undefined ? { cookies: alwaysCookies(policy) } : {}),
+ ...(xLogin?.source ? { cookieSource: xLogin.source } : {}),
+ ...(xLogin?.browserSpec ? { browserCookies: xLogin.browserSpec } : {}),
+ });
+ if (res.needsCookies) return { ...base, ok: false, needsCookies: true, error: res.error ?? `${fetcher.label} needs a login to read the post` };
+ if (!res.post) return { ...base, ok: false, error: res.error ?? `the platform has no post ${ref.id} (deleted, private, or never there)` };
+ if (!sameAccount(res.post.author, handle)) {
+ return { ...base, ok: false, error: `the post is @${res.post.author}'s; ${opts.slug} archives @${handle}'s posts — nothing written` };
+ }
+ const w = await writePosts(channelRoot, [res.post]);
+ log(`Wrote ${w.written} post(s) to ${opts.slug}'s archive.`);
+ return {
+ ...base,
+ ok: true,
+ written: w.written,
+ post: { id: res.post.id, url: res.post.url, author: res.post.author, createdAt: res.post.createdAt },
+ };
+}
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -57,6 +57,8 @@ import {
type PostFetchResult,
type SocialFetcher,
type SocialFetcherProbe,
+ type OnePostFetchInput,
+ type OnePostFetchResult,
} from "./fetchers";
// Substrings in gallery-dl's stderr that mean "we are not authenticated" (or no
@@ -1347,4 +1349,30 @@ export const xGalleryDlFetcher: SocialFetcher = {
captureByIds: captureXPostsByIds,
};
+// ONE post by its URL (release 27 S3b, import-post): the timeline read run on
+// the status URL — gallery-dl's tweet extractor — with the same login, pacing
+// and output parsing, and the one post it names picked out of what it read
+// (a status read can also emit the post it quotes).
+xGalleryDlFetcher.fetchOne = async (input: OnePostFetchInput): Promise<OnePostFetchResult> => {
+ if (input.post.platform !== "twitter") return { post: null, error: "not an X post" };
+ const res = await xGalleryDlFetcher.fetch({
+ accountUrl: input.post.url,
+ handle: input.post.handle ?? "",
+ channelSlug: input.channelSlug,
+ seenIds: new Set(),
+ stopAtKnown: false,
+ signal: input.signal,
+ ...(input.cookies !== undefined ? { cookies: input.cookies } : {}),
+ ...(input.cookieSource !== undefined ? { cookieSource: input.cookieSource } : {}),
+ ...(input.browserCookies !== undefined ? { browserCookies: input.browserCookies } : {}),
+ ...(input.onLog ? { onLog: input.onLog } : {}),
+ });
+ const post = res.posts.find((p) => p.id === input.post.id) ?? null;
+ return {
+ post,
+ ...(res.needsCookies ? { needsCookies: true } : {}),
+ ...(res.error ? { error: res.error } : {}),
+ };
+};
+
registerSocialFetcher(xGalleryDlFetcher);
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -16,6 +16,8 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/corpus.mjs` | Two channels of recordings with cues (`CHANNELS`), posts (`POSTS`), `ORIGIN`, `momentHref`, `postHref`, `cuesOf`, `recordOf`, and `writeDraftCorpus(dir)` — a composed public dir for the MCP's `--local`. |
| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one). |
| `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. |
+| `web/fakeWeb.mjs` | A fake web on loopback: a DuckDuckGo-shaped HTML search (`POST /html/`, links in the `uddg` redirect, an ad), pages, plain text, a long page, redirects and a redirect loop, a PDF, a 429 that clears (`busyTimes`), a 503 that does not. `web.searchUrl` is what `webSearch` takes. |
+| `archiveOrg/fakeArchiveOrg.mjs` | A fake archive.org on loopback: `/advancedsearch.php` (every word of `q` in an item's identifier, title or subject; `*` all) and `/metadata/<id>` over invented items (`ITEMS`: a show's episodes with an original, a derivative and a JSON file, a restricted item, an audio tape). `ia.fetch` sends `https://archive.org/…` to it, for `new ArchiveOrgClient({ fetch: ia.fetch })`; `busyTimes` answers 429 first. |
| `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. |
As committed at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and
diff --git a/common/testing/archiveOrg/fakeArchiveOrg.d.mts b/common/testing/archiveOrg/fakeArchiveOrg.d.mts
@@ -0,0 +1,15 @@
+export type FakeArchiveOrgItem = {
+ metadata: { identifier: string } & Record<string, unknown>;
+ files: ({ name: string } & Record<string, unknown>)[];
+};
+
+export const ITEMS: FakeArchiveOrgItem[];
+
+export type FakeArchiveOrg = {
+ base: string;
+ requests: string[];
+ fetch(url: string, init: RequestInit): Promise<Response>;
+ close(): Promise<void>;
+};
+
+export function startFakeArchiveOrg(opts?: { items?: FakeArchiveOrgItem[]; busyTimes?: number }): Promise<FakeArchiveOrg>;
diff --git a/common/testing/archiveOrg/fakeArchiveOrg.mjs b/common/testing/archiveOrg/fakeArchiveOrg.mjs
@@ -0,0 +1,119 @@
+// A fake archive.org for the research tests (release 27 S3b): the advanced
+// search and the item metadata API, on loopback, over invented items. No test
+// talks to archive.org.
+//
+// const ia = await startFakeArchiveOrg(); // ITEMS below, or opts.items
+// new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 })
+// ia.requests every request path, in order
+// await ia.close()
+//
+// `ia.fetch` is a fetch that sends https://archive.org/… to the fake instead,
+// so the real client (its gap, its retries, its URLs) is what is tested.
+//
+// Routes:
+// GET /advancedsearch.php?q=…&rows=N items whose identifier, title or
+// subject contains every word of q
+// (`*` matches all), identifier order
+// GET /metadata/<id> the item, or {} (archive.org's answer
+// for an unknown id)
+// opts.busyTimes the first N requests answer 429
+
+import http from "node:http";
+
+// Invented items: a kitchen show's episodes, a restricted one, an audio tape.
+export const ITEMS = [
+ {
+ metadata: {
+ identifier: "synth-kitchen-episodes-2026",
+ title: "Synth Kitchen — episodes, spring 2026",
+ date: "2026-04-01",
+ mediatype: "movies",
+ collection: ["opensource_movies"],
+ creator: "Synth Kitchen",
+ subject: ["baking", "bakery"],
+ },
+ files: [
+ { name: "Bread day.mp4", source: "original", format: "MPEG4", size: "104857600", length: "70.0" },
+ { name: "Pie stream.mkv", source: "original", format: "Matroska", size: "209715200", length: "02:00" },
+ { name: "Pie stream.mp4", source: "derivative", format: "h.264", original: "Pie stream.mkv", size: "50000000" },
+ { name: "Bread day.info.json", source: "original", format: "JSON", size: "2048" },
+ { name: "synth-kitchen-episodes-2026_meta.xml", source: "metadata", format: "Metadata", size: "900" },
+ ],
+ },
+ {
+ metadata: {
+ identifier: "synth-kitchen-restricted",
+ title: "Synth Kitchen — members stream",
+ mediatype: "movies",
+ collection: "opensource_movies",
+ "access-restricted-item": "true",
+ },
+ files: [{ name: "members.mp4", source: "original", format: "MPEG4", size: "5000" }],
+ },
+ {
+ metadata: {
+ identifier: "synth-radio-tape-01",
+ title: "Synth radio — the bakery call-in",
+ date: "2025-11-02",
+ mediatype: "audio",
+ collection: ["opensource_audio"],
+ subject: "bakery",
+ },
+ files: [
+ { name: "tape1.flac", source: "original", format: "Flac", size: "300000000", length: "3600" },
+ { name: "tape1.mp3", source: "derivative", format: "VBR MP3", original: "tape1.flac", size: "60000000" },
+ ],
+ },
+];
+
+const words = (s) => String(s ?? "").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
+const flat = (v) => (Array.isArray(v) ? v.join(" ") : (v ?? ""));
+
+export async function startFakeArchiveOrg(opts = {}) {
+ const items = opts.items ?? ITEMS;
+ const requests = [];
+ let busy = opts.busyTimes ?? 0;
+ const server = http.createServer((req, res) => {
+ const u = new URL(req.url ?? "/", "http://fake");
+ requests.push(u.pathname + u.search);
+ const json = (status, body, headers = {}) => {
+ res.writeHead(status, { "content-type": "application/json", ...headers });
+ res.end(JSON.stringify(body));
+ };
+ if (busy > 0) {
+ busy--;
+ return json(429, { error: "slow down" }, { "retry-after": "1" });
+ }
+ if (u.pathname === "/advancedsearch.php") {
+ const q = u.searchParams.get("q") ?? "";
+ const rows = Number(u.searchParams.get("rows") ?? 50);
+ const want = q.trim() === "*" ? [] : words(q);
+ const hits = items
+ .filter((it) => {
+ const hay = new Set(words(`${it.metadata.identifier} ${flat(it.metadata.title)} ${flat(it.metadata.subject)}`));
+ return want.every((w) => hay.has(w));
+ })
+ .sort((a, b) => a.metadata.identifier.localeCompare(b.metadata.identifier));
+ return json(200, {
+ response: {
+ numFound: hits.length,
+ docs: hits.slice(0, rows).map((it) => ({ identifier: it.metadata.identifier, title: it.metadata.title })),
+ },
+ });
+ }
+ const m = /^\/metadata\/([^/]+)$/.exec(u.pathname);
+ if (m) {
+ const it = items.find((x) => x.metadata.identifier === decodeURIComponent(m[1]));
+ return json(200, it ?? {});
+ }
+ return json(404, { error: "not found" });
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return {
+ base,
+ requests,
+ fetch: (url, init) => fetch(String(url).replace(/^https:\/\/archive\.org/, base), init),
+ close: () => new Promise((r) => server.close(() => r())),
+ };
+}
diff --git a/common/testing/web/fakeWeb.d.mts b/common/testing/web/fakeWeb.d.mts
@@ -0,0 +1,17 @@
+export type FakeSearchResult = { title: string; url: string; snippet?: string };
+
+export function duckDuckGoHtml(results: FakeSearchResult[]): string;
+
+export type FakeWeb = {
+ base: string;
+ searchUrl: string;
+ url(path: string): string;
+ requests: { method: string; path: string; body: string; at: number; ua?: string }[];
+ close(): Promise<void>;
+};
+
+export function startFakeWeb(opts?: {
+ results?: Record<string, FakeSearchResult[]>;
+ pages?: Record<string, string>;
+ busyTimes?: number;
+}): Promise<FakeWeb>;
diff --git a/common/testing/web/fakeWeb.mjs b/common/testing/web/fakeWeb.mjs
@@ -0,0 +1,93 @@
+// A fake web for the generation tests (release 27 D7): a DuckDuckGo-shaped
+// HTML search page and a few pages, on loopback. No test reaches the real web.
+//
+// const web = await startFakeWeb({ results: { oven: [{ title, url, snippet }] } });
+// web.searchUrl POST q=… here (the endpoint webSearch takes)
+// web.url("/page/a") a page on the fake
+// web.requests every request: { method, path, body, at }
+// await web.close()
+//
+// Routes:
+// POST /html/ results for the form's `q` (opts.results[q], else
+// the `*` entry, else none), each link wrapped in
+// DuckDuckGo's /l/?uddg= redirect, plus one ad
+// GET /page/<name> opts.pages[name] as text/html (a default page)
+// GET /text a plain-text page
+// GET /long a page longer than any default cut
+// GET /redirect?to=<u> 302 to <u>
+// GET /loop 302 to itself
+// GET /pdf application/pdf
+// GET /busy 429 (Retry-After: 1) for the first opts.busyTimes
+// requests (default 1), then a page
+// GET /down 503 always
+
+import http from "node:http";
+
+const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
+
+export function duckDuckGoHtml(results) {
+ const items = results
+ .map(
+ (r) => `<div class="result results_links web-result"><div class="links_main result__body">
+<h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=${encodeURIComponent(r.url)}&rut=abc">${esc(r.title)}</a></h2>
+<a class="result__snippet" href="//duckduckgo.com/l/?uddg=${encodeURIComponent(r.url)}">${r.snippet ?? ""}</a>
+</div></div>`,
+ )
+ .join("\n");
+ const ad = `<div class="result result--ad"><a class="result__a" href="https://duckduckgo.com/y.js?ad_provider=x&u3=1">An ad</a></div>`;
+ return `<!doctype html><html><head><title>results</title></head><body>${ad}\n${items}</body></html>`;
+}
+
+const DEFAULT_PAGE = `<!doctype html><html><head><title>The bakery & the oven</title>
+<style>body{color:red}</style><script>var tracking = "do not read me";</script></head>
+<body><nav>Home | About</nav><h1>The bakery</h1><p>The second shop opened in the spring.</p>
+<p>It is a small place with a big oven.</p><ul><li>bread</li><li>pies</li></ul><footer>footer text</footer></body></html>`;
+
+export async function startFakeWeb(opts = {}) {
+ const requests = [];
+ let busy = opts.busyTimes ?? 1;
+ const server = http.createServer(async (req, res) => {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const body = Buffer.concat(chunks).toString("utf8");
+ const u = new URL(req.url ?? "/", "http://fake");
+ requests.push({ method: req.method, path: u.pathname + u.search, body, at: Date.now(), ua: req.headers["user-agent"] });
+ const send = (status, type, text, headers = {}) => {
+ res.writeHead(status, { "content-type": type, ...headers });
+ res.end(text);
+ };
+ if (u.pathname === "/html/" && req.method === "POST") {
+ const q = new URLSearchParams(body).get("q") ?? "";
+ const results = (opts.results ?? {})[q] ?? (opts.results ?? {})["*"] ?? [];
+ return send(200, "text/html; charset=utf-8", duckDuckGoHtml(results));
+ }
+ if (u.pathname.startsWith("/page/")) {
+ const name = decodeURIComponent(u.pathname.slice(6));
+ return send(200, "text/html; charset=utf-8", (opts.pages ?? {})[name] ?? DEFAULT_PAGE);
+ }
+ if (u.pathname === "/text") return send(200, "text/plain", "plain words\r\nsecond line\n");
+ if (u.pathname === "/long") return send(200, "text/html", `<p>${"word ".repeat(30000)}</p>`);
+ if (u.pathname === "/redirect") return send(302, "text/plain", "", { location: u.searchParams.get("to") ?? "/page/a" });
+ if (u.pathname === "/loop") return send(302, "text/plain", "", { location: "/loop" });
+ if (u.pathname === "/pdf") return send(200, "application/pdf", "%PDF-1.4");
+ if (u.pathname === "/busy") {
+ if (busy > 0) {
+ busy--;
+ return send(429, "text/plain", "slow down", { "retry-after": "1" });
+ }
+ return send(200, "text/html", DEFAULT_PAGE);
+ }
+ if (u.pathname === "/down") return send(503, "text/plain", "down");
+ return send(404, "text/plain", "not found");
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const port = server.address().port;
+ const base = `http://127.0.0.1:${port}`;
+ return {
+ base,
+ searchUrl: `${base}/html/`,
+ url: (p) => `${base}${p}`,
+ requests,
+ close: () => new Promise((r) => server.close(() => r())),
+ };
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -6,6 +6,10 @@
- **A report video made by `reports to-manifest` no longer shows "undefined" under its title or ends on a silent card.** The title card now has an empty third line (and a manifest made before this renders one too), and a section with nothing to show — a trailing Coverage note, a section of posts only — gets no chapter card; the article keeps the section.
- **`umtool build <project> --dry` names the real pipeline directory wherever it is run from** (it printed `<cwd>/report-to-video`).
- **`archilyzer reports iterations <id> [--json]` lists an article's iterations.** Release 27 keeps each generation of an article (a sweep, a revision of its report or its video, a research run) as an ITERATION under `transcripts/reports/<id>/iterations/<n>/`, with its kind, model, status, cost, parent and the iteration it copies; the command lists them with their lineage (`i1 › i3 › i4`), and marks the current article and the current video. Iterations are never published: compose, an article's history and the homepage ignore them, and an article whose only content is iterations (no report.json yet) is not listed anywhere until one of them is made current.
+- **Import one post by its URL.** `pnpm ops import-post --json '{"slug", "url"}'` imports one X status or one Bluesky post into a posts channel of that platform that archives that account, as an `import-post` job on the platform's queue, through the channel's own fetcher (gallery-dl with the channel's X login; the public Bluesky API). It is refused before any job when the URL is not a post, when the channel is not a posts channel of that platform (or its fetcher cannot read one post), when the post is another account's, or while the platform is held or cooling down after a rate limit. A post already archived is not read again. Needs a restart of the editor.
+- **archive.org from the command line, read only.** `pnpm ops archive-search --json '{"query", "limit"?}'` answers the items an archive.org search finds, and `pnpm ops archive-item --json '{"item"}'` one item's files with their sizes, formats and lengths, which are the media an import would take, and what archive.org restricts. Both go through the editor's archive.org client, paced like an import, and download nothing. Needs a restart of the editor.
+- **`pnpm ops web-search` and `pnpm ops web-fetch` read the web, politely.** `web-search` (`{"query", "n"?}`) answers DuckDuckGo's results as titles, links and snippets; `web-fetch` (`{"url", "maxChars"?}`) answers one page as plain text. Both are read only and go through one queue in the editor: one request at a time, three seconds apart, backing off when a site answers 429 or 503. A page on a private or local address (`localhost`, `192.168.…`, a name that resolves to one) is refused before anything is sent, and so is a file that is not a page (a PDF, an image). Needs a restart of the editor.
+- **`archilyzer reports verify-quotes` flags an inexact quote.** A quote that passes the usual check but whose words are not, word for word, in the transcript within 90 seconds of its cited second — a word dropped that reverses its meaning, a quote from another moment — is now reported as `INEXACT (warning)`, with the first fragment that was not found. It is a warning: it is counted in the summary line and does not change the exit code; compose and publish are unchanged. Quotes a model writes in release 27's generation are held to it.
- **Orpheus speaks as the operator picked by ear: zac, calmer, quicker, in longer runs.** The default Orpheus voice is now `zac` (leah stays available); the sampler is cooler (temperature 0.55, top_p 0.85) and its repeat penalty higher (1.2), which reads less acted and less over-enunciated; a chunk holds up to 5 sentences and 420 characters, with shorter joins (0.2 s after a sentence, 0.1 s after a clause, 0.4 s after a paragraph), so the voice restarts its phrasing less often; and a very short line gets at least four seconds of budget, so it can no longer fail every take. Orpheus narration made before this is made again the next time it is asked for. Needs a restart of the editor.
- **A site's reports are its pages.** site.json `reports` is now `pages` (a file that still says `reports` reads as `pages` for this release; saving writes `pages`). Each page is served at `/pages/<id>/` and linked from the site's header by its title, after Ask AI; there is no Reports index any more. A site with search off shows its first page as its home, and saving a site with search off and no pages is refused. The site form lists them as **Pages**. Rebuild each site that has pages.
- **Site ids `articles` and `new` are refused.** The editor's `/sites/articles` and `/sites/new` (and umtool's `articles/`) would hide a site of either name, so a save under one is refused, naming why.
diff --git a/editor/app/api/ops/_corpusTools.test.ts b/editor/app/api/ops/_corpusTools.test.ts
@@ -0,0 +1,26 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_corpusTools.test.ts"
+//
+// The MCP's corpus tools are importable from the editor (release 27 S3, D2):
+// the package export resolves and the tools answer over a synthetic corpus.
+// The generation jobs (S6) run them in this process.
+
+test("the editor imports the MCP's in-process corpus tools", async () => {
+ const dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "editor-corpus-tools-")));
+ const corpus = await createCorpusTools({ source: `local:${dir}` });
+ try {
+ assert.ok(corpus.tools.some((t) => t.name === "search_transcripts"));
+ assert.match(await corpus.call("list_channels"), /synth-kitchen/);
+ } finally {
+ await corpus.close();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/editor/app/api/ops/_research.test.ts b/editor/app/api/ops/_research.test.ts
@@ -0,0 +1,52 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { callPost, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_research.test.ts"
+//
+// The research actions (release 27 S3b): archive-search, archive-item and
+// import-post, refused at the door before anything reaches archive.org or a
+// platform. The reads and the import themselves are tested in common
+// (controller/archiveOrgResearch.test.ts, social/importPost.test.ts).
+
+const corpus = await setupOpsCorpus("one-youtube-channel-with-data");
+type Post = Parameters<typeof callPost>[0];
+const route = async (name: string) => (await import(`./${name}/route`)).POST as Post;
+test.after(() => corpus.cleanup());
+
+test("archive-search: a query is required; the limit is at most 500", async () => {
+ const search = await route("archive-search");
+ const none = await callPost(search, {});
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /"query" is required/);
+ const big = await callPost(search, { query: "bakery", limit: 501 });
+ assert.equal(big.status, 400);
+ assert.match(String(big.body.error), /"limit" is at most 500/);
+});
+
+test("archive-item: an identifier, nothing else", async () => {
+ const item = await route("archive-item");
+ const bad = await callPost(item, { item: "../../etc" });
+ assert.equal(bad.status, 400);
+ assert.match(String(bad.body.error), /is not an archive\.org identifier/);
+ const extra = await callPost(item, { item: "x", files: [] });
+ assert.equal(extra.status, 400);
+});
+
+test("import-post: refused before any job — not a post URL, not a posts channel, no such channel", async () => {
+ const imp = await route("import-post");
+ const before = await corpus.listJobIds();
+ const notPost = await callPost(imp, { slug: "test-youtube", url: "https://video.example/v/1" });
+ assert.equal(notPost.status, 400);
+ assert.match(String(notPost.body.error), /not a post URL/);
+ const video = await callPost(imp, { slug: "test-youtube", url: "https://x.com/synthbaker/status/1" });
+ assert.equal(video.status, 400);
+ assert.match(String(video.body.error), /test-youtube is not a posts channel/);
+ const missing = await callPost(imp, { slug: "no-such-channel", url: "https://x.com/synthbaker/status/1" });
+ assert.equal(missing.status, 400);
+ assert.match(String(missing.body.error), /No such channel/);
+ const noUrl = await callPost(imp, { slug: "test-youtube" });
+ assert.equal(noUrl.status, 400);
+ assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued");
+});
diff --git a/editor/app/api/ops/_web.test.ts b/editor/app/api/ops/_web.test.ts
@@ -0,0 +1,46 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { callPost, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_web.test.ts"
+//
+// web-search and web-fetch (release 27 S3): the refusals answered before any
+// request leaves the machine. The reads themselves are tested against a fake
+// web in common/lib/web/web.test.ts.
+
+const corpus = await setupOpsCorpus(null);
+type Post = Parameters<typeof callPost>[0];
+const route = async (name: string) => (await import(`./${name}/route`)).POST as Post;
+test.after(() => corpus.cleanup());
+
+test("web-search: the query is required, n a whole number, unknown keys refused", async () => {
+ const search = await route("web-search");
+ const none = await callPost(search, {});
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /"query" is required/);
+ const badN = await callPost(search, { query: "x", n: 0 });
+ assert.equal(badN.status, 400);
+ assert.match(String(badN.body.error), /"n" must be a whole number above zero/);
+ const extra = await callPost(search, { query: "x", searchUrl: "http://127.0.0.1/" });
+ assert.equal(extra.status, 400);
+ assert.match(String(extra.body.error), /unknown key\(s\): searchUrl/);
+});
+
+test("web-fetch: http(s) only, and never a private or loopback host — refused before any request", async () => {
+ const fetchRoute = await route("web-fetch");
+ for (const [url, why] of [
+ ["file:///etc/passwd", /only http and https/],
+ ["http://localhost:3001/api/ops/settings", /localhost is a private host/],
+ ["http://127.0.0.1:3001/", /127\.0\.0\.1 is a private address/],
+ ["http://169.254.169.254/latest/meta-data", /private address/],
+ ["http://[::1]:3001/", /private address/],
+ ] as const) {
+ const r = await callPost(fetchRoute, { url });
+ assert.equal(r.status, 400, url);
+ assert.match(String(r.body.error), why, url);
+ }
+ const noUrl = await callPost(fetchRoute, {});
+ assert.equal(noUrl.status, 400);
+ assert.match(String(noUrl.body.error), /"url" is required/);
+});
diff --git a/editor/app/api/ops/_web.ts b/editor/app/api/ops/_web.ts
@@ -0,0 +1,11 @@
+import { NextResponse } from "next/server";
+import { WebRequestError } from "yt-dlp-transcript-common/lib/web/pacer";
+import { opsFail } from "./_lib";
+
+// A web read's failure as an ops answer: a request the fence or the input
+// refuses before anything is sent is a 400; an answer from the far side (an
+// HTTP error, a back-off that ran out, a page that is not text) is a 502.
+export function webFailure(e: unknown): NextResponse {
+ if (e instanceof WebRequestError) return opsFail(e.message, e.status === null ? 400 : 502);
+ throw e;
+}
diff --git a/editor/app/api/ops/archive-item/route.ts b/editor/app/api/ops/archive-item/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient";
+import { describeArchiveOrgItem } from "yt-dlp-transcript-common/controller/archiveOrgImport";
+import { OpsInputError, ops, opsFail, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { item } -> { ok: true, item: { identifier, url, title?, date?,
+// mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes,
+// files: [{ name, format?, source?, size?, seconds?, media, restricted,
+// original? }] } }
+//
+// One archive.org item's file list, read off its metadata
+// (archive.org/metadata/<id>) — one request through the editor's polite
+// archive.org client, cached as an import's is — with each file's size,
+// format and length, which are the media originals an import takes (one
+// record each), and what archive.org restricts. Nothing is downloaded.
+const IDENTIFIER = /^[A-Za-z0-9._-]{1,100}$/;
+
+export async function POST(request: Request) {
+ return ops(request, ["item"], async (body) => {
+ const id = reqString(body, "item");
+ if (!IDENTIFIER.test(id)) throw new OpsInputError(`"${id}" is not an archive.org identifier`);
+ try {
+ return NextResponse.json({ ok: true, item: await describeArchiveOrgItem(id) });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, e.status === 404 ? 404 : 502);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/archive-search/route.ts b/editor/app/api/ops/archive-search/route.ts
@@ -0,0 +1,35 @@
+import { NextResponse } from "next/server";
+import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient";
+import {
+ ARCHIVE_ORG_SEARCH_MAX_ROWS,
+ searchArchiveOrgItems,
+} from "yt-dlp-transcript-common/controller/archiveOrgImport";
+import { OpsInputError, ops, opsFail, optPositiveInt, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { query, limit? } -> { ok: true, query, found, items: [{ identifier, title? }] }
+//
+// An archive.org search (its advanced-search syntax), read only: ONE request
+// through the editor's polite archive.org client — the same client, gap and
+// back-off an import uses (controller/archiveOrgImport.ts) — the first
+// `limit` items (default 50, at most 500) in identifier order. Nothing is
+// written; `import-archive-org` with `query` imports what a search finds.
+const ARCHIVE_SEARCH_DEFAULT_LIMIT = 50;
+
+export async function POST(request: Request) {
+ return ops(request, ["query", "limit"], async (body) => {
+ const query = reqString(body, "query");
+ const limit = optPositiveInt(body, "limit") ?? ARCHIVE_SEARCH_DEFAULT_LIMIT;
+ if (limit > ARCHIVE_ORG_SEARCH_MAX_ROWS) {
+ throw new OpsInputError(`"limit" is at most ${ARCHIVE_ORG_SEARCH_MAX_ROWS}`);
+ }
+ try {
+ const r = await searchArchiveOrgItems(query, { rows: limit });
+ return NextResponse.json({ ok: true, query, found: r.found, items: r.items });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/import-post/route.ts b/editor/app/api/ops/import-post/route.ts
@@ -0,0 +1,24 @@
+import { importPostAction } from "../../../channels/[slug]/importPostAction";
+import { jobResponse, ops, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, url } -> { ok: true, jobId }
+//
+// ONE post by its URL — an X status (https://x.com/<handle>/status/<id>) or a
+// Bluesky post (https://bsky.app/profile/<handle>/post/<id>, or its at://
+// URI) — into the posts archive of `slug`, a posts channel of that platform
+// that archives that account (release 27 S3b). Read through the channel's own
+// fetcher (gallery-dl for X, the public AppView for Bluesky) as an
+// `import-post` job on the platform's queue; the job's log ends with
+// `@@import-post {ok, slug, url, id, written, already?, post?, error?}`. A
+// post already archived is not read again.
+//
+// Every refusal is the action's own sentence: not a post URL, no such channel,
+// not a posts channel, a channel of another platform or whose fetcher cannot
+// read one post, another account's post, the platform held or cooling down.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "url"], async (body) =>
+ jobResponse(await importPostAction(reqSlug(body, "slug"), reqString(body, "url"))),
+ );
+}
diff --git a/editor/app/api/ops/web-fetch/route.ts b/editor/app/api/ops/web-fetch/route.ts
@@ -0,0 +1,28 @@
+import { NextResponse } from "next/server";
+import { webFetch } from "yt-dlp-transcript-common/lib/web/fetchPage";
+import { ops, optPositiveInt, reqString } from "../_lib";
+import { webFailure } from "../_web";
+
+export const dynamic = "force-dynamic";
+
+// POST { url, maxChars? } -> { ok: true, page: { url, finalUrl, status,
+// contentType, title?, text, truncated } }
+//
+// One web page as readable text (release 27 D7), read only, through the
+// process's web pacer (common/lib/web): http(s) only, never a private or
+// loopback host (by name, address or what the name resolves to, every
+// redirect hop checked), text pages only, the text cut at `maxChars`
+// (default 12,000, at most 60,000). Nothing is written. A generation run's
+// agent tool `web_fetch` is the same read.
+export async function POST(request: Request) {
+ return ops(request, ["url", "maxChars"], async (body) => {
+ const url = reqString(body, "url");
+ const maxChars = optPositiveInt(body, "maxChars");
+ try {
+ const page = await webFetch(url, maxChars !== undefined ? { maxChars } : {});
+ return NextResponse.json({ ok: true, page });
+ } catch (e) {
+ return webFailure(e);
+ }
+ });
+}
diff --git a/editor/app/api/ops/web-search/route.ts b/editor/app/api/ops/web-search/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { webSearch } from "yt-dlp-transcript-common/lib/web/search";
+import { ops, optPositiveInt, reqString } from "../_lib";
+import { webFailure } from "../_web";
+
+export const dynamic = "force-dynamic";
+
+// POST { query, n? } -> { ok: true, query, results: [{ title, url, snippet }] }
+//
+// A web search (DuckDuckGo's HTML page, release 27 D7), read only, through
+// the process's web pacer (common/lib/web): one request at a time, 3 s apart,
+// backing off on a 429 or 503. `n` results (default 6, at most 20). Nothing
+// is written. A generation run's agent tool `web_search` is the same read.
+export async function POST(request: Request) {
+ return ops(request, ["query", "n"], async (body) => {
+ const query = reqString(body, "query");
+ const n = optPositiveInt(body, "n");
+ try {
+ const results = await webSearch(query, n !== undefined ? { n } : {});
+ return NextResponse.json({ ok: true, query, results });
+ } catch (e) {
+ return webFailure(e);
+ }
+ });
+}
diff --git a/editor/app/channels/[slug]/importPostAction.ts b/editor/app/channels/[slug]/importPostAction.ts
@@ -0,0 +1,45 @@
+"use server";
+
+// IMPORT ONE POST (release 27 S3b): one X status or one Bluesky post, by its
+// URL, into a posts channel of that platform (common/social/importPost.ts).
+// Refused HERE, before a job exists, with the controller's sentences: not a
+// post URL, no such channel, not a posts channel, a channel of another
+// platform or whose fetcher cannot read one post, another account's post, the
+// platform held or cooling down. The read runs as an `import-post` job on the
+// channel's platform queue, so it never runs beside a fetch of the same
+// source; its log ends with `@@import-post {…}`.
+
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { downloadQueueKey } from "yt-dlp-transcript-common/lib/queueKeys";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/platform";
+import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ IMPORT_POST_RESULT_MARKER,
+ importPost,
+ importPostHeld,
+ planImportPost,
+} from "yt-dlp-transcript-common/social/importPost";
+
+export async function importPostAction(slug: string, url: string): Promise<StreamActionResult> {
+ const paths = getPaths();
+ const planned = await planImportPost(paths, slug, url);
+ if (!planned.ok) return { ok: false, error: planned.error };
+ const { config } = planned.plan;
+ const platform = detectPlatform(config.url) ?? "unknown";
+ const held = await importPostHeld(paths, platform);
+ if (held) return { ok: false, info: true, error: held };
+ return runManagedFunction({
+ kind: "import-post",
+ queueKey: downloadQueueKey(config),
+ paths,
+ channelSlug: slug,
+ fn: async (onLog, signal) => {
+ const result = await importPost({ paths, slug, url, settings: getSettings(), onLog, signal });
+ onLog(`${IMPORT_POST_RESULT_MARKER}${JSON.stringify(result)}`);
+ safeRevalidate([`/channels/${slug}`]);
+ if (!result.ok) throw new Error(result.error ?? "Post import failed");
+ },
+ });
+}
diff --git a/editor/package.json b/editor/package.json
@@ -20,7 +20,8 @@
"next": "16.2.3",
"react": "19.2.4",
"react-dom": "19.2.4",
- "yt-dlp-transcript-common": "workspace:*"
+ "yt-dlp-transcript-common": "workspace:*",
+ "yt-dlp-transcript-mcp": "workspace:*"
},
"devDependencies": {
"@playwright/test": "^1.59.1",
diff --git a/mcp/package.json b/mcp/package.json
@@ -3,6 +3,10 @@
"version": "0.1.0",
"private": true,
"type": "module",
+ "exports": {
+ "./package.json": "./package.json",
+ "./callTool": "./src/callTool.ts"
+ },
"description": "MCP server exposing a yt-dlp transcript archive (or a federated hub) to Claude Code and other MCP clients \u2014 reads the site's static JSON shards.",
"bin": {
"yt-dlp-transcript-mcp": "src/index.ts"
diff --git a/mcp/src/callTool.test.ts b/mcp/src/callTool.test.ts
@@ -0,0 +1,108 @@
+// The corpus tools in process, over the synthetic draft corpus read the way
+// the MCP's --local reads a composed public dir.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { CORPUS_TOOL_NAMES, CorpusToolError, createCorpusTools, type CorpusTools } from "./callTool";
+import { fakeEditor } from "./editorOps.testkit";
+
+let dir: string;
+let corpus: CorpusTools;
+
+before(async () => {
+ dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "mcp-calltool-")));
+ corpus = await createCorpusTools({ source: `local:${dir}` });
+});
+
+after(async () => {
+ await corpus.close();
+ await rm(dir, { recursive: true, force: true });
+});
+
+test("the allowlist: read-only corpus tools only — no fetch_clip, enqueue, get_job or open_link", () => {
+ const names = corpus.tools.map((t) => t.name);
+ assert.deepEqual([...names].sort(), [...CORPUS_TOOL_NAMES].sort());
+ for (const n of ["fetch_clip", "enqueue", "get_job", "open_link"]) assert.ok(!names.includes(n), n);
+ for (const t of corpus.tools) {
+ assert.equal(typeof t.run, "function");
+ assert.equal(typeof t.description, "string");
+ const props = (t.inputSchema as { properties?: Record<string, unknown> }).properties ?? {};
+ assert.ok(!("source" in props), `${t.name} shows no source`);
+ assert.ok(!((t.inputSchema as { required?: string[] }).required ?? []).includes("source"));
+ }
+});
+
+test("a call outside the allowlist is refused before the server sees it", async () => {
+ for (const n of ["fetch_clip", "enqueue", "get_job", "open_link", "nope"]) {
+ await assert.rejects(corpus.call(n, {}), (e: Error) => e instanceof CorpusToolError && /not one of this run's read-only corpus tools/.test(e.message));
+ }
+});
+
+test("search and transcript reads over the draft corpus, through the same dispatch Claude Code uses", async () => {
+ const channels = await corpus.call("list_channels");
+ assert.match(channels, /synth-kitchen/);
+ assert.match(channels, /synth-other/);
+ const hits = await corpus.call("search_transcripts", { query: "second shop" });
+ assert.match(hits, /qa-long-03/);
+ const t = await corpus.tools.find((x) => x.name === "get_transcript")!.run({ video_id: "bread-day-01", channel: "synth-kitchen" }, {});
+ assert.match(t, /I would never sell the bakery to a chain/);
+ // Every result names its corpus — the forced one.
+ assert.match(t, new RegExp(`\\(corpus: local:${dir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
+});
+
+test("source is FORCED: an argument naming another corpus is overwritten", async () => {
+ const out = await corpus.call("list_channels", { source: "remote:https://elsewhere.example" });
+ assert.match(out, /synth-kitchen/);
+ assert.match(out, /\(corpus: local:/);
+ assert.doesNotMatch(out, /elsewhere/);
+});
+
+test("a tool's own error comes back as a CorpusToolError with its words", async () => {
+ await assert.rejects(
+ corpus.call("get_transcript", { video_id: "no-such-video" }),
+ (e: Error) => e instanceof CorpusToolError && /no-such-video/.test(e.message),
+ );
+});
+
+test("notes: list and read only; a reply is refused, and the schema offers neither reply nor its fields", async () => {
+ const notes = corpus.tools.find((t) => t.name === "notes")!;
+ const props = (notes.inputSchema as { properties: Record<string, { enum?: string[] }> }).properties;
+ assert.deepEqual(props.action!.enum, ["list", "read"]);
+ for (const k of ["note_id", "text", "resolve"]) assert.ok(!(k in props), k);
+ await assert.rejects(corpus.call("notes", { action: "reply", note_id: "n_1", text: "x" }), /list and read only/);
+
+ // list goes through to umtool, as the MCP's notes does.
+ const editor = fakeEditor(() => ({ status: 200, body: { notes: [] } }), { UMTOOL_URL: "http://umtool.test" });
+ const withNotes = await createCorpusTools({ source: `local:${dir}`, only: ["notes"], editorDeps: editor.deps });
+ try {
+ await withNotes.call("notes", { action: "list" }).catch(() => "");
+ assert.ok(editor.sent.length >= 1);
+ assert.ok(editor.sent.every((s) => s.method === "GET"), JSON.stringify(editor.sent));
+ } finally {
+ await withNotes.close();
+ }
+});
+
+test("only: a narrower set; a name outside the allowlist cannot be asked for", async () => {
+ const two = await createCorpusTools({ source: `local:${dir}`, only: ["search_transcripts", "get_transcript"] });
+ try {
+ assert.deepEqual(two.tools.map((t) => t.name), ["search_transcripts", "get_transcript"]);
+ await assert.rejects(two.call("list_channels"), CorpusToolError);
+ } finally {
+ await two.close();
+ }
+ await assert.rejects(
+ createCorpusTools({ source: `local:${dir}`, only: ["fetch_clip" as never] }),
+ /not a read-only corpus tool/,
+ );
+});
+
+test("an aborted signal stops a call", async () => {
+ const ac = new AbortController();
+ ac.abort();
+ await assert.rejects(corpus.tools[0]!.run({}, { signal: ac.signal }));
+});
diff --git a/mcp/src/callTool.ts b/mcp/src/callTool.ts
@@ -0,0 +1,187 @@
+// THE CORPUS TOOLS IN PROCESS (release 27 S3, D2) — the MCP's own read tools
+// for an agent a generation job runs, so it sees exactly what Claude Code
+// sees, with no MCP process and no stdio.
+//
+// A Client and the server (createServer) linked over the SDK's in-memory
+// transport: the tool handlers are module-private, and going through
+// `tools/call` keeps the dispatch wrapper (the corpus note on every result,
+// the error shapes) in the path.
+//
+// The rules, in code:
+// - `source` is FORCED: every call reads the run's corpus. An argument naming
+// another source is overwritten, and `source` is not in the schemas the
+// agent sees.
+// - A READ-ONLY allowlist (CORPUS_TOOL_NAMES): the listing, search,
+// enumerate, get_* corpus reads, channel coverage, the sources, and the
+// sweep and ask plans. `notes` is in it for `list` and `read` only (a
+// reply writes in umtool). `fetch_clip` and `enqueue` cause work in the
+// editor, `get_job` reads the editor's jobs and `open_link` reads OTHER
+// corpora by URL: none of them is in it.
+//
+// The tools come in the agent loop's AgentTool shape (common/lib/llm, lane A
+// of release 27); the type is declared here until S5 unifies the import.
+
+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
+import type { FetchClipDeps } from "./fetchClip";
+import { createServer, TOOLS } from "./server";
+import { SourceRegistry } from "./sourceRegistry";
+import type { ShardSource } from "./source";
+import type { SourceSpec } from "./sources";
+
+export type AgentTool = {
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+ run(input: any, ctx: { signal?: AbortSignal }): Promise<string>; // eslint-disable-line @typescript-eslint/no-explicit-any
+};
+
+export const CORPUS_TOOL_NAMES = [
+ "list_channels",
+ "list_tags",
+ "list_reports",
+ "get_report",
+ "search_transcripts",
+ "enumerate_matches",
+ "get_transcript",
+ "get_post",
+ "get_thread",
+ "get_transcripts",
+ "get_video_metadata",
+ "channel_coverage",
+ "notes",
+ "list_sources",
+ "resolve_source",
+ "sweep_plan",
+ "ask_plan",
+] as const;
+
+export type CorpusToolName = (typeof CORPUS_TOOL_NAMES)[number];
+
+// What `notes` may do in process.
+export const NOTES_ACTIONS = ["list", "read"] as const;
+
+export class CorpusToolError extends Error {}
+
+export type CorpusTools = {
+ // The source handle every call reads.
+ source: string;
+ tools: AgentTool[];
+ // Call one allowed tool; its text. A tool error is thrown as a
+ // CorpusToolError carrying the tool's own words.
+ call(name: string, args?: Record<string, unknown>): Promise<string>;
+ close(): Promise<void>;
+};
+
+export type CorpusToolsOptions = {
+ // The corpus: a handle (`local:<dir>`, `remote:<url>`, `hub:<url>`), a
+ // spec, or a built ShardSource (tests).
+ source: string | SourceSpec | ShardSource;
+ // Only these of CORPUS_TOOL_NAMES (default: all of them).
+ only?: readonly CorpusToolName[];
+ // The editor and umtool the editor-backed reads (channel_coverage, notes)
+ // reach: env, fetch, clock. Default: the process's.
+ editorDeps?: Partial<FetchClipDeps>;
+};
+
+function specOf(handle: string): SourceSpec {
+ const m = /^(local|remote|hub):(.+)$/s.exec(handle.trim());
+ if (!m) throw new Error(`createCorpusTools: "${handle}" is not a source handle (local:<dir>, remote:<url>, hub:<url>)`);
+ const rest = m[2]!.trim();
+ if (m[1] === "local") return { kind: "local", dir: rest };
+ if (m[1] === "remote") return { kind: "remote", url: rest.replace(/\/+$/, "") };
+ const hash = rest.indexOf("#");
+ if (hash < 0) return { kind: "hub", url: rest.replace(/\/+$/, "") };
+ const sites = rest
+ .slice(hash + 1)
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ return { kind: "hub", url: rest.slice(0, hash).replace(/\/+$/, ""), ...(sites.length ? { sites } : {}) };
+}
+
+const isSource = (s: unknown): s is ShardSource =>
+ typeof s === "object" && s !== null && typeof (s as ShardSource).listChannels === "function";
+
+type JsonSchema = { properties?: Record<string, unknown>; required?: string[] } & Record<string, unknown>;
+
+// A tool's schema as the agent sees it: no `source`; `notes` list/read only.
+function agentSchema(name: string, schema: unknown): Record<string, unknown> {
+ const s = structuredClone(schema) as JsonSchema;
+ if (s.properties) delete s.properties.source;
+ if (Array.isArray(s.required)) {
+ s.required = s.required.filter((r) => r !== "source");
+ if (s.required.length === 0) delete s.required;
+ }
+ if (name === "notes" && s.properties) {
+ s.properties.action = { type: "string", enum: [...NOTES_ACTIONS], description: 'Default "list".' };
+ for (const k of ["note_id", "text", "resolve"]) delete s.properties[k];
+ }
+ return s;
+}
+
+const NOTES_DESCRIPTION =
+ "The operator's notes in umtool on articles and report-video projects (read only here). action " +
+ '"list": every open note, grouped by target. action "read" with target (as list names it: ' +
+ '"sites/<site>/<report>" for an article, else a project id): each note with its anchor resolved ' +
+ "(status: open, resolved or all).";
+
+export async function createCorpusTools(opts: CorpusToolsOptions): Promise<CorpusTools> {
+ let registry: SourceRegistry;
+ if (isSource(opts.source)) registry = SourceRegistry.forSource(opts.source);
+ else registry = new SourceRegistry(typeof opts.source === "string" ? specOf(opts.source) : opts.source);
+ const source = registry.defaultHandle;
+ const allowed = new Set<string>(opts.only ?? CORPUS_TOOL_NAMES);
+ for (const n of allowed) {
+ if (!(CORPUS_TOOL_NAMES as readonly string[]).includes(n)) {
+ throw new Error(`createCorpusTools: "${n}" is not a read-only corpus tool`);
+ }
+ }
+
+ const server = createServer(registry, opts.editorDeps ? { fetchClipDeps: opts.editorDeps } : {});
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: "archilyzer-generation", version: "0" }, { capabilities: {} });
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+
+ const call = async (name: string, args: Record<string, unknown> = {}, signal?: AbortSignal): Promise<string> => {
+ if (!allowed.has(name)) {
+ throw new CorpusToolError(`${name}: not one of this run's read-only corpus tools (${[...allowed].join(", ")})`);
+ }
+ const a: Record<string, unknown> = { ...(args ?? {}), source };
+ if (name === "notes") {
+ const action = a.action ?? "list";
+ if (!(NOTES_ACTIONS as readonly unknown[]).includes(action)) {
+ throw new CorpusToolError(`notes: ${NOTES_ACTIONS.join(" and ")} only here (a reply is the operator's)`);
+ }
+ a.action = action;
+ for (const k of ["note_id", "text", "resolve"]) delete a[k];
+ }
+ signal?.throwIfAborted();
+ const res = (await client.callTool({ name, arguments: a }, signal ? { signal } : undefined)) as {
+ content?: { type: string; text?: string }[];
+ isError?: boolean;
+ };
+ const text = (res.content ?? [])
+ .filter((c) => c.type === "text")
+ .map((c) => c.text ?? "")
+ .join("\n");
+ if (res.isError) throw new CorpusToolError(text);
+ return text;
+ };
+
+ const tools: AgentTool[] = TOOLS.filter((t) => allowed.has(t.name)).map((t) => ({
+ name: t.name,
+ description: t.name === "notes" ? NOTES_DESCRIPTION : (t.description ?? ""),
+ inputSchema: agentSchema(t.name, t.inputSchema),
+ run: (input: Record<string, unknown>, ctx: { signal?: AbortSignal }) => call(t.name, input, ctx?.signal),
+ }));
+
+ return {
+ source,
+ tools,
+ call: (name, args) => call(name, args),
+ close: async () => {
+ await client.close();
+ await server.close();
+ },
+ };
+}
diff --git a/plans/release-27.md b/plans/release-27.md
@@ -371,6 +371,55 @@ Gates:
- Unit suites: common 3844/3844, `test:scripts` 850 pass + 3 skipped of 853, editor unit 264/264, mcp 306/306.
- `docs cli|files|env --check` clean.
- **Not run:** the umtool `build.spec.ts` e2e and the capped umtool build. Memory stayed under the 6000 MB floor; the heavy gate waited 9.5 min at 3.4–4.4 GB available, and the attempt was stopped.
+### S2, as shipped (2026-10-13, lane B)
+
+Branch `r27/checks-tools`, from `r27/integration` `4b8dc576`.
+
+| Commit | What |
+| --- | --- |
+| `ee288e89` | `citations/verify.ts` strict check (`strictQuoteCheck`, `strictTextCheck`, `strictNormalize`, `quoteFragments`); verify-quotes status `inexact` (a warning: printed, counted, exit unchanged); `report/draft/{sweepModel,reportOps,videoOps,grounding}.ts` with their tests |
+| (this commit) | this record; the CHANGELOG bullet |
+
+- **The strict check** normalises both sides (NFKC, case, curly quotes, apostrophes removed, other punctuation a space), splits the quote on `…` / `...`, and matches each fragment on word boundaries in the cues overlapping ±90 s of the cited second. verify-quotes runs it on every track and takes a pass on any; `drift` and `en-orig-drift` keep precedence, so `inexact` is only a quote recall passes. A post is checked against its text.
+- **`sweepModel.ts`**: a finding is a `- `/`* ` item inside a section with at least one citing link (a link-less bullet stays a line). Lines before the title, the preamble, blank lines, indented continuations and odd heading spacing are kept, so `renderSweep(parseSweep(md)) === md` for any input.
+- **`reportOps.ts`**: `applyReportOps(doc, ops, ctx)` is async (the `add` checker is injected: `strictCheckerOver(cuesOf)`), returns a new doc, and reports `{index, op}` applied / `{index, op, why}` refused. A section a batch empties of findings and text is removed; a moved or added finding goes after the section's last finding, or into a new section before Coverage. `quotedClaimProblems(doc)` lints the quotes-in-claims shape (words between two quotes of one link's run that are not a joiner).
+- **`videoOps.ts`**: `applyVideoOps(manifest, ops, {report, parent?})` is pure; a narration's soft warnings come back on its applied entry. A clip added in the batch is bounded by its own citation's span.
+- **`grounding.ts`**: `checkNarration(text, {reference, quotes, evidence?})` → `{hard, soft}`; `groundingInputOf(report)`. The lints match a sentence to the evidence line sharing the most content words (at least two and half the sentence's).
+
+Gates: `pnpm -r exec tsc --noEmit` clean; common tests 3862/3862 (35 new).
+
+Found: `testing/draft/sweeps/inexact.md`'s far quote (200 s from its link) is a `drift` in verify-quotes, not an `inexact`: its ±5 s recall window shares only "the" with it (0.25), and drift is the stronger status. The strict check refuses it (the unit test says so); verify-quotes' `inexact` is the reversed quote.
+
+### S3, as shipped (2026-10-13, lane B)
+
+| Commit | What |
+| --- | --- |
+| `be908bdd` | the test kit's `derive.ts` / `regenerate.ts` path joins opt out of Turbopack tracing — `test:scripts`' next-build-trace test was red from S0 |
+| `037c996c` | `mcp/src/callTool.ts` (`createCorpusTools`, exported as `yt-dlp-transcript-mcp/callTool`; the editor depends on the package); `common/lib/web/{pacer,search,fetchPage,tools}.ts`; the editor's `web-search` / `web-fetch` actions, ACTIONS rows, help, COMMANDS.md; `testing/web/fakeWeb.mjs`; `report/draft/agentTool.ts` (the AgentTool shape, until S5 imports lane A's) |
+| (this commit) | this record; the CHANGELOG bullet; the kit README row |
+
+- **`createCorpusTools({source, only?, editorDeps?})`** → `{source, tools, call(name, args), close()}`. A Client linked to `createServer(registry)` over `InMemoryTransport`, so the dispatch wrapper (the `(corpus: …)` note, the error shapes) is in the path. `source` is a handle, a `SourceSpec` or a built `ShardSource`. The allowlist is `CORPUS_TOOL_NAMES`: `list_channels`, `list_tags`, `list_reports`, `get_report`, `search_transcripts`, `enumerate_matches`, `get_transcript`, `get_post`, `get_thread`, `get_transcripts`, `get_video_metadata`, `channel_coverage`, `notes` (list and read; `reply` and its fields gone from the schema and refused), `list_sources`, `resolve_source`, `sweep_plan`, `ask_plan`. Not in it: `fetch_clip`, `enqueue` (work in the editor), `get_job` (the editor's jobs, not the corpus) and `open_link` (reads OTHER corpora by URL). A tool's error is thrown as `CorpusToolError` with the tool's words.
+- **The web.** `webPacer` is the process's one queue (the editor's two actions and every job's tools share it). `webSearch(query, {n, searchUrl, pacer})` → `[{title, url, snippet}]`; `webFetch(url, {maxChars, pacer, allowPrivate, resolve})` → `{url, finalUrl, status, contentType, title?, text, truncated}`; `fetchRefusal(url)` is the fence on its own; `webTools({pacer, searchUrl, allowPrivate})` → the `web_search` / `web_fetch` AgentTools. A backed-off request still waits out the rest of the 3 s gap.
+- **The editor actions** answer synchronously, through `ops()` (`_web.ts` maps a refusal before any request to a 400, a far-side failure to a 502). The search endpoint is DuckDuckGo's; S6's `generation` settings name the web provider.
+
+Gates: tsc clean; common 3870/3870 (8 new); mcp 314/314 (8 new, `protocol.test.ts`'s tool list unchanged); editor unit 267/267 (3 new); `test:scripts` 832 + 3 skipped, 1 failed before `be908bdd` (S0's next-build-trace) and green after it; `docs cli --check` clean.
+
+Not done here: the editor's `next.config.ts` `transpilePackages` does not list `yt-dlp-transcript-mcp` yet — S6, which imports it from a route, adds it (the unit test imports it under tsx).
+
+### S3b, as shipped (2026-10-13, lane B)
+
+| Commit | What |
+| --- | --- |
+| `f7b2757c` | editor actions `archive-search`, `archive-item`, `import-post` (routes, ACTIONS rows, help, COMMANDS.md; the `import-post` action in `channels/[slug]/importPostAction.ts`); `describeArchiveOrgItem` in `archiveOrgImport.ts`; `SocialFetcher.fetchOne` (X through gallery-dl on the status URL, Bluesky through `getPosts`), `parsePostUrl`, `social/importPost.ts`; job kind `import-post`; `report/draft/research/{decide,tools}.ts`; `testing/archiveOrg/fakeArchiveOrg.mjs`; common's test glob reaches `lib/*/*/*/` |
+| (this commit) | this record; the CHANGELOG bullets |
+
+- **`decideAcquisition(proposal, autonomy, limits, spentSoFar)`** → `{decision: "enqueue"} | {decision: "approval", reason} | {decision: "refuse", reason}`. The standing rules (`standingRuleRefusal`) refuse in every mode: `create-channel` with any `sites` (an X channel's refusal says so), a Twitch VOD URL anywhere in the args, a `queueKey`, an action not in `ACQUISITION_ACTIONS`. Then `propose` waits on everything; the approval flags (`newChannelsNeedApproval`, `postWalksNeedApproval` — `fetch-posts` with `full` or `older`) hold under `limits` and `auto`; under `limits` a new channel and a priority bump always wait; a cap reached, or a download of unknown size (`estimate.gb` absent; a dry run is 0) or a transcription of unknown length, waits in both. One post is one item; a channel, a post fetch, a capture and a bump cost none.
+- **`acquisitionTools(ctx)`** → nine AgentTools named as the actions (`import-archive-org`, `import-video`, `create-channel`, `fetch-posts`, `capture-posts`, `import-post`, `transcribe-one`, `priority-bump` = `channel-priority` tier normal, `persist-videos`), each taking the action's own keys plus `reason`, `evidence`, `estimate`. Each records a `Proposal` in `ctx.ledger` (ids `p01`…; `note` carries why it waits or failed), and only an `enqueue` calls `ctx.editor.run(editorAction, body)` — the body is built from the action's own keys, so a `sites` the model adds never reaches the editor. `runApprovedProposal` (the operator's yes: past autonomy and caps, never past a standing rule), `rejectProposal`, `archiveReadTools` (`archive-search` / `archive-item` through the editor), `newLedger`. `ctx.onChange` is where S11 writes `proposals.json`.
+- **`import-post`** refuses at the door (route unit test) and in the job: not a post URL, no channel, not a posts channel, a channel of another platform, a fetcher with no `fetchOne` (x-playwright, x-nitter, forum), a post the URL names as another account's; after the read, a post the platform says is another account's is not written. The platform's hold and rate-limit cooldown refuse it before a job (`importPostHeld`, the holds a manual download meets). The job's log ends `@@import-post {…}`.
+
+Gates: tsc clean; common 3891/3891 (21 new); mcp 314/314; editor unit 270/270 (3 new); `test:scripts` 833 + 3 skipped; `docs cli --check` clean. Editor `next build` (heavy slot, 5 GB cap): clean, the five new `/api/ops` routes built. e2e `ops-api.spec.ts` alone: 13 passed, 0 failed (32 s; its prebuild rebuilt `editor/.next/e2e` in 66 s).
+
+Decided here: `import-post` takes a post of the channel's own account only (a reply or quote by another account would be misattributed in that archive). `import-post` is not replayable (a second import reads nothing anyway).
## Rollout
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
@@ -156,6 +156,9 @@ importers:
yt-dlp-transcript-common:
specifier: workspace:*
version: link:../common
+ yt-dlp-transcript-mcp:
+ specifier: workspace:*
+ version: link:../mcp
devDependencies:
'@playwright/test':
specifier: ^1.59.1
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -95,6 +95,11 @@
// pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait
// pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait
// pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait
+// pnpm ops web-search --json '{"query":"second shop opening","n":5}'
+// pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'
+// pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'
+// pnpm ops archive-item --json '{"item":"example-item"}'
+// pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -359,6 +364,17 @@ const ACTIONS = [
"delete-file",
"do-not-clean",
"cleanup",
+ // WEB READS (release 27 S3): a DuckDuckGo search ({query, n?}) and one
+ // page as text ({url, maxChars?}), read only, through the editor's one
+ // paced web queue. Synchronous; no job.
+ "web-search",
+ "web-fetch",
+ // RESEARCH (release 27 S3b): an archive.org search ({query, limit?}) and one
+ // item's file list ({item}), read only and paced; ONE post by its URL into a
+ // posts channel of its platform ({slug, url}), as a job.
+ "archive-search",
+ "archive-item",
+ "import-post",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -1079,6 +1095,44 @@ export function usage() {
" (a local llama-server the editor starts and stops) and waits while a",
" transcription holds it. With --wait the result is printed on stdout.",
"",
+ 'web-search searches the web (DuckDuckGo\'s HTML page) and answers the',
+ ' results: {"query", "n"?: 6 (at most 20)} -> {results: [{title, url,',
+ ' snippet}]}. Read only, through the editor\'s one web queue: one request at',
+ " a time, 3 s apart, backing off on a 429 or 503. For context; a web page",
+ " is never cited as what someone said.",
+ "",
+ 'web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at',
+ ' most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text,',
+ " truncated}}. http and https only; a private or loopback host (by name, by",
+ " address, or by what its name resolves to, every redirect checked) is",
+ " refused before any request, and so is a page that is not text (a PDF, an",
+ " image). Read only, on the same web queue as web-search.",
+ "",
+ 'archive-search searches archive.org (its advanced-search syntax) and answers',
+ ' the items: {"query", "limit"?: 50 (at most 500)} -> {found, items:',
+ ' [{identifier, title?}]}, in identifier order. One request through the',
+ " editor's archive.org client, paced and backed off as an import is. Read",
+ ' only; import-archive-org with "query" imports what a search finds.',
+ "",
+ 'archive-item answers one archive.org item\'s files from its metadata:',
+ ' {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?,',
+ " collections, restricted, mediaFiles, mediaBytes, files: [{name, format?,",
+ " source?, size?, seconds?, media, restricted, original?}]}}. media marks the",
+ " originals an import takes (one record each); restricted, what archive.org",
+ " will not hand out. Read only; nothing is downloaded.",
+ "",
+ 'import-post imports ONE post by its URL into a posts channel of its',
+ ' platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a',
+ ' Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read',
+ " through the channel's own fetcher (gallery-dl for X, with the channel's",
+ " login; the public AppView for Bluesky) as an import-post job on the",
+ " platform's queue. Refused, before any job: a URL that is not a post, a",
+ " channel that is not a posts channel of that platform or whose fetcher",
+ " cannot read one post, a post the URL names as another account's, the",
+ " platform held or cooling down. A post already archived is not read again;",
+ " one the platform says is another account's is not written. The log ends",
+ " with @@import-post {ok, slug, url, id, written, already?, post?, error?}.",
+ "",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
" WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from",