commit 81c712609eeace8952a95f7d90f571e1fe809087
parent c497e9062ef96809739355eae8a782c87b5e3430
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 11:10:47 -0400
common, editor: release 27 S3b — research tools: archive.org reads, import-post, and the acquisition tools
- editor actions archive-search ({query, limit?}: one paced archive.org search)
and archive-item ({item}: an item's files, sizes, formats, lengths, media
originals and restrictions, describeArchiveOrgItem in archiveOrgImport.ts),
read only, through the editor's polite archive.org client.
- editor action import-post ({slug, url}): one X status or Bluesky post into a
posts channel of that platform, as an `import-post` job on the platform's
queue (social/importPost.ts). SocialFetcher gains an optional fetchOne:
gallery-dl on the status URL for X, getPosts on the public AppView for
Bluesky. Refused before any job: not a post URL, not a posts channel of that
platform, a fetcher that cannot, another account's post, the platform held or
cooling down. A post already archived is not read again; another account's
is not written.
- report/draft/research: Autonomy, ResearchLimits, Proposal, the pure
decideAcquisition (enqueue | approval | refuse) with the standing rules
(create-channel on NO site, an X channel never on a site, no Twitch VOD URL,
no queueKey override, only the listed actions), acquisitionTools (one per
action, each mapped to its existing editor action through an injected
editor.run), runApprovedProposal / rejectProposal, archiveReadTools.
- testing/archiveOrg/fakeArchiveOrg.mjs: a fake archive.org for the client.
- common's test glob reaches lib/*/*/*/ (report/draft/research).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
22 files changed, 1804 insertions(+), 1 deletion(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -131,6 +131,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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/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/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/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
@@ -17,6 +17,7 @@ transcript, channel or person goes in these fixtures, ever.
| `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 (S0), the `paragraphs` manifest shows two owed bugs that release 27 S7 fixes: the title
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/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/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/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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -97,6 +97,9 @@
// 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
@@ -366,6 +369,12 @@ const ACTIONS = [
// 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
@@ -1099,6 +1108,31 @@ export function usage() {
" 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",