Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit d816088420e4c38dac4f4eeeaa92903ca7b24e2b
parent ffee4005180f18b198e3b24beab3887ea5a071ee
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 16:17:43 -0400

editor: X search channels — the form's kind, the Leads panel, Archive this account / Never archive, ops, CLI, MCP, e2e

Release 38 lane S, the editor half. The New channel form's Platform gains
"X search (posts from any account)" (a pasted x.com/search URL selects it):
query, since, until, window, language; the Sites section says it is never
put on a site, and create / Configure refuse memberships for one before
anything is written. The channel page shows the query and the search walk,
"Search again from the top", no older walk, no fetcher switch, and the Leads
panel: accounts by matching posts with Archive this account (<handle>-x on
no site, through createChannelFromForm, its fetch started), Never archive
and Restore. Ops: GET /api/ops/channel/<slug>?leads=1 (`pnpm ops get channel
<slug> --leads [--limit N]`), POST /api/ops/x-search-lead {slug, handle,
action}; MCP x_search_leads (read only, through the editor). Fetch details on
a search URL answers without a request. The e2e fake gallery-dl answers a
/search URL with posts by three accounts; x-search.spec.ts drives the form,
the walk, the leads and both actions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Meditor/app/api/ops/channel/[slug]/route.ts | 22+++++++++++++++++++++-
Aeditor/app/api/ops/x-search-lead/route.test.ts | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/x-search-lead/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 24++++++++++++++++++++----
Aeditor/app/channels/[slug]/components/XSearchLeadsPanel.tsx | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 16++++++++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 4++++
Aeditor/app/channels/[slug]/xSearchActions.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/actions.ts | 26++++++++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 40+++++++++++++++++++++++++++++++++-------
Aeditor/app/channels/components/XSearchFields.tsx | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 18++++++++++++++++--
Meditor/app/channels/components/parseChannelForm.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Meditor/e2e/fixtures/bin/fake-gallery-dl.mjs | 26++++++++++++++++++++++++++
Aeditor/e2e/x-search.spec.ts | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/protocol.test.ts | 1+
Mmcp/src/server.ts | 5+++++
Amcp/src/xSearchLeads.test.ts | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amcp/src/xSearchLeads.ts | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 46++++++++++++++++++++++++++++++++++++++++------
21 files changed, 1228 insertions(+), 29 deletions(-)

diff --git a/editor/app/api/ops/channel/[slug]/route.ts b/editor/app/api/ops/channel/[slug]/route.ts @@ -13,6 +13,7 @@ import { tierOf, } from "yt-dlp-transcript-common/lib/channelPriority"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; import { opsAuth } from "../../_lib"; export const dynamic = "force-dynamic"; @@ -63,7 +64,25 @@ export async function GET( ); } const priority = getSettings().channelPriority; - const wantCounts = new URL(request.url).searchParams.get("counts") === "1"; + const sp = new URL(request.url).searchParams; + const wantCounts = sp.get("counts") === "1"; + // `?leads=1` (release 38): an X search channel's leads — the accounts its + // matching posts came from, ranked (`&limit=N`, default 100). Refused, with + // the sentence, for any other channel. + let leads: unknown = undefined; + if (sp.get("leads") === "1") { + const limitRaw = sp.get("limit"); + const limit = limitRaw === null ? undefined : Number(limitRaw); + if (limit !== undefined && !(Number.isInteger(limit) && limit > 0)) { + return NextResponse.json({ ok: false, error: `"limit" must be a whole number above 0` }, { status: 400 }); + } + const read = await readXSearchLeads(paths, slug, limit !== undefined ? { limit } : {}); + if (!read.ok) return NextResponse.json({ ok: false, error: read.error }, { status: 400 }); + const { ok: _ok, slug: _slug, ...rest } = read; + void _ok; + void _slug; + leads = rest; + } const [snapshot, stat, media] = await Promise.all([ readChannelSnapshot(paths, slug), wantCounts ? readChannelStat(paths, slug) : Promise.resolve(null), @@ -88,6 +107,7 @@ export async function GET( }, // null unless ?counts=1 — see the header. counts: stat, + ...(leads !== undefined ? { leads } : {}), media, report: snapshot ? { diff --git a/editor/app/api/ops/x-search-lead/route.test.ts b/editor/app/api/ops/x-search-lead/route.test.ts @@ -0,0 +1,149 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/x-search-lead/route.test.ts" +// +// An X search channel over ops (release 38 lane S), against a temp corpus: the +// leads read (`GET /api/ops/channel/<slug>?leads=1`), x-search-lead's Never +// archive / Restore and the Archive dry run, and every refusal — create-channel +// of a search channel on a site, a lead on a channel that is not a search, an +// account already archived. A successful create ends in revalidatePath, which +// needs a running Next server: Archive this account is driven in +// e2e/x-search.spec.ts. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-search-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +async function channel(slug: string, config: Record<string, unknown>, posts?: string[]): Promise<void> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + if (posts) { + const lines = posts.map((author, i) => { + const id = String(1899000000000000000n + BigInt(i)); + return JSON.stringify({ + id, + slug: `${slug}/${id}`, + channelSlug: slug, + author, + createdAt: `2025-0${i + 1}-01T00:00:00.000Z`, + uploadDate: `20250${i + 1}01`, + text: `zephyr ${i}`, + url: `https://x.com/${author}/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }); + }); + await writeFile(path.join(dir, "posts", "2025-01.jsonl"), lines.join("\n") + "\n"); + } +} +await channel( + "demo-search", + { + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + xSearch: { query: "zephyr" }, + }, + ["alice", "alice", "bob"], +); +await channel("bob-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "bob", url: "https://x.com/bob" }); +await mkdir(path.join(ROOT, "sites", "demo-site"), { recursive: true }); +await writeFile( + path.join(ROOT, "sites", "demo-site", "site.json"), + JSON.stringify({ siteId: "demo-site", siteTitle: "Demo", channels: [] }), +); + +const lead = (await import("./route")).POST; +const create = (await import("../create-channel/route")).POST; +const read = (await import("../channel/[slug]/route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function call(handler: (r: Request) => Promise<Response>, body: Record<string, unknown>) { + const res = await handler( + new Request("http://localhost/api/ops/x", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} +async function get(slug: string, query: string) { + const res = await (read as unknown as (r: Request, ctx: { params: Promise<{ slug: string }> }) => Promise<Response>)( + new Request(`http://localhost/api/ops/channel/${slug}?${query}`, { headers: { authorization: "Bearer test-token" } }), + { params: Promise.resolve({ slug }) }, + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} +const exists = (p: string) => access(p).then(() => true, () => false); + +test("the leads read: ranked, archived accounts named; refused for any other channel and a bad limit", async () => { + const res = await get("demo-search", "leads=1"); + assert.equal(res.status, 200); + const leads = res.json.leads as { query: string; leads: { key: string; count: number; archivedAs?: string[] }[]; posts: number }; + assert.equal(leads.query, "zephyr"); + assert.equal(leads.posts, 3); + assert.deepEqual(leads.leads.map((l) => [l.key, l.count, l.archivedAs ?? []]), [["alice", 2, []], ["bob", 1, ["bob-x"]]]); + const plain = await get("demo-search", ""); + assert.equal(plain.json.leads, undefined); + const other = await get("bob-x", "leads=1"); + assert.equal(other.status, 400); + assert.match(String(other.json.error), /bob-x is not an X search channel/); + assert.equal((await get("demo-search", "leads=1&limit=0")).status, 400); +}); + +test("never, restore, and the archive dry run; refusals in the controller's sentences", async () => { + const never = await call(lead, { slug: "demo-search", handle: "@alice", action: "never" }); + assert.deepEqual(never.json, { ok: true, exclude: ["alice"], changed: true }); + const hidden = await get("demo-search", "leads=1"); + assert.deepEqual((hidden.json.leads as { hidden: unknown }).hidden, [{ handle: "alice", count: 2 }]); + const restore = await call(lead, { slug: "demo-search", handle: "alice", action: "restore" }); + assert.deepEqual(restore.json, { ok: true, exclude: [], changed: true }); + + const dry = await call(lead, { slug: "demo-search", handle: "alice", action: "archive", dryRun: true }); + assert.equal(dry.status, 200); + assert.equal(dry.json.slug, "alice-x"); + assert.equal((dry.json.fields as Record<string, string>).url, "https://x.com/alice"); + assert.equal(await exists(path.join(ROOT, "channels", "alice-x")), false); + + const archived = await call(lead, { slug: "demo-search", handle: "bob", action: "archive" }); + assert.equal(archived.status, 400); + assert.equal(archived.json.error, "@bob is already archived: bob-x."); + const notSearch = await call(lead, { slug: "bob-x", handle: "alice", action: "never" }); + assert.equal(notSearch.status, 400); + assert.match(String(notSearch.json.error), /not an X search channel/); + const badAction = await call(lead, { slug: "demo-search", handle: "alice", action: "follow" }); + assert.equal(badAction.status, 400); + assert.match(String(badAction.json.error), /"action" must be one of archive, never, restore/); + const stray = await call(lead, { slug: "demo-search", handle: "alice", action: "never", dryRun: true }); + assert.equal(stray.status, 400); +}); + +test("create-channel makes no X search channel on a site", async () => { + const onSite = await call(create, { + slug: "made-search", + fields: { name: "Made search", handling: "transcribe", url: "https://x.com/search?q=zephyr" }, + sites: [{ siteId: "demo-site" }], + }); + assert.equal(onSite.status, 400); + assert.equal(onSite.json.error, "made-search is an X search channel: it is never put on a site."); + assert.equal(await exists(path.join(ROOT, "channels", "made-search")), false); + const badQuery = await call(create, { + slug: "made-search", + fields: { name: "Made search", handling: "transcribe", platform: "x-search", xSearchQuery: "zephyr until:2025-01-01" }, + }); + assert.equal(badQuery.status, 400); + assert.match(String(badQuery.json.error), /Take until: out of the query/); + const site = JSON.parse(await readFile(path.join(ROOT, "sites", "demo-site", "site.json"), "utf8")); + assert.deepEqual(site.channels, []); +}); diff --git a/editor/app/api/ops/x-search-lead/route.ts b/editor/app/api/ops/x-search-lead/route.ts @@ -0,0 +1,46 @@ +import { NextResponse } from "next/server"; +import { + archiveXSearchLeadAction, + hideXSearchLeadAction, +} from "../../../channels/[slug]/xSearchActions"; +import { oneOf, ops, opsFail, optBool, optString, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, handle, action: "archive" | "never" | "restore", name?, fetch?, dryRun? } +// -> archive: { ok: true, slug, jobIds, jobId? } (dryRun: { ok, slug, fields, dryRun }) +// -> never | restore: { ok: true, exclude, changed } +// +// An X search channel's leads view, over HTTP (release 38 lane S). "archive" +// is Archive this account: a `<handle>-x` X channel on NO site, created by +// the New channel form's path with its first post fetch started (`fetch: +// false` skips it), named `name` (or the handle) + " (X)". Refused: a channel +// that is not an X search channel, a handle that is not one, an account an X +// channel archives already, a slug taken. "never" is Never archive — the +// handle into the channel's `xSearch.exclude`, hidden from the leads — and +// "restore" undoes it. Read the leads with `get channel <slug> --leads`. +export async function POST(request: Request) { + return ops(request, ["slug", "handle", "action", "name", "fetch", "dryRun"], async (body) => { + const slug = reqSlug(body, "slug"); + const handle = reqString(body, "handle"); + const action = oneOf(body, "action", ["archive", "never", "restore"] as const); + if (action === "archive") { + const name = optString(body, "name"); + const res = await archiveXSearchLeadAction(slug, handle, { + ...(name ? { name } : {}), + ...(optBool(body, "dryRun") ? { dryRun: true } : {}), + ...(optBool(body, "fetch") === false ? { fetch: false } : {}), + }); + if (!res.ok) return opsFail(res.error); + if (res.dryRun) return NextResponse.json({ ok: true, dryRun: true, slug: res.slug, fields: res.fields }); + const jobIds = res.jobIds ?? []; + return NextResponse.json({ ok: true, slug: res.slug, jobIds, ...(jobIds.length === 1 ? { jobId: jobIds[0] } : {}) }); + } + if (body.dryRun !== undefined || body.name !== undefined || body.fetch !== undefined) { + return opsFail(`"dryRun", "name" and "fetch" apply only to action "archive"`); + } + const res = await hideXSearchLeadAction(slug, handle, action === "never"); + if (!res.ok) return opsFail(res.error); + return NextResponse.json({ ok: true, exclude: res.exclude ?? [], changed: res.changed === true }); + }); +} diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -42,6 +42,8 @@ export type SocialChannelState = { platform?: string; // A forum thread's browser session (its host's profile), when it is one. forumSession?: ForumSessionStatus; + // An X search channel (release 38): its query and where its walk stands. + search?: { query: string; walk: string }; }; export function SocialChannelPanel({ @@ -139,7 +141,16 @@ export function SocialChannelPanel({ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> <h2 className="text-sm font-medium">Posts</h2> <span className="text-xs text-muted-foreground"> - {forum ? state.handle : `@${state.handle}`} · {state.fetcherLabel} + {state.search ? ( + <> + X search <code aria-label="x search query" className="font-mono">{state.search.query}</code> + </> + ) : forum ? ( + state.handle + ) : ( + `@${state.handle}` + )}{" "} + · {state.fetcherLabel} </span> </div> @@ -173,6 +184,7 @@ export function SocialChannelPanel({ {state.canFetchOlder && ( <Stat label="Older posts" value={state.olderStatus} /> )} + {state.search && <Stat label="Search walk" value={state.search.walk} />} </dl> {state.availableFetchers.length > 1 && ( @@ -253,11 +265,15 @@ export function SocialChannelPanel({ type="button" onClick={() => run(true)} disabled={pending} - aria-label="refetch full history" - title="Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + aria-label={state.search ? "search again from the top" : "refetch full history"} + title={ + state.search + ? "Walk the whole search again from its newest window. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + : "Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + } className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" > - Re-fetch full history + {state.search ? "Search again from the top" : "Re-fetch full history"} </button> {state.canFetchOlder && ( <button diff --git a/editor/app/channels/[slug]/components/XSearchLeadsPanel.tsx b/editor/app/channels/[slug]/components/XSearchLeadsPanel.tsx @@ -0,0 +1,187 @@ +"use client"; + +// AN X SEARCH CHANNEL'S LEADS (release 38 lane S): the accounts its matching +// posts came from, most matches first — each with Archive this account (a +// `<handle>-x` channel on no site, its first fetch started) and Never archive +// (hidden here, kept in the channel's `xSearch.exclude`; Restore undoes it). +// No model: the counts are the channel's own posts. + +import { useState, useTransition } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import type { XSearchLeads } from "yt-dlp-transcript-common/lib/xSearch/leads"; +import { archiveXSearchLeadAction, hideXSearchLeadAction } from "../xSearchActions"; + +const day = (iso: string) => iso.slice(0, 10); + +export function XSearchLeadsPanel({ slug, leads }: { slug: string; leads: XSearchLeads }) { + const router = useRouter(); + const [pending, startTransition] = useTransition(); + const [note, setNote] = useState<{ kind: "ok" | "error"; text: string; href?: string } | null>(null); + + const archive = (handle: string, name?: string) => + startTransition(async () => { + setNote(null); + const res = await archiveXSearchLeadAction(slug, handle, name ? { name } : {}); + if (!res.ok) { + setNote({ kind: "error", text: res.error }); + return; + } + setNote({ + kind: "ok", + text: `Created ${res.slug} on no site${res.jobIds?.length ? "; its first fetch is queued" : ""}.`, + href: `/channels/${res.slug}`, + }); + router.refresh(); + }); + + const hide = (handle: string, hidden: boolean) => + startTransition(async () => { + setNote(null); + const res = await hideXSearchLeadAction(slug, handle, hidden); + if (!res.ok) { + setNote({ kind: "error", text: res.error }); + return; + } + router.refresh(); + }); + + return ( + <section data-x-search-leads="" className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="text-sm font-medium">Leads</h2> + <span aria-label="leads summary" className="text-xs text-muted-foreground"> + {leads.authors} account{leads.authors === 1 ? "" : "s"} across {leads.posts} matching post + {leads.posts === 1 ? "" : "s"} + {leads.hidden.length > 0 ? ` · ${leads.hidden.length} hidden` : ""} + </span> + </div> + + {note && ( + <p role={note.kind === "error" ? "alert" : "status"} className={`text-xs ${note.kind === "error" ? "text-destructive" : "text-success"}`}> + {note.text}{" "} + {note.href && ( + <Link href={note.href} className="underline"> + Open it + </Link> + )} + </p> + )} + + {leads.leads.length === 0 ? ( + <p className="text-sm text-muted-foreground">No matching posts yet: fetch the search.</p> + ) : ( + <div className="overflow-x-auto"> + <table className="w-full min-w-[40rem] text-sm"> + <thead> + <tr className="border-b border-border text-left text-xs uppercase tracking-wide text-muted-foreground"> + <th className="py-1 pr-3 font-medium">Account</th> + <th className="py-1 pr-3 font-medium">Matches</th> + <th className="py-1 pr-3 font-medium">First – last</th> + <th className="py-1 pr-3 font-medium">Sample</th> + <th className="py-1 font-medium" /> + </tr> + </thead> + <tbody> + {leads.leads.map((lead) => ( + <tr key={lead.key} data-x-lead={lead.key} className="border-b border-border align-top last:border-0"> + <td className="py-2 pr-3"> + <a + href={`https://x.com/${lead.handle}`} + target="_blank" + rel="noopener noreferrer" + className="font-mono underline" + > + @{lead.handle} + </a> + {lead.name && <div className="text-xs text-muted-foreground">{lead.name}</div>} + </td> + <td className="py-2 pr-3 font-mono" aria-label={`matches for ${lead.handle}`}> + {lead.count} + {lead.reposts > 0 && ( + <span className="text-xs text-muted-foreground"> ({lead.reposts} repost{lead.reposts === 1 ? "" : "s"})</span> + )} + </td> + <td className="py-2 pr-3 font-mono text-xs whitespace-nowrap"> + {day(lead.first)} – {day(lead.last)} + </td> + <td className="py-2 pr-3 text-xs"> + <a href={lead.sample.url} target="_blank" rel="noopener noreferrer" className="hover:underline"> + {lead.sample.text || "(no text)"} + </a> + </td> + <td className="py-2"> + {lead.archivedAs?.length ? ( + <span className="text-xs text-muted-foreground"> + Archived as{" "} + {lead.archivedAs.map((s, i) => ( + <span key={s}> + {i > 0 ? ", " : ""} + <Link href={`/channels/${s}`} className="underline"> + {s} + </Link> + </span> + ))} + </span> + ) : ( + <div className="flex flex-wrap gap-2"> + <button + type="button" + onClick={() => archive(lead.handle, lead.name)} + disabled={pending} + aria-label={`archive ${lead.handle}`} + className="whitespace-nowrap rounded-md border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50" + > + Archive this account + </button> + <button + type="button" + onClick={() => hide(lead.handle, true)} + disabled={pending} + aria-label={`never archive ${lead.handle}`} + className="whitespace-nowrap rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-muted disabled:opacity-50" + > + Never archive + </button> + </div> + )} + </td> + </tr> + ))} + </tbody> + </table> + {leads.more > 0 && ( + <p className="mt-2 text-xs text-muted-foreground"> + {leads.more} more account{leads.more === 1 ? "" : "s"} with fewer matches not listed. + </p> + )} + </div> + )} + + {leads.hidden.length > 0 && ( + <details data-x-search-hidden="" className="text-sm"> + <summary className="cursor-pointer text-xs text-muted-foreground"> + Never archive ({leads.hidden.length}) + </summary> + <ul className="mt-2 flex flex-col gap-1"> + {leads.hidden.map((h) => ( + <li key={h.handle} className="flex items-center gap-2"> + <span className="font-mono">@{h.handle}</span> + <span className="text-xs text-muted-foreground">{h.count} match{h.count === 1 ? "" : "es"}</span> + <button + type="button" + onClick={() => hide(h.handle, false)} + disabled={pending} + aria-label={`restore ${h.handle}`} + className="rounded-md border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50" + > + Restore + </button> + </li> + ))} + </ul> + </details> + )} + </section> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -23,6 +23,10 @@ import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoPa import { SocialChannelPanel } from "./components/SocialChannelPanel"; import { WaybackPagesPanel } from "./components/WaybackPagesPanel"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk"; +import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; +import { XSearchLeadsPanel } from "./components/XSearchLeadsPanel"; import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server"; import { waybackCaptureDate } from "yt-dlp-transcript-common/lib/wayback"; import { listPostFetchersFor } from "./socialActions"; @@ -205,6 +209,9 @@ export default async function ChannelDetailPage({ })), } : null; + // An X SEARCH channel (release 38): its query, its walk and its leads. + const xSearch = isXSearchChannel(config) && config.xSearch ? config.xSearch : null; + const leads = xSearch ? await readXSearchLeads(paths, slug) : null; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> @@ -243,9 +250,18 @@ export default async function ChannelDetailPage({ accountUrl: config.url, platform: config.platform, ...(forumSession ? { forumSession } : {}), + ...(xSearch + ? { + search: { query: xSearch.query, walk: describeXSearchWalk(fetchState?.search) }, + canFetchOlder: false, + // Only gallery-dl can walk a search: no method to switch to. + availableFetchers: [], + } + : {}), }} /> )} + {leads && leads.ok && <XSearchLeadsPanel slug={slug} leads={leads} />} {/* THE SAME DANGER ZONE A VIDEO CHANNEL HAS, which a social channel used to lack entirely: this branch returns before the stage list, so a misspelled X channel could not be renamed from the editor. The diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -21,6 +21,8 @@ import { } from "yt-dlp-transcript-common/controller/channels"; import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { emptyAccountOlderProblem, @@ -197,6 +199,8 @@ export async function fetchPostsAction( // A Wayback pages channel is never fetched: its captures are imported one // by one (import-page), as chosen — no unattended crawling (release 37). if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED }; + // An X search channel's one walk is its search windows (release 38). + if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL }; if (older) { await registerBuiltinSocialFetchers(); const problem = olderPostsProblem( diff --git a/editor/app/channels/[slug]/xSearchActions.ts b/editor/app/channels/[slug]/xSearchActions.ts @@ -0,0 +1,64 @@ +"use server"; + +// AN X SEARCH CHANNEL'S LEADS (release 38 lane S): "Archive this account" — +// a `<handle>-x` channel on NO site through the New channel form's own path +// (createChannelFromForm), its first post fetch started — and "Never archive" +// (the handle into the search channel's `xSearch.exclude`, hidden from the +// view) with its undo. The controllers' refusals, in their sentences +// (common/controller/xSearchLeads.ts). No model, no request but the new +// channel's fetch, which runs on X's queue like any other. + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + planArchiveXLead, + readXSearchLeads, + setXSearchLeadHidden, + type XSearchLeadsView, +} from "yt-dlp-transcript-common/controller/xSearchLeads"; +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { applyChannelFormPatch } from "../components/channelConfigToForm"; +import { createChannelFromForm } from "../actions"; + +export type XLeadActionResult = + | { ok: true; slug?: string; jobIds?: string[]; exclude?: string[]; changed?: boolean; dryRun?: boolean; fields?: Record<string, string> } + | { ok: false; error: string }; + +export async function readXSearchLeadsAction( + slug: string, + limit?: number, +): Promise<XSearchLeadsView | { ok: false; error: string }> { + return readXSearchLeads(getPaths(), slug, limit !== undefined ? { limit } : {}); +} + +// Archive this account: plan (refused when the account is archived already +// or the slug is taken), then create through the form's path — on no site, +// "Fetch posts now" ticked. `dryRun` answers the plan and creates nothing. +export async function archiveXSearchLeadAction( + slug: string, + handle: string, + opts: { name?: string; dryRun?: boolean; fetch?: boolean } = {}, +): Promise<XLeadActionResult> { + const plan = await planArchiveXLead(getPaths(), slug, handle, opts.name); + if (!plan.ok) return plan; + if (opts.dryRun) return { ok: true, slug: plan.slug, fields: plan.fields, dryRun: true }; + const fd = new FormData(); + applyChannelFormPatch(fd, plan.fields); + fd.set("slug", plan.slug); + if (opts.fetch !== false) fd.set("fetchPostsNow", "on"); + const created = await createChannelFromForm(fd); + if (!created.ok) return { ok: false, error: created.error }; + safeRevalidate([`/channels/${slug}`, `/channels/${created.slug}`, "/channels"]); + return { ok: true, slug: created.slug, jobIds: created.jobIds }; +} + +// Never archive (hidden: true) and its undo (hidden: false). +export async function hideXSearchLeadAction( + slug: string, + handle: string, + hidden: boolean, +): Promise<XLeadActionResult> { + const res = await setXSearchLeadHidden(getPaths(), slug, handle, hidden); + if (!res.ok) return res; + safeRevalidate([`/channels/${slug}`]); + return { ok: true, exclude: res.exclude, changed: res.changed }; +} diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -36,6 +36,8 @@ import { type Site, } from "yt-dlp-transcript-common/lib/site"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site"; +import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; import { saveSettings } from "../settings/saveSettings"; import { LANES, @@ -138,6 +140,22 @@ export async function probeChannelUrlAction( const platformDetected = detectPlatform(trimmed); const queueKey = queueKeyForUrl(trimmed); + // An X search page (release 38): nothing to probe — the query is the + // channel. No request; a name from the query. + const searchQuery = xSearchQueryOfUrl(trimmed); + if (searchQuery !== null) { + const query = xSearchFromUrl(trimmed)?.query || searchQuery; + return { + ok: true, + name: `X search: ${query.length > 60 ? `${query.slice(0, 59)}…` : query}`, + platformDetected: "twitter", + queueKey, + queueKnown: true, + sourceKind: "social", + postFetcher: "x-gallery-dl", + }; + } + // Social accounts never go through yt-dlp: it cannot enumerate a timeline on // either platform (no twitter:user extractor exists). Route them to the // fetcher's own probe instead — for Bluesky that is a free, instant @@ -240,6 +258,11 @@ export async function createChannelFromForm( const requests = parseSiteMembershipsField( formData.get("siteMembershipsJson"), ); + // An X search channel is never put on a site (release 38): refused before + // the channel exists, so nothing is half-made. + if (config.xSearch && requests && requests.length > 0) { + return fail(X_SEARCH_NOT_ON_A_SITE(slug)); + } if (requests) { siteWrites = planSiteMembershipWrites(paths, slug, requests); } @@ -340,6 +363,9 @@ export async function updateChannelAction( const requests = parseSiteMembershipsField( formData.get("siteMembershipsJson"), ); + if (parsed.config.xSearch && requests && requests.length > 0) { + return { error: X_SEARCH_NOT_ON_A_SITE(slug), values }; + } if (requests) { siteWrites = planSiteMembershipWrites(paths, slug, requests); } diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -38,6 +38,8 @@ import { handleFromAccountUrl } from "yt-dlp-transcript-common/social/fetchers"; import { isWaybackPagesUrl } from "yt-dlp-transcript-common/lib/waybackPages/urls"; import { waybackTargetFromUrl, waybackTargetHost } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { WaybackTargetsField } from "./WaybackTargetsField"; +import { XSearchFields } from "./XSearchFields"; +import { isXSearchUrl, xSearchFromUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; import { probeChannelUrlAction } from "../actions"; import { Field, @@ -92,6 +94,12 @@ function shortSlugBase(title: string, max = 48): string { function slugCandidateFromUrl(url: string): string { const trimmed = url.trim(); if (!trimmed) return ""; + // An X search page: its query, not the word "search". + const searched = xSearchFromUrl(trimmed)?.query; + if (searched) { + const base = shortSlugBase(slugify(searched), 40); + return base ? `${base}-x-search` : ""; + } try { const u = new URL(trimmed); const segs = u.pathname @@ -194,7 +202,7 @@ export function ChannelForm({ c?.handling === "transcribe" ? "transcribe" : "youtube", ); const [handlingTouched, setHandlingTouched] = useState(false); - const [platform, setPlatform] = useState<string>(c?.platform ?? ""); + const [platform, setPlatform] = useState<string>(c?.xSearch ? "x-search" : (c?.platform ?? "")); const [platformTouched, setPlatformTouched] = useState(false); // Social sources are ingested into the posts corpus, not the video pipeline, // so every video-only control below is hidden for them. In edit mode this is @@ -205,7 +213,12 @@ export function ChannelForm({ const editSourceKind = c?.sourceKind ?? "video"; const isSocial = isEdit ? editSourceKind === "social" - : isSocialPlatform(platform as Platform) || isSocialPlatform(detectPlatform(url)) || isWaybackPagesUrl(url); + : isSocialPlatform(platform as Platform) || + isSocialPlatform(detectPlatform(url)) || + isWaybackPagesUrl(url) || + platform === "x-search"; + // An X search channel (release 38): a query across accounts, never on a site. + const isXSearch = isEdit ? Boolean(c?.xSearch) : platform === "x-search"; // A Wayback pages channel (release 37): captures of pages, no fetcher; its // scope is its targets. const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage"; @@ -224,7 +237,9 @@ export function ChannelForm({ // NO network call. Only fills untouched fields, so a hand-set value sticks. useEffect(() => { if (isEdit) return; - const detected = detectPlatform(url) ?? (isWaybackPagesUrl(url) ? "webpage" : null); + const detected = isXSearchUrl(url) + ? "x-search" + : (detectPlatform(url) ?? (isWaybackPagesUrl(url) ? "webpage" : null)); if (!platformTouched) setPlatform(detected ?? ""); if (!handlingTouched && url.trim()) { setHandling(detected === "youtube" ? "youtube" : "transcribe"); @@ -239,7 +254,7 @@ export function ChannelForm({ if (!handleTouched) { setSocialHandle(handleFromAccountUrl(url) ?? ""); } - if (detected === "twitter") setPostFetcher("x-gallery-dl"); + if (detected === "twitter" || detected === "x-search") setPostFetcher("x-gallery-dl"); else if (detected === "bluesky") setPostFetcher("bluesky-atproto"); // A forum thread URL (…/threads/<title>.<id>/): the thread walker. else if (detected === "xenforo") setPostFetcher("xenforo-thread"); @@ -269,7 +284,7 @@ export function ChannelForm({ setName(res.name); if (!slugTouched) setSlug(slugify(res.name)); } - if (!platformTouched) setPlatform(res.platformDetected ?? ""); + if (!platformTouched) setPlatform(isXSearchUrl(url) ? "x-search" : (res.platformDetected ?? "")); // A social URL resolves through the fetcher's own probe, which also // reports which fetcher claimed it and the canonical handle. if (res.postFetcher) setPostFetcher(res.postFetcher); @@ -343,11 +358,17 @@ export function ChannelForm({ )} </Section> <Section title="Sites"> + {isXSearch ? ( + <span data-x-search-no-site="" className="text-xs text-muted-foreground"> + An X search channel is never put on a site. + </span> + ) : ( <SiteMembershipsSection sites={sites} initialMemberships={initialMemberships} activeSiteId={activeSiteId} /> + )} </Section> <Section title="Source"> {isEdit ? ( @@ -386,7 +407,7 @@ export function ChannelForm({ <SeededSelect state={state} name="platform" - initial={c?.platform ?? ""} + initial={c?.xSearch ? "x-search" : (c?.platform ?? "")} className="rounded border border-border bg-card px-2 py-1 text-sm" > <option value="">Auto (detect from URL)</option> @@ -398,6 +419,7 @@ export function ChannelForm({ <option value="archiveorg">archive.org</option> <option value="bitchute">BitChute</option> <option value="twitter">X / Twitter (posts)</option> + <option value="x-search">X search (posts from any account)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> <option value="webpage">Wayback pages (captures of pages)</option> @@ -521,6 +543,7 @@ export function ChannelForm({ <option value="archiveorg">archive.org</option> <option value="bitchute">BitChute</option> <option value="twitter">X / Twitter (posts)</option> + <option value="x-search">X search (posts from any account)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> <option value="webpage">Wayback pages (captures of pages)</option> @@ -613,7 +636,10 @@ export function ChannelForm({ /> </> )} - {isSocial && !isWaybackPages && ( + {isSocial && isXSearch && ( + <XSearchFields {...(isEdit ? (c?.xSearch ? { initial: c.xSearch } : {}) : { derivedFrom: url })} /> + )} + {isSocial && !isWaybackPages && !isXSearch && ( <> {/* A social source is ingested into the posts corpus, so it carries its fetcher + handle instead of any of the video controls. */} diff --git a/editor/app/channels/components/XSearchFields.tsx b/editor/app/channels/components/XSearchFields.tsx @@ -0,0 +1,110 @@ +"use client"; + +// An X search channel's fields on the channel form (release 38): the query as +// X's search box takes it, the days walked between, the window size and a +// language. Posted as xSearch* fields; parseChannelForm refuses what the +// channel cannot hold, with a sentence. "Never archive"'s hidden authors ride +// along unchanged in a hidden field (they are edited on the channel page). + +import { useState } from "react"; +import { xSearchFromUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; +import type { XSearchConfig } from "yt-dlp-transcript-common/lib/xSearch/config"; + +export function XSearchFields({ + initial, + derivedFrom, +}: { + // Edit: the stored search. Create: none — the query comes from the URL. + initial?: XSearchConfig; + derivedFrom?: string; +}) { + const fromUrl = derivedFrom ? xSearchFromUrl(derivedFrom) : null; + const seed = initial ?? fromUrl ?? undefined; + const [query, setQuery] = useState(seed?.query ?? ""); + const [touched, setTouched] = useState(false); + // Create mode follows the URL until the query is typed by hand. + const shownQuery = !initial && !touched && fromUrl ? fromUrl.query : query; + const sinceSeed = initial?.since ?? fromUrl?.since ?? ""; + const untilSeed = initial?.until ?? fromUrl?.until ?? ""; + return ( + <fieldset data-x-search-fields="" className="flex flex-col gap-3 rounded-md border border-border px-3 py-2"> + <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground"> + X search + </legend> + <input type="hidden" name="sourceKind" value="social" /> + <input type="hidden" name="postFetcher" value="x-gallery-dl" /> + {initial?.exclude?.length ? ( + <input type="hidden" name="xSearchExclude" value={JSON.stringify(initial.exclude)} /> + ) : null} + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Query</span> + <input + type="text" + name="xSearchQuery" + value={shownQuery} + onChange={(e) => { + setQuery(e.target.value); + setTouched(true); + }} + aria-label="x search query" + placeholder={'"exact phrase" OR word -noise lang:en'} + className="rounded border border-border bg-card px-2 py-1 font-mono text-sm" + /> + <span className="text-xs text-muted-foreground"> + As typed in X&apos;s search box: OR, &quot;quotes&quot;, -term, from:, to:, @name, url:, filter: and + lang: all work. Leave since: and until: out — the dates below set the search windows. + </span> + </label> + <div className="flex flex-wrap gap-3"> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Since</span> + <input + type="date" + name="xSearchSince" + defaultValue={sinceSeed} + aria-label="x search since" + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Until</span> + <input + type="date" + name="xSearchUntil" + defaultValue={untilSeed} + aria-label="x search until" + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Window (months)</span> + <input + type="number" + name="xSearchWindowMonths" + min={1} + max={12} + defaultValue={initial?.windowMonths ?? ""} + placeholder="3" + aria-label="x search window months" + className="w-24 rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Language</span> + <input + type="text" + name="xSearchLang" + defaultValue={initial?.lang ?? ""} + placeholder="any" + aria-label="x search language" + className="w-24 rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + </div> + <span className="text-xs text-muted-foreground"> + A fetch searches back from Until (blank: today) to Since (blank: until a year of windows finds nothing), + newest first, a window at a time; later fetches search the new days. Needs an X login. Never on a site. + </span> + </fieldset> + ); +} diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -64,6 +64,14 @@ export const CHANNEL_FORM_VALUES = [ // A Wayback pages channel's targets (release 37): a JSON array, or (in a // patch) the array itself. "waybackTargets", + // An X search channel's query and dates (release 38); `xSearchExclude` is a + // JSON array of handles (or, in a patch, the array itself). + "xSearchQuery", + "xSearchSince", + "xSearchUntil", + "xSearchWindowMonths", + "xSearchLang", + "xSearchExclude", ] as const; export type ChannelFormFlag = (typeof CHANNEL_FORM_FLAGS)[number]; @@ -131,6 +139,12 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { put(fd, "mirrorOf", config.mirror?.of.join(", ")); if (config.wayback?.targets.length) fd.set("waybackTargets", JSON.stringify(config.wayback.targets)); if (config.wayback?.auto) fd.set("waybackAuto", "on"); + put(fd, "xSearchQuery", config.xSearch?.query); + put(fd, "xSearchSince", config.xSearch?.since); + put(fd, "xSearchUntil", config.xSearch?.until); + putNum(fd, "xSearchWindowMonths", config.xSearch?.windowMonths); + put(fd, "xSearchLang", config.xSearch?.lang); + if (config.xSearch?.exclude?.length) fd.set("xSearchExclude", JSON.stringify(config.xSearch.exclude)); // Ticked when the check is on: said so, or the platform's default (an // Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch // that does not name it keeps what the channel has. @@ -176,7 +190,7 @@ export function applyChannelFormPatch( else fd.delete(key); continue; } - if (key === "waybackTargets" && Array.isArray(value)) { + if ((key === "waybackTargets" || key === "xSearchExclude") && Array.isArray(value)) { if (value.length > 0) fd.set(key, JSON.stringify(value)); else fd.delete(key); continue; @@ -212,7 +226,7 @@ export function validateChannelFormPatch(patch: ChannelConfigPatch): void { `"${key}" is not a channel config field — accepted: ${CHANNEL_FORM_FIELD_NAMES.join(", ")}`, ); } - if (key === "waybackTargets" && Array.isArray(value)) continue; + if ((key === "waybackTargets" || key === "xSearchExclude") && Array.isArray(value)) continue; if (key === "ytdlpExtraArgs" && Array.isArray(value)) { if (value.some((v) => typeof v !== "string")) { throw new Error(`"${key}" must be an array of strings`); diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -229,3 +229,78 @@ test("a form save keeps wayback.auto and the targets' filters; the checkbox and applyChannelFormPatch(fd, { waybackAuto: true }); assert.equal(parseChannelForm(fd).config.wayback?.auto, true); }); + +// Release 38 lane S: an X SEARCH channel — a pasted x.com/search URL (its +// dates lifted into the channel's), or the platform choice "X search" with +// the query fields. platform twitter, sourceKind social, gallery-dl, the URL +// rebuilt from the query, no handle; the walk's own operators refused; the +// ops patch round-trips every field, the hidden authors included. +test("an X search channel from a pasted search URL: the query, its dates lifted out, the URL rebuilt", () => { + const { config } = parseChannelForm( + form({ + handling: "transcribe", + url: "https://x.com/search?q=%22zephyr%20archive%22%20OR%20zephyrs%20since%3A2025-01-01&src=typed_query", + }), + ); + assert.equal(config.platform, "twitter"); + assert.equal(config.sourceKind, "social"); + assert.equal(config.postFetcher, "x-gallery-dl"); + assert.equal(config.socialHandle, undefined); + assert.deepEqual(config.xSearch, { query: '"zephyr archive" OR zephyrs', since: "2025-01-01" }); + assert.equal(config.url, "https://x.com/search?q=%22zephyr%20archive%22%20OR%20zephyrs&f=live"); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("xSearch")); +}); + +test("the X search choice with its fields; refusals in sentences", () => { + const { config } = parseChannelForm( + form({ + handling: "transcribe", + platform: "x-search", + xSearchQuery: "zephyr -from:spam_bot", + xSearchSince: "2024-01-01", + xSearchUntil: "2025-01-01", + xSearchWindowMonths: "1", + xSearchLang: "EN", + }), + ); + assert.deepEqual(config.xSearch, { + query: "zephyr -from:spam_bot", + since: "2024-01-01", + until: "2025-01-01", + windowMonths: 1, + lang: "en", + }); + assert.equal(config.platform, "twitter"); + const refused = (fields: Record<string, string>) => () => + parseChannelForm(form({ handling: "transcribe", platform: "x-search", ...fields })); + assert.throws(refused({}), /needs a query/); + assert.throws(refused({ xSearchQuery: "zephyr since:2024-01-01" }), /Take since: out of the query/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchSince: "2024-02-30" }), /since date must be a day/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchSince: "2024-02-01", xSearchUntil: "2024-01-01" }), /must be after its since/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchWindowMonths: "13" }), /1–12 months/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchLang: "english!" }), /not a language code/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchExclude: "[\"bad handle\"]" }), /hidden authors/); + // An ordinary X account URL is not a search. + const account = parseChannelForm(form({ handling: "transcribe", url: "https://x.com/example_user" })).config; + assert.equal(account.xSearch, undefined); + assert.equal(account.socialHandle, "example_user"); +}); + +test("the ops patch round-trips a search channel, its hidden authors kept", () => { + const stored = { + handling: "transcribe" as const, + name: "Zephyr search", + sourceKind: "social" as const, + platform: "twitter" as const, + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + xSearch: { query: "zephyr", since: "2024-01-01", lang: "en", exclude: ["alice"] }, + }; + const fd = channelConfigToFormData(stored); + assert.deepEqual(parseChannelForm(fd).config.xSearch, stored.xSearch); + validateChannelFormPatch({ xSearchQuery: "zephyr OR breeze", xSearchExclude: ["alice", "bob"] }); + applyChannelFormPatch(fd, { xSearchQuery: "zephyr OR breeze", xSearchExclude: ["alice", "bob"], xSearchSince: "" }); + const next = parseChannelForm(fd).config; + assert.deepEqual(next.xSearch, { query: "zephyr OR breeze", lang: "en", exclude: ["alice", "bob"] }); + assert.equal(next.url, "https://x.com/search?q=zephyr%20OR%20breeze&f=live"); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -28,6 +28,16 @@ import { type WaybackPagesConfig, } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { isWaybackPagesUrl } from "yt-dlp-transcript-common/lib/waybackPages/urls"; +import { + coerceXSearchConfig, + isXSearchUrl, + X_SEARCH_WINDOW_MONTHS_MAX, + xLeadHandle, + xSearchFromUrl, + xSearchQueryProblem, + xSearchUrl, + type XSearchConfig, +} from "yt-dlp-transcript-common/lib/xSearch/config"; import { isCookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { isDownloadFormatPreset, @@ -75,6 +85,7 @@ export const CHANNEL_FORM_FIELDS = [ "recordedDate", "mirror", "wayback", + "xSearch", ] as const satisfies ReadonlyArray<keyof ChannelConfig>; // Maps FormData -> ChannelConfig. Throws on invalid input so the server @@ -90,11 +101,21 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { const slug = String(formData.get("slug") ?? "").trim(); - const url = stringOrUndef(formData, "url"); + const typedUrl = stringOrUndef(formData, "url"); const platformRaw = String(formData.get("platform") ?? ""); - const platform: Platform | undefined = PLATFORM_VALUES.includes( - platformRaw as Platform, - ) + // AN X SEARCH CHANNEL (release 38): the platform choice "X search", or an X + // search page's URL (x.com/search?q=…) with the platform on Auto or X. Its + // URL is always the search page of its query, rebuilt here. + const xSearch = + platformRaw === X_SEARCH_PLATFORM_CHOICE || + ((platformRaw === "" || platformRaw === "twitter") && + (isXSearchUrl(typedUrl) || (platformRaw === "twitter" && stringOrUndef(formData, "xSearchQuery") !== undefined))) + ? parseXSearchFields(formData, typedUrl) + : undefined; + const url = xSearch ? xSearchUrl(xSearch.query) : typedUrl; + const platform: Platform | undefined = xSearch + ? "twitter" + : PLATFORM_VALUES.includes(platformRaw as Platform) ? (platformRaw as Platform) : (detectPlatform(url) ?? // A Wayback Machine URL of a page that is not a video (a capture, or a @@ -112,20 +133,25 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { : sourceKindRaw === "video" ? "video" : undefined; - const postFetcher = - sourceKind === "social" ? stringOrUndef(formData, "postFetcher") : undefined; + // A search channel is walked by the one fetcher that can (gallery-dl). + const postFetcher = xSearch + ? "x-gallery-dl" + : sourceKind === "social" + ? stringOrUndef(formData, "postFetcher") + : undefined; const socialHandleRaw = - sourceKind === "social" ? stringOrUndef(formData, "socialHandle") : undefined; + sourceKind === "social" && !xSearch ? stringOrUndef(formData, "socialHandle") : undefined; // A Wayback pages channel's scope: the form's target rows (one hidden JSON // field), else one target derived from the URL. const wayback = platform === "webpage" ? parseWaybackTargets(formData, url) : undefined; const socialHandle = socialHandleRaw?.replace(/^@/, "") || (wayback ? waybackTargetHost(wayback.targets[0]) : undefined) || - (sourceKind === "social" && url + (sourceKind === "social" && url && !xSearch ? (handleFromAccountUrl(url) ?? undefined) : undefined); - if (sourceKind === "social" && !socialHandle) { + // A search channel has no account: its query is what it archives. + if (sourceKind === "social" && !socialHandle && !xSearch) { throw new Error( "A social source needs an account handle (could not derive one from the URL)", ); @@ -436,10 +462,77 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { } if (mirrorOf.length > 0) config.mirror = { of: mirrorOf }; if (wayback) config.wayback = wayback; + if (xSearch) config.xSearch = xSearch; return { name, slug, config }; } +// The platform select's value for an X search channel: not a platform (the +// channel's platform is "twitter"), a kind of X channel. +export const X_SEARCH_PLATFORM_CHOICE = "x-search"; + +// An X search channel's query and dates: the form's fields (xSearchQuery, +// xSearchSince, xSearchUntil, xSearchWindowMonths, xSearchLang, and the +// hidden xSearchExclude carried from the stored config), else what a pasted +// x.com/search URL says. Refused here, with a sentence, rather than dropped +// by the reader. +function parseXSearchFields(formData: FormData, url: string | undefined): XSearchConfig { + const fromUrl = xSearchFromUrl(url); + const query = stringOrUndef(formData, "xSearchQuery") ?? fromUrl?.query ?? ""; + const problem = xSearchQueryProblem(query); + if (problem) throw new Error(problem); + const day = (key: string, fallback: string | undefined, label: string): string | undefined => { + const raw = stringOrUndef(formData, key) ?? fallback; + if (raw === undefined) return undefined; + if (!/^\d{4}-\d{2}-\d{2}$/.test(raw) || !coerceXSearchConfig({ query: "x", since: raw })?.since) { + throw new Error(`The X search's ${label} date must be a day (YYYY-MM-DD), not "${raw}"`); + } + return raw; + }; + const since = day("xSearchSince", fromUrl?.since, "since"); + const until = day("xSearchUntil", fromUrl?.until, "until"); + if (since && until && until <= since) { + throw new Error(`The X search's until date (${until}) must be after its since date (${since})`); + } + const monthsRaw = stringOrUndef(formData, "xSearchWindowMonths"); + let windowMonths: number | undefined; + if (monthsRaw !== undefined) { + const n = Number(monthsRaw); + if (!Number.isInteger(n) || n < 1 || n > X_SEARCH_WINDOW_MONTHS_MAX) { + throw new Error(`The X search's window must be 1–${X_SEARCH_WINDOW_MONTHS_MAX} months`); + } + windowMonths = n; + } + const langRaw = stringOrUndef(formData, "xSearchLang")?.toLowerCase(); + if (langRaw !== undefined && !coerceXSearchConfig({ query: "x", lang: langRaw })?.lang) { + throw new Error(`"${langRaw}" is not a language code (en, de, pt-br …)`); + } + let exclude: string[] = []; + const excludeRaw = stringOrUndef(formData, "xSearchExclude"); + if (excludeRaw !== undefined) { + let parsed: unknown; + try { + parsed = JSON.parse(excludeRaw); + } catch { + throw new Error("The X search's hidden authors must be a JSON list of handles"); + } + if (!Array.isArray(parsed) || parsed.some((h) => xLeadHandle(h) === null)) { + throw new Error("The X search's hidden authors must be a JSON list of handles"); + } + exclude = parsed.map((h) => xLeadHandle(h)!); + } + const config = coerceXSearchConfig({ + query, + ...(since ? { since } : {}), + ...(until ? { until } : {}), + ...(windowMonths ? { windowMonths } : {}), + ...(langRaw ? { lang: langRaw } : {}), + ...(exclude.length > 0 ? { exclude } : {}), + }); + if (!config) throw new Error("An X search channel needs a query (what you would type in X's search box)."); + return config; +} + // `waybackTargets` (a JSON array of {url, match, from?, to?, …}) as the // channel's Wayback scope; with none given, one target derived from the URL // (lib/waybackPages/config.ts, waybackTargetFromUrl). A row that is not a diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs @@ -40,6 +40,32 @@ if (process.env.E2E_FAKE_GALLERY_DL_AUTH_FAIL === "1") { process.exit(1); } +// AN X SEARCH (release 38): a search URL (x.com/search?q=…) answers posts by +// SEVERAL accounts, bounded by the query's since:/until: days and its max_id: +// resume point, newest first — what gallery-dl's search extractor prints for a +// query across accounts. The query's words are not matched: every window gets +// the posts dated inside it. +if (/\/search(\?|$)/.test(url)) { + const q = new URL(url).searchParams.get("q") ?? ""; + const term = (k) => (q.split(" ").find((t) => t.startsWith(k + ":")) ?? "").slice(k.length + 1) || undefined; + const since = term("since") ?? "0000-00-00"; + const until = term("until") ?? "9999-99-99"; + const maxId = term("max_id"); + const SEARCH = [ + ["1899100000000000004", "2026-06-10 10:00:00", "leadone", "Lead One", "zephyr archives, first"], + ["1899100000000000003", "2026-06-05 09:00:00", "leadtwo", "Lead Two", "the zephyr again"], + ["1899100000000000002", "2026-05-10 08:00:00", "leadone", "Lead One", "zephyr archives, second"], + ["1899100000000000001", "2026-05-01 07:00:00", "leadthree", "Lead Three", "one zephyr more"], + ]; + const hits = SEARCH.filter(([id, date]) => date.slice(0, 10) >= since && date.slice(0, 10) < until) + .filter(([id]) => !maxId || BigInt(id) <= BigInt(maxId)); + for (const [id, date, name, nick, content] of hits.slice(0, limit)) { + const author = { name, nick }; + process.stdout.write(JSON.stringify({ tweet_id: id, conversation_id: id, date, content, lang: "en", author, user: author }) + "\n"); + } + process.exit(0); +} + const AUTHOR = { name: handle, nick: "Fake Tester" }; // Ids are deliberately > 2^53 so any accidental numeric parse would corrupt diff --git a/editor/e2e/x-search.spec.ts b/editor/e2e/x-search.spec.ts @@ -0,0 +1,109 @@ +// AN X SEARCH CHANNEL end to end (release 38 lane S): a search URL pasted into +// the New channel form makes one (its dates lifted into the form, the Sites +// section replaced by "never on a site"); its first fetch walks the search +// through the fake gallery-dl's search mode, which answers posts by several +// accounts; the channel page's Leads ranks them, Never archive hides one and +// Restore brings it back, and Archive this account creates `<handle>-x` on no +// site and fetches it. +// +// X is NEVER contacted: e2e/fixtures/bin/fake-gallery-dl.mjs answers every +// read. The login the search needs is a cookies-from-browser spec the fake +// ignores. + +import { test, expect } from "@playwright/test"; +import { readFile } from "node:fs/promises"; +import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings, writeSite } from "./helpers"; + +type Config = { + platform?: string; + sourceKind?: string; + postFetcher?: string; + socialHandle?: string; + url?: string; + xSearch?: { query: string; since?: string; until?: string; exclude?: string[] }; +}; + +const SEARCH_URL = + "https://x.com/search?q=zephyr%20since%3A2026-04-01%20until%3A2026-07-01&src=typed_query"; + +const archiveLines = async (slug: string): Promise<number> => { + const file = `${testPaths().transcriptsDir}/channels/${slug}/posts-archive`; + return (await pathExists(file)) ? (await readFile(resolvePath(file), "utf8")).split("\n").filter(Boolean).length : 0; +}; + +test("an X search channel: the form, the walk, the leads, Never archive and Archive this account", async ({ page }) => { + await resetData("empty"); + await writeSettings({ cookiesFromBrowser: "firefox" }); + await writeSite("demo-site", { siteTitle: "Demo" }); + await generateReport(page, "new"); + await page.goto("/channels/new"); + + await page.locator('input[name="url"]').fill(SEARCH_URL); + await expect(page.locator('select[name="platform"]')).toHaveValue("x-search"); + await expect(page.getByLabel("x search query")).toHaveValue("zephyr"); + await expect(page.getByLabel("x search since")).toHaveValue("2026-04-01"); + await expect(page.getByLabel("x search until")).toHaveValue("2026-07-01"); + await expect(page.locator("[data-x-search-no-site]")).toBeVisible(); + await expect(page.locator('input[name="socialHandle"]')).toHaveCount(0); + await expect(page.locator('select[name="audioFormat"]')).toHaveCount(0); + + await page.locator('input[name="name"]').fill("Zephyr search"); + await page.locator('input[name="slug"]').fill("zephyr-search"); + // "Fetch posts now" is on by default: the create starts the first walk. + await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); + + const configPath = `${testPaths().transcriptsDir}/channels/zephyr-search/config.json`; + await expect + .poll(async () => ((await pathExists(configPath)) ? await readJson<Config>(configPath) : null), { timeout: 15_000 }) + .toMatchObject({ + platform: "twitter", + sourceKind: "social", + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + xSearch: { query: "zephyr", since: "2026-04-01", until: "2026-07-01" }, + }); + expect((await readJson<Config>(configPath)).socialHandle).toBeUndefined(); + // Four matching posts by three accounts. + await expect.poll(() => archiveLines("zephyr-search"), { timeout: 30_000 }).toBe(4); + const site = await readJson<{ channels: { slug: string }[] }>(`${testPaths().transcriptsDir}/sites/demo-site/site.json`); + expect(site.channels).toEqual([]); + + await generateReport(page, "zephyr-search"); + await page.goto("/channels/zephyr-search"); + await expect(page.getByLabel("x search query")).toHaveText("zephyr"); + await expect(page.getByRole("button", { name: "fetch older posts" })).toHaveCount(0); + const leads = page.locator("[data-x-search-leads]"); + await expect(leads.getByLabel("leads summary")).toHaveText(/3 accounts across 4 matching posts/); + // Most matches first, then the most recent. + await expect(leads.locator("tr[data-x-lead]")).toHaveCount(3); + const rows = leads.locator("tr[data-x-lead]"); + await expect(rows.nth(0)).toHaveAttribute("data-x-lead", "leadone"); + await expect(rows.nth(1)).toHaveAttribute("data-x-lead", "leadtwo"); + await expect(rows.nth(2)).toHaveAttribute("data-x-lead", "leadthree"); + await expect(leads.getByLabel("matches for leadone")).toHaveText("2"); + + // Never archive: hidden here, kept in the channel's xSearch.exclude. + await leads.getByRole("button", { name: "never archive leadthree" }).click(); + await expect(leads.locator('tr[data-x-lead="leadthree"]')).toHaveCount(0); + await expect(leads.locator("[data-x-search-hidden] summary")).toHaveText("Never archive (1)"); + expect((await readJson<Config>(configPath)).xSearch?.exclude).toEqual(["leadthree"]); + await leads.locator("[data-x-search-hidden] summary").click(); + await leads.getByRole("button", { name: "restore leadthree" }).click(); + await expect(leads.locator('tr[data-x-lead="leadthree"]')).toHaveCount(1); + await expect.poll(async () => (await readJson<Config>(configPath)).xSearch?.exclude).toBeUndefined(); + + // Archive this account: leadone-x, an X channel on no site, its first fetch started. + await leads.getByRole("button", { name: "archive leadone" }).click(); + await expect(leads.getByRole("status")).toHaveText(/Created leadone-x on no site/); + const leadConfig = `${testPaths().transcriptsDir}/channels/leadone-x/config.json`; + await expect + .poll(async () => ((await pathExists(leadConfig)) ? await readJson<Config>(leadConfig) : null), { timeout: 15_000 }) + .toMatchObject({ platform: "twitter", sourceKind: "social", socialHandle: "leadone", url: "https://x.com/leadone" }); + await expect.poll(() => archiveLines("leadone-x"), { timeout: 30_000 }).toBe(3); + const after = await readJson<{ channels: { slug: string }[] }>(`${testPaths().transcriptsDir}/sites/demo-site/site.json`); + expect(after.channels).toEqual([]); + // The lead now names the channel that archives it. + await page.reload(); + await expect(page.locator('tr[data-x-lead="leadone"]')).toContainText("Archived as leadone-x"); + await expect(page.getByRole("button", { name: "archive leadone" })).toHaveCount(0); +}); diff --git a/mcp/src/protocol.test.ts b/mcp/src/protocol.test.ts @@ -49,6 +49,7 @@ const EXPECTED_TOOLS = [ "enqueue", "channel_coverage", "notes", + "x_search_leads", "generation_policy", "generate", "list_sources", diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -91,6 +91,7 @@ import { notesTool, type ToolAnswer, } from "./archivalTools"; +import { X_SEARCH_TOOLS, xSearchLeadsTool } from "./xSearchLeads"; import { GENERATION_TOOLS, generateTool, @@ -924,6 +925,8 @@ export const TOOLS: Tool[] = [ }, // Archival writes through the editor (release 19 A9): archivalTools.ts. ...(ARCHIVAL_TOOLS as unknown as Tool[]), + // An X search channel's leads, through the editor (release 38 lane S). + ...(X_SEARCH_TOOLS as unknown as Tool[]), // The Claude Code balance (release 27 S9): generation.ts. ...(GENERATION_TOOLS as unknown as Tool[]), { @@ -1321,6 +1324,8 @@ export function createServer( return fromAnswer(await enqueue(args, fetchClipDeps)); case "channel_coverage": return fromAnswer(await channelCoverageTool(args, fetchClipDeps)); + case "x_search_leads": + return fromAnswer(await xSearchLeadsTool(args, fetchClipDeps)); case "notes": return fromAnswer(await notesTool(args, fetchClipDeps)); case "generation_policy": diff --git a/mcp/src/xSearchLeads.test.ts b/mcp/src/xSearchLeads.test.ts @@ -0,0 +1,78 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit"; + +// ─── x_search_leads (release 38 lane S), through tools/call ─── +// +// One GET on the fake editor (/api/ops/channel/<slug>?leads=1); what is pinned +// is the request sent and the words the agent reads. + +const EDITOR = "http://editor.test"; + +test("x_search_leads: the leads read through the editor, ranked as it answers them", async () => { + const { deps, sent } = fakeEditor(() => ({ + status: 200, + body: { + ok: true, + slug: "zephyr-search", + leads: { + query: "zephyr", + search: "zephyr · since 2025-01-01", + walk: "searched 2025-01-01 – 2026-10-21", + posts: 4, + authors: 3, + more: 1, + hidden: [{ handle: "spam_bot", count: 9 }], + leads: [ + { + handle: "alice", + name: "Alice", + count: 2, + reposts: 1, + first: "2025-02-01T00:00:00.000Z", + last: "2025-03-01T00:00:00.000Z", + sample: { url: "https://x.com/alice/status/1", text: "the zephyr archive", createdAt: "2025-03-01T00:00:00.000Z" }, + }, + { + handle: "bob", + count: 1, + reposts: 0, + first: "2025-04-01T00:00:00.000Z", + last: "2025-04-01T00:00:00.000Z", + sample: { url: "https://x.com/bob/status/2", text: "zephyr", createdAt: "2025-04-01T00:00:00.000Z" }, + archivedAs: ["bob-x"], + }, + ], + }, + }, + }), { ARCHILYZER_EDITOR_URL: EDITOR, WORKER_TOKEN: "t" }); + const client = await connectWith(deps); + const res = await client.callTool({ name: "x_search_leads", arguments: { channel: "zephyr-search", limit: 2 } }); + const url = new URL(sent[0].url); + assert.equal(url.pathname, "/api/ops/channel/zephyr-search"); + assert.equal(url.searchParams.get("leads"), "1"); + assert.equal(url.searchParams.get("limit"), "2"); + const t = textOf(res); + assert.match(t, /^X search zephyr-search: zephyr · since 2025-01-01/); + assert.match(t, /4 matching posts from 3 accounts/); + assert.match(t, /1\. @alice \(Alice\) — 2 matches \(1 reposts\), 2025-02-01 – 2025-03-01/); + assert.match(t, /2\. @bob — 1 match, 2025-04-01 – 2025-04-01 · archived as bob-x/); + assert.match(t, /… 1 more accounts/); + assert.match(t, /Never archive \(hidden\): @spam_bot/); +}); + +test("x_search_leads: refusals — no channel, a bad limit, the editor's own sentence", async () => { + const { deps } = fakeEditor(() => ({ status: 400, body: { ok: false, error: "demo is not an X search channel (its config has no xSearch query)." } }), { + ARCHILYZER_EDITOR_URL: EDITOR, + WORKER_TOKEN: "t", + }); + const client = await connectWith(deps); + const none = await client.callTool({ name: "x_search_leads", arguments: { channel: "" } }); + assert.ok(isError(none)); + assert.match(textOf(none), /channel is required/); + const bad = await client.callTool({ name: "x_search_leads", arguments: { channel: "demo", limit: 0 } }); + assert.match(textOf(bad), /limit is a whole number, 1–500/); + const refused = await client.callTool({ name: "x_search_leads", arguments: { channel: "demo" } }); + assert.ok(isError(refused)); + assert.match(textOf(refused), /the editor refused \(HTTP 400\): demo is not an X search channel/); +}); diff --git a/mcp/src/xSearchLeads.ts b/mcp/src/xSearchLeads.ts @@ -0,0 +1,100 @@ +import { describeEditorFailure, editorGet, type EditorDeps } from "./editorOps"; +import type { ToolAnswer } from "./archivalTools"; + +// ─── x_search_leads (release 38 lane S) ─── +// +// An X SEARCH channel's leads, read through the local editor +// (GET /api/ops/channel/<slug>?leads=1&limit=N): the accounts the channel's +// matching posts came from, most matches first, with each account's first and +// last matching day, a sample post, and whether an X channel archives it +// already. Read only: acting on a lead (archive the account on no site, never +// archive it) is the operator's — the channel page's Leads, or +// `pnpm ops x-search-lead`. An X search channel is never on a site, so only +// the editor can answer. + +const SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/i; +export const X_SEARCH_LEADS_MAX = 500; + +type Lead = { + handle: string; + name?: string; + count: number; + reposts: number; + first: string; + last: string; + sample: { url: string; text: string; createdAt: string }; + archivedAs?: string[]; +}; + +type LeadsBody = { + leads?: { + query?: string; + search?: string; + walk?: string; + leads?: Lead[]; + hidden?: Array<{ handle: string; count: number }>; + posts?: number; + authors?: number; + more?: number; + }; +}; + +export function renderXSearchLeads(slug: string, body: LeadsBody): string { + const l = body.leads ?? {}; + const lines: string[] = []; + lines.push(`X search ${slug}: ${l.search ?? l.query ?? "?"}`); + lines.push(`walk: ${l.walk ?? "?"} · ${l.posts ?? 0} matching posts from ${l.authors ?? 0} accounts`); + const leads = l.leads ?? []; + if (leads.length === 0) lines.push("No leads yet: the search has matched nothing (fetch it first)."); + for (const [i, lead] of leads.entries()) { + lines.push( + `${i + 1}. @${lead.handle}${lead.name ? ` (${lead.name})` : ""} — ${lead.count} match${lead.count === 1 ? "" : "es"}` + + (lead.reposts ? ` (${lead.reposts} reposts)` : "") + + `, ${lead.first.slice(0, 10)} – ${lead.last.slice(0, 10)}` + + (lead.archivedAs?.length ? ` · archived as ${lead.archivedAs.join(", ")}` : ""), + ); + lines.push(` ${lead.sample.createdAt.slice(0, 10)} ${lead.sample.url} — ${lead.sample.text}`); + } + if (l.more) lines.push(`… ${l.more} more accounts with fewer matches (raise limit).`); + if (l.hidden?.length) lines.push(`Never archive (hidden): ${l.hidden.map((h) => `@${h.handle}`).join(", ")}`); + return lines.join("\n"); +} + +export async function xSearchLeadsTool(args: Record<string, unknown>, deps: EditorDeps): Promise<ToolAnswer> { + const channel = typeof args.channel === "string" ? args.channel.trim() : ""; + if (!channel || !SLUG_RE.test(channel)) { + return { text: "x_search_leads: channel is required (the X search channel's slug)", isError: true }; + } + const q = new URLSearchParams({ leads: "1" }); + if (args.limit !== undefined) { + const n = Number(args.limit); + if (!Number.isInteger(n) || n < 1 || n > X_SEARCH_LEADS_MAX) { + return { text: `x_search_leads: limit is a whole number, 1–${X_SEARCH_LEADS_MAX}`, isError: true }; + } + q.set("limit", String(n)); + } + const a = await editorGet(deps, `/api/ops/channel/${encodeURIComponent(channel)}?${q.toString()}`); + if (a.kind !== "ok") return { text: describeEditorFailure("x_search_leads", a), isError: true }; + return { text: renderXSearchLeads(channel, a.body as LeadsBody) }; +} + +export const X_SEARCH_TOOLS = [ + { + name: "x_search_leads", + description: + "An X SEARCH channel's leads: the accounts whose posts matched its saved X query, most " + + "matches first, each with its first and last matching day, a sample post and whether an " + + "X channel archives it already. For finding which accounts keep saying something. Read " + + "only — archiving an account (always on no site) or hiding it is the operator's, on the " + + "channel page or `pnpm ops x-search-lead`. Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.", + inputSchema: { + type: "object", + properties: { + channel: { type: "string", description: "The X search channel's slug (the editor's)." }, + limit: { type: "number", description: `Leads to list (default 100, at most ${X_SEARCH_LEADS_MAX}).` }, + }, + required: ["channel"], + additionalProperties: false, + }, + }, +] as const; diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -10,7 +10,7 @@ // // pnpm ops <action> [--json '<body>' | --file <path>] [--wait] // [--wait-timeout <seconds>] [--quiet] -// pnpm ops get channel <slug> [--counts] +// pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]] // pnpm ops get channels // pnpm ops get tags [<tagId>] // pnpm ops get job <id> [--tail [<lines>]] @@ -121,6 +121,10 @@ // pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait // pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}' // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait +// pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}' +// pnpm ops get channel demo-search --leads --limit 20 +// pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}' +// pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait // pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait @@ -186,8 +190,11 @@ const MAX_PROBE_FAILURES = 10; const GETTERS = { // --counts adds the LIVE on-disk counts, which walk every video directory — // opt-in for the same reason the route makes it opt-in. - channel: (slug, { counts }) => - `/api/ops/channel/${encodeURIComponent(slug)}${counts ? "?counts=1" : ""}`, + // --leads (an X search channel, release 38) adds its leads, --limit how many. + channel: (slug, { counts, leads, jobs }) => { + const q = [counts ? "counts=1" : "", leads ? "leads=1" : "", leads && jobs?.limit ? `limit=${jobs.limit}` : ""].filter(Boolean); + return `/api/ops/channel/${encodeURIComponent(slug)}${q.length ? `?${q.join("&")}` : ""}`; + }, // Every channel, one line each: slug, name, kind, platform and the sites // that carry it ([] = private to this editor). channels: () => "/api/ops/channels", @@ -282,7 +289,7 @@ const GET_ARG_OPTIONAL = new Set([ // The flags each noun takes beyond the shared ones; any other is refused. const GET_FLAGS = { transcript: ["slug"], - channel: ["counts"], + channel: ["counts", "leads", "limit"], job: ["tail"], jobs: ["active", "failed", "kind", "slug", "limit"], }; @@ -452,6 +459,10 @@ const ACTIONS = [ // re-derived from its stored captures ({slug, dryRun?}), offline, as a job. "import-page", "reextract-pages", + // X SEARCH (release 38): an X search channel's lead, acted on — archive the + // account as its own X channel on no site, or never archive it (hidden), + // or restore it ({slug, handle, action, name?, fetch?, dryRun?}). + "x-search-lead", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -567,6 +578,7 @@ export function parseArgs(argv) { let wait = false; let quiet = false; let counts = false; + let leads = false; let tail = 0; const jobs = {}; // The noun-specific flags seen, checked against GET_FLAGS once the noun is @@ -603,6 +615,9 @@ export function parseArgs(argv) { } else if (arg === "--counts") { counts = true; used.add("counts"); + } else if (arg === "--leads") { + leads = true; + used.add("leads"); } else if (arg === "--active" || arg === "--failed") { jobs[arg.slice(2)] = true; used.add(arg.slice(2)); @@ -708,9 +723,12 @@ export function parseArgs(argv) { error: `get ${noun} does not take ${stray.map((f) => `--${f}`).join(", ")}`, }; } + if (noun === "channel" && used.has("limit") && !leads) { + return { error: "get channel: --limit goes with --leads" }; + } return { method: "GET", - path: GETTERS[noun](positional[2], { counts, tail, jobs }), + path: GETTERS[noun](positional[2], { counts, leads, tail, jobs }), wait: false, quiet, waitTimeout, @@ -852,7 +870,7 @@ export function usage() { return [ "Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]", " [--wait-timeout <seconds>] [--quiet]", - " pnpm ops get channel <slug> [--counts]", + " pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]]", " pnpm ops get channels", " pnpm ops get tags [<tagId>]", " pnpm ops get publish", @@ -1162,6 +1180,22 @@ export function usage() { ' derived from the name), "sites"? (absent = on no site). "fetchPlaylist",', ' "fetchPostsNow" and "prioritizeDownload" are the form\'s checkboxes, OFF', ' unless true; a job they start comes back as jobId(s), so --wait follows it.', + ' An X search page URL (x.com/search?q=…), or "platform": "x-search" with', + ' "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?,', + ' "xSearchLang"?), makes an X SEARCH channel: the matching posts from any', + " account, walked by fetch-posts in search windows; never on a site (sites", + " refused).", + "", + 'x-search-lead acts on one lead of an X search channel (the accounts its', + ' posts came from — `get channel <slug> --leads [--limit <n>]` lists them,', + ' most matches first): {"slug", "handle", "action": "archive" | "never" |', + ' "restore"}. "archive" creates <handle>-x, an X channel on NO site, by the', + ' New channel form\'s path and starts its first post fetch ("fetch": false', + ' skips it; "name"? names it; "dryRun" answers the fields and creates', + ' nothing) -> {slug, jobIds}. Refused: not an X search channel, an account', + " an X channel archives already, a slug taken. \"never\" hides the handle", + " (the channel's xSearch.exclude), \"restore\" un-hides it -> {exclude,", + " changed}. No model, no request but the new channel's fetch.", "", 'rename-channel moves a channel to a new slug, as Danger → Rename does:', ' {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit,',