Archilyzer · Source

archilyzer

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

commit 15cebfb7840ed159c8be484787534eb76ddeb14c
parent 453dfa4c7e8cb9f013406172eb8688ff1b524720
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 00:33:48 -0500

editor: Sync new and Resume backfill, two buttons and two named ops actions

The channel page of an X or Bluesky channel now shows "Sync new" (the old
Fetch posts there, aria "sync new posts"). When the full-history walk is
part-way it also shows "Resume backfill", with the line "backfill unfinished
— N archived; Resume backfill continues it", and a line for a sync that
stopped part-way. A forum thread and an X search channel keep Fetch posts.
Re-fetch full history and Fetch older posts are unchanged.

fetch-posts takes "backfill": true. The new ops action resume-backfill
{slug, limit?} is the same walk under its own name. A plain fetch-posts, the
scheduler and Sync stay sync new. A refusal comes before any job: no backfill
part-way, backfill with full or older, a forum thread, an X search channel.
A resume-backfill job replays and resumes as one. The MCP enqueue tool takes
backfill.

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

Diffstat:
Mcommon/lib/timelineWalk.test.ts | 12++++++++++++
Mcommon/lib/timelineWalk.ts | 22+++++++++++++---------
Meditor/app/api/ops/_door.test.ts | 1+
Meditor/app/api/ops/fetch-posts/route.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/fetch-posts/route.ts | 10++++++++--
Aeditor/app/api/ops/resume-backfill/route.ts | 37+++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Meditor/app/channels/[slug]/page.tsx | 17+++++++++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 27+++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 2++
Meditor/e2e/social-channel.spec.ts | 71++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mmcp/src/archivalTools.test.ts | 8++++++++
Mmcp/src/archivalTools.ts | 14++++++++++----
Mscripts/archilyzer-ops.mjs | 31++++++++++++++++++++++++++-----
14 files changed, 339 insertions(+), 32 deletions(-)

diff --git a/common/lib/timelineWalk.test.ts b/common/lib/timelineWalk.test.ts @@ -86,6 +86,18 @@ test("SYNC NEW with nothing archived is the first full-history walk: an unfinish assert.deepEqual(planTimelineRun("sync", after, WATERMARK), { mode: "sync", since: WATERMARK, saveTo: "sync" }); }); +test("SYNC NEW on an empty archive never moves or clears a backfill that is part-way", () => { + const walks = timelineWalks({ cursor: "1/LEGACY" }); + const plan = planTimelineRun("sync", walks, null) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "sync", saveTo: "sync" }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true }, NOW), { backfill: { cursor: "1/LEGACY" } }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: false, cursor: "1/S" }, NOW), { + backfill: { cursor: "1/LEGACY" }, + sync: { cursor: "1/S", savedAt: NOW }, + }); + assert.deepEqual(withResumePoint(plan, walks, "1/CP", NOW).backfill, { cursor: "1/LEGACY" }); +}); + test("RESUME BACKFILL continues the saved point with no watermark, and never touches the sync's", () => { const walks = timelineWalks({ backfill: { cursor: "1/BF" }, diff --git a/common/lib/timelineWalk.ts b/common/lib/timelineWalk.ts @@ -145,15 +145,18 @@ export function planTimelineRun( } // SYNC NEW: an unfinished sync continues down to the watermark it began // with; else from the top down to the newest archived post. Nothing - // archived: the walk is the channel's first full-history walk, and its - // resume point is the backfill's. - if (walks.sync) { - const since = walks.sync.since ?? watermark ?? undefined; - return since - ? { mode, cursor: walks.sync.cursor, since, saveTo: "sync" } - : { mode, cursor: walks.sync.cursor, saveTo: "backfill" }; - } - return watermark ? { mode, since: watermark, saveTo: "sync" } : { mode, saveTo: "backfill" }; + // archived and no backfill part-way: the walk is the channel's first + // full-history walk, and its resume point is the backfill's. With a backfill + // part-way a sync keeps to its own slot whatever the archive holds, so it + // can never move or clear the backfill's place. + const since = walks.sync?.since ?? watermark ?? undefined; + const cursor = walks.sync?.cursor; + return { + mode, + ...(cursor ? { cursor } : {}), + ...(since ? { since } : {}), + saveTo: since || walks.backfill ? "sync" : "backfill", + }; } // The positions after a run, from the fetcher's outcome. A run that finished @@ -211,6 +214,7 @@ export function timelineRunLine(plan: TimelineRunPlan): string { if (plan.mode === "backfill") return "resume backfill, from its saved resume point"; if (plan.cursor && plan.since) return `sync new, continuing the unfinished sync down to ${plan.since}`; if (plan.since) return `sync new, since ${plan.since}`; + if (plan.saveTo === "sync") return "sync new — nothing archived yet, from the top"; return "sync new — nothing archived yet, so this is the first full-history walk"; } diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts @@ -106,6 +106,7 @@ test("a traversing slug is refused at the door, on every route that takes one", ["relocate", { slugs: ["../../escape"], root: "/tmp/ops-api-never" }], ["relocate-back", { slugs: ["../../escape"] }], ["fetch-posts", { slug: "../../escape", older: true }], + ["resume-backfill", { slug: "../../escape" }], ["capture-posts", { slug: "../../escape", ids: ["1"] }], ["persist-videos", { items: [{ slug: "../../escape", id: "abc123" }] }], ["fetch-chat", { slug: "../../escape", id: "abc123" }], diff --git a/editor/app/api/ops/fetch-posts/route.test.ts b/editor/app/api/ops/fetch-posts/route.test.ts @@ -137,3 +137,49 @@ test("fetch-posts refuses a channel that is not social, full with older, and an assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); }); + +test("resume backfill — fetch-posts \"backfill\": true or the resume-backfill action — is refused before any job when none is part-way", async () => { + const { NO_BACKFILL_TO_RESUME, BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL, FORUM_BACKFILL_REFUSAL } = + await import("yt-dlp-transcript-common/controller/fetchPosts"); + const { POST: RESUME } = await import("../resume-backfill/route"); + // demo-x's state holds no resume point of either walk. + const none = await post({ slug: SLUG, backfill: true }); + assert.equal(none.status, 400); + assert.equal(none.error, NO_BACKFILL_TO_RESUME); + const res = await RESUME( + new Request("http://localhost/api/ops/resume-backfill", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify({ slug: SLUG }), + }), + ); + assert.equal(res.status, 400); + assert.equal(((await res.json()) as { error?: string }).error, NO_BACKFILL_TO_RESUME); + // It takes no walk options of its own. + const stray = await RESUME( + new Request("http://localhost/api/ops/resume-backfill", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify({ slug: SLUG, full: true }), + }), + ); + assert.equal(stray.status, 400); + + assert.equal((await post({ slug: SLUG, backfill: true, full: true })).error, BACKFILL_AND_FULL_REFUSAL); + assert.equal((await post({ slug: SLUG, backfill: true, older: true })).error, BACKFILL_AND_OLDER_REFUSAL); + const bad = await post({ slug: SLUG, backfill: "yes" }); + assert.equal(bad.status, 400); + assert.match(bad.error, /"backfill" must be a boolean/); + + // A forum thread has no separate backfill. + await channel("demo-forum", { + handling: "transcribe", + sourceKind: "social", + platform: "xenforo", + name: "Demo thread", + url: "https://forum.example.invalid/threads/demo.1/", + }); + assert.equal((await post({ slug: "demo-forum", backfill: true })).error, FORUM_BACKFILL_REFUSAL); + + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); diff --git a/editor/app/api/ops/fetch-posts/route.ts b/editor/app/api/ops/fetch-posts/route.ts @@ -26,7 +26,12 @@ function optRetryOnBlock(body: OpsBody): RetryOnBlock | "settings" | undefined { export const dynamic = "force-dynamic"; -// POST { slug, full?, older?, floor?, from?, force?, limit?, pages?, retryOnBlock?, queueKey? } -> { ok: true, jobId } +// POST { slug, backfill?, full?, older?, floor?, from?, force?, limit?, pages?, retryOnBlock?, queueKey? } -> { ok: true, jobId } +// +// Plain, it is SYNC NEW (lib/timelineWalk.ts): from the top of the timeline +// down to the newest archived post, never reading or clearing an unfinished +// backfill's resume point. `backfill: true` is RESUME BACKFILL — the same as +// the ops action resume-backfill — refused when no backfill is part-way. // // `pages` caps how many pages a run reads, for a channel read page by page (a // forum thread: its latest N pages). `retryOnBlock` ({minutes, max}, or true @@ -47,7 +52,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "full", "older", "floor", "from", "force", "limit", "pages", "retryOnBlock", "queueKey"], + ["slug", "backfill", "full", "older", "floor", "from", "force", "limit", "pages", "retryOnBlock", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -62,6 +67,7 @@ export async function POST(request: Request) { optPositiveInt(body, "pages"), optString(body, "from"), optRetryOnBlock(body), + optBool(body, "backfill"), ), ); }, diff --git a/editor/app/api/ops/resume-backfill/route.ts b/editor/app/api/ops/resume-backfill/route.ts @@ -0,0 +1,37 @@ +import { fetchPostsAction } from "../../../channels/[slug]/socialActions"; +import { jobResponse, ops, optPositiveInt, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, limit?, queueKey? } -> { ok: true, jobId } +// +// RESUME BACKFILL (lib/timelineWalk.ts): a social channel's unfinished +// full-history timeline walk, continued from its saved resume point +// (posts-state.json's `backfill`) with no watermark — the channel page's +// Resume backfill button, and fetch-posts `"backfill": true` by its own name. +// Its counterpart, SYNC NEW, is a plain fetch-posts: from the top down to the +// newest archived post, never touching this point. +// +// Refused before any job: no backfill part-way, a forum thread (its catch-up +// always comes first, then its history), an X search channel (one walk), a +// channel that is not a social one. On the platform's queue, as fetch-posts. +export async function POST(request: Request) { + return ops(request, ["slug", "limit", "queueKey"], async (body) => { + const slug = reqSlug(body, "slug"); + return jobResponse( + await fetchPostsAction( + slug, + optString(body, "queueKey"), + undefined, + optPositiveInt(body, "limit"), + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + true, + ), + ); + }); +} diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -54,6 +54,11 @@ export type SocialChannelState = { forumSession?: ForumSessionStatus; // An X search channel (release 38): its query and where its walk stands. search?: { query: string; walk: string }; + // A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new, and + // Resume backfill when the full-history walk is part-way (`backfill`, its + // status line); `sync`, the line for a sync that stopped part-way. Absent on + // a forum thread and an X search channel, which keep Fetch posts. + timeline?: { backfill: string | null; sync: string | null }; // A forum thread's two walks (lib/forumWalk.ts): the status line, the // thread's last page as last seen, the mean seconds a page takes at the // channel's pace, and the Fetch posts button's retry after a block. @@ -135,7 +140,8 @@ export function SocialChannelPanel({ const [fetchNote, setFetchNote] = useState<string | null>(null); const [fetchErr, setFetchErr] = useState<string | null>(null); - const run = (full: boolean, older = false) => + const timeline = state.timeline; + const run = (full: boolean, older = false, backfill = false) => startTransition(async () => { setFetchNote(null); setFetchErr(null); @@ -153,13 +159,21 @@ export function SocialChannelPanel({ undefined, // A forum thread's Fetch posts waits out a block as settings say. forum && !full ? "settings" : undefined, + backfill || undefined, ); // The job streams to the jobs page; nothing to consume here, but the // stream must be released or its buffered chunks leak. if (res.ok) { void res.stream.cancel(); if (forum) setFetchNote(full ? "Full re-walk queued — its log is on the jobs page." : "Fetch queued — its log is on the jobs page."); - } else if (forum) { + else if (timeline && !full && !older) { + setFetchNote( + backfill + ? "Resume backfill queued — its log is on the jobs page." + : "Sync new queued — its log is on the jobs page.", + ); + } + } else if (forum || timeline) { setFetchErr(res.error); } }); @@ -296,15 +310,42 @@ export function SocialChannelPanel({ <span>pages</span> </label> )} - <button - type="button" - onClick={() => run(false)} - disabled={pending} - aria-label="fetch posts" - className="rounded-md bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" - > - {pending ? "Fetching…" : "Fetch posts"} - </button> + {timeline ? ( + <> + <button + type="button" + onClick={() => run(false)} + disabled={pending} + aria-label="sync new posts" + title="Fetch the posts newer than the newest archived one: from the top of the timeline down to it. It never resumes an unfinished backfill, and never moves its place." + className="rounded-md bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" + > + {pending ? "Fetching…" : "Sync new"} + </button> + {timeline.backfill && ( + <button + type="button" + onClick={() => run(false, false, true)} + disabled={pending} + aria-label="resume backfill" + title="Continue the account's unfinished full-history walk from where it stopped, down through older posts. It does not look for new posts — Sync new does that." + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Resume backfill + </button> + )} + </> + ) : ( + <button + type="button" + onClick={() => run(false)} + disabled={pending} + aria-label="fetch posts" + className="rounded-md bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" + > + {pending ? "Fetching…" : "Fetch posts"} + </button> + )} <button type="button" onClick={checkDeleted} @@ -395,6 +436,16 @@ export function SocialChannelPanel({ {walk.status} </p> )} + {timeline?.backfill && ( + <p aria-label="timeline backfill" className="mt-3 text-xs text-warning"> + {timeline.backfill} + </p> + )} + {timeline?.sync && ( + <p aria-label="timeline sync" className="mt-2 text-xs text-muted-foreground"> + {timeline.sync} + </p> + )} {fetchNote && ( <p role="status" className="mt-2 text-xs text-success"> {fetchNote} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -13,6 +13,11 @@ import { import { isPostGone, type Post, type PostAvailabilityMap } from "yt-dlp-transcript-common/lib/posts"; import { resolveSocialFetcher } from "yt-dlp-transcript-common/social/fetchers"; import { describeOlderBackfill } from "yt-dlp-transcript-common/social/olderBackfill"; +import { + describeTimelineBackfill, + describeTimelineSync, + timelineWalks, +} from "yt-dlp-transcript-common/lib/timelineWalk"; import "yt-dlp-transcript-common/social/blueskyFetcher"; import "yt-dlp-transcript-common/social/xGalleryDlFetcher"; import "yt-dlp-transcript-common/social/xPlaywrightFetcher"; @@ -234,6 +239,10 @@ export default async function ChannelDetailPage({ // 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; + // A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new and, + // when the full-history walk is part-way, Resume backfill — never a forum + // thread's (its own two walks) or an X search's (one walk). + const timeline = !forumThread && !xSearch ? timelineWalks(fetchState) : null; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> @@ -276,6 +285,14 @@ export default async function ChannelDetailPage({ typeof fetcher?.checkAvailability === "function", canFetchOlder: typeof fetcher?.fetchOlder === "function", olderStatus: describeOlderBackfill(fetchState?.older), + ...(timeline + ? { + timeline: { + backfill: timeline.backfill ? describeTimelineBackfill(timeline, postCount) : null, + sync: describeTimelineSync(timeline), + }, + } + : {}), handle: config.socialHandle ?? slug, accountUrl: config.url, platform: config.platform, diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -26,11 +26,16 @@ import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetc import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; import { + BACKFILL_AND_FULL_REFUSAL, + BACKFILL_AND_OLDER_REFUSAL, emptyAccountOlderProblem, fetchPosts, + FORUM_BACKFILL_REFUSAL, FULL_AND_OLDER_REFUSAL, OLDER_FROM_REFUSAL, olderPostsProblem, + resumeBackfillProblem, RETRY_AND_OLDER_REFUSAL, + X_SEARCH_BACKFILL_REFUSAL, } from "yt-dlp-transcript-common/controller/fetchPosts"; import { retryOnBlockProblem, @@ -167,6 +172,14 @@ export async function checkPostAvailabilityAction( }); } +// With none of `full`, `older`, `backfill` it is SYNC NEW (lib/timelineWalk.ts): +// from the top of the timeline down to the newest archived post — what the +// scheduler, the Sync button and a plain ops fetch-posts run. It never reads or +// clears an unfinished backfill's resume point. `backfill` is RESUME +// BACKFILL: that point continued, with no watermark — refused here, before a +// job exists, when no backfill is part-way, with `full` or `older`, on a forum +// thread or an X search channel. +// // `older` walks the account's history backwards from the oldest archived post // (the fetcher's `fetchOlder` — X: search windows) instead of fetching new // posts; `floor` (YYYY-MM-DD) is the date that walk stops at. Both are refused @@ -189,8 +202,12 @@ export async function fetchPostsAction( // `{minutes, max}`, or "settings" for `settings.social.xenforo.retryOnBlock` // (a forum thread's Fetch posts button; nothing when it is unset). retryOnBlock?: RetryOnBlock | "settings", + // RESUME BACKFILL in place of sync new (FetchPostsOptions.backfill). + backfill?: boolean, ): Promise<StreamActionResult> { if (full && older) return { ok: false, error: FULL_AND_OLDER_REFUSAL }; + if (backfill && full) return { ok: false, error: BACKFILL_AND_FULL_REFUSAL }; + if (backfill && older) return { ok: false, error: BACKFILL_AND_OLDER_REFUSAL }; if (retryOnBlock && older) return { ok: false, error: RETRY_AND_OLDER_REFUSAL }; const retry = retryOnBlock === "settings" ? getSettings().social.xenforo?.retryOnBlock : retryOnBlock; @@ -223,6 +240,14 @@ export async function fetchPostsAction( 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 (backfill) { + if (isXSearchChannel(config)) return { ok: false, error: X_SEARCH_BACKFILL_REFUSAL }; + if (config.platform === "xenforo") return { ok: false, error: FORUM_BACKFILL_REFUSAL }; + const problem = resumeBackfillProblem( + await readPostFetchState(path.join(paths.channelsDir, slug)), + ); + if (problem) return { ok: false, error: problem }; + } if (older) { await registerBuiltinSocialFetchers(); const problem = olderPostsProblem( @@ -262,6 +287,7 @@ export async function fetchPostsAction( older, floor, force, + ...(backfill ? { backfill: true } : {}), ...(pages ? { pages } : {}), ...(from ? { from } : {}), ...(retry ? { retryOnBlock: retry } : {}), @@ -273,6 +299,7 @@ export async function fetchPostsAction( slug, settings: getSettings(), full, + ...(backfill ? { backfill: true } : {}), older, floor, from, diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -426,6 +426,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { p.retryOnBlock && typeof p.retryOnBlock === "object" ? (p.retryOnBlock as { minutes: number; max: number }) : undefined, + // A resume-backfill job replays as one; any other as sync new. + bool(p.backfill), ); }, // Lane spn-batch: the batch's state file holds the list and each URL's diff --git a/editor/e2e/social-channel.spec.ts b/editor/e2e/social-channel.spec.ts @@ -173,7 +173,8 @@ test("fetch-posts writes month-sharded JSONL + a posts-archive, and re-running i // the archive must dedupe all of them rather than doubling the corpus. await generateReport(page, "faketester"); await page.goto("/channels/faketester"); - await page.getByRole("button", { name: /fetch posts/i }).first().click(); + // An X timeline's Fetch posts is Sync new (lib/timelineWalk.ts). + await page.getByRole("button", { name: "sync new posts" }).click(); await expect .poll( @@ -265,6 +266,74 @@ test("a forum thread URL makes a forum-thread channel, and saved pages import in .toEqual(["xenforo 21", "xenforo 22", "xenforo 23"]); }); +// SYNC NEW AND RESUME BACKFILL are two buttons for two walks (operator, 6 Nov +// 2026): an unfinished backfill is said, not silently resumed — Sync new walks +// from the top down to the watermark and keeps the backfill's place; Resume +// backfill continues it. The state is a posts-state.json from before the split +// (one `cursor`), which reads as the backfill's. +test("an X channel: Sync new keeps an unfinished backfill's place; Resume backfill continues it and the button goes", async ({ + page, +}) => { + await resetData("empty"); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/faketester`); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + socialHandle: "faketester", + name: "Fake Tester", + url: X_URL, + }), + ); + const statePath = path.join(dir, "posts-state.json"); + await writeFile(statePath, JSON.stringify({ lastFetchedAt: "2026-11-05T00:00:00.000Z", lastFetchedCount: 0, cursor: "1/LEGACY-BACKFILL" })); + await generateReport(page, "faketester"); + await page.goto("/channels/faketester"); + + const panel = page.locator("[data-social-panel]"); + await expect(panel.getByLabel("timeline backfill")).toHaveText("backfill unfinished — 0 archived; Resume backfill continues it"); + await expect(panel.getByRole("button", { name: "resume backfill" })).toBeVisible(); + await expect(panel.getByRole("button", { name: "fetch posts" })).toHaveCount(0); + await expect(panel.getByRole("button", { name: "refetch full history" })).toBeVisible(); + await expect(panel.getByRole("button", { name: "fetch older posts" })).toBeVisible(); + + // SYNC NEW: the fake's three tweets land; the backfill's place is kept. + await panel.getByRole("button", { name: "sync new posts" }).click(); + await expect(panel.getByRole("status")).toHaveText("Sync new queued — its log is on the jobs page."); + const archive = `${testPaths().transcriptsDir}/channels/faketester/posts-archive`; + const archived = async () => + (await pathExists(archive)) ? (await readFile(resolvePath(archive), "utf8")).split("\n").filter(Boolean).length : 0; + await expect.poll(archived, { timeout: 30_000 }).toBe(3); + const config = `${testPaths().transcriptsDir}/channels/faketester/config.json`; + await expect + .poll(async () => (await readJson<{ lastSyncedAt?: string }>(config)).lastSyncedAt ?? null, { timeout: 30_000 }) + .not.toBeNull(); + const afterSync = JSON.parse(await readFile(statePath, "utf8")) as Record<string, unknown>; + expect(afterSync.backfill).toMatchObject({ cursor: "1/LEGACY-BACKFILL" }); + expect("cursor" in afterSync).toBe(false); + await page.reload(); + await expect(panel.getByLabel("timeline backfill")).toHaveText("backfill unfinished — 3 archived; Resume backfill continues it"); + + // RESUME BACKFILL: the fake walks to the end and exits cleanly — the walk + // is finished, its place cleared, and the button goes. + await panel.getByRole("button", { name: "resume backfill" }).click(); + await expect(panel.getByRole("status")).toHaveText("Resume backfill queued — its log is on the jobs page."); + await expect + .poll(async () => (JSON.parse(await readFile(statePath, "utf8")) as Record<string, unknown>).backfill ?? null, { + timeout: 30_000, + }) + .toBeNull(); + await page.reload(); + await expect(panel.getByRole("button", { name: "sync new posts" })).toBeVisible(); + await expect(panel.getByRole("button", { name: "resume backfill" })).toHaveCount(0); + await expect(panel.getByLabel("timeline backfill")).toHaveCount(0); + expect(await archived()).toBe(3); +}); + // A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17): the // Sync button on the /channels rack ran yt-dlp's listing against an X profile // and failed. It runs fetch-posts now (the fake gallery-dl here), and a diff --git a/mcp/src/archivalTools.test.ts b/mcp/src/archivalTools.test.ts @@ -29,7 +29,15 @@ test("enqueue: each kind posts to its own route with only the keys it takes", () route: "/api/ops/import-video", body: { slug: "demo", url: "https://example.invalid/v/1" }, }); + // Sync new is a plain fetch-posts; resume backfill is asked for by name. + assert.deepEqual(enqueueBody({ kind: "fetch-posts", channel: "demo", backfill: true }), { + ok: true, + kind: "fetch-posts", + route: "/api/ops/fetch-posts", + body: { slug: "demo", backfill: true }, + }); const refusals: [Record<string, unknown>, RegExp][] = [ + [{ kind: "sync", channel: "demo", backfill: true }, /sync does not take backfill/], [{ kind: "delete-channel", channel: "demo" }, /kind must be one of sync, download-missing/], [{ kind: "sync" }, /channel is required/], [{ kind: "sync", channel: "../x" }, /channel is required/], diff --git a/mcp/src/archivalTools.ts b/mcp/src/archivalTools.ts @@ -119,10 +119,10 @@ const KIND_ARGS: Record<EnqueueKind, readonly string[]> = { "download-missing": [], "retry-bucket": ["bucket", "ids"], "transcribe-bucket": ["ids"], - "fetch-posts": ["full", "older"], + "fetch-posts": ["full", "older", "backfill"], "import-video": ["url"], }; -const ALL_ARGS = ["full", "older", "bucket", "ids", "url"]; +const ALL_ARGS = ["full", "older", "backfill", "bucket", "ids", "url"]; export function enqueueBody( args: Record<string, unknown>, @@ -142,7 +142,7 @@ export function enqueueBody( }; } const body: Record<string, unknown> = { slug: channel }; - for (const k of ["full", "older"] as const) { + for (const k of ["full", "older", "backfill"] as const) { if (args[k] === undefined) continue; if (typeof args[k] !== "boolean") return { ok: false, error: `enqueue: ${k} must be true or false` }; if (args[k]) body[k] = true; @@ -479,7 +479,8 @@ export const ARCHIVAL_TOOLS = [ "the whole listing), download-missing (every listed video not held), retry-bucket " + "(one bucket of the channel's report, or ids within it — the way to download chosen " + "videos), transcribe-bucket (the downloaded, untranscribed videos, or ids among them), " + - "fetch-posts (a social channel's new posts; full / older walks), import-video (one " + + "fetch-posts (a social channel's new posts — sync new; backfill: true resumes its unfinished " + + "history walk instead; full / older walks), import-video (one " + "video by URL into the channel). The editor runs it on its own queues at each " + "platform's pace and answers a job id — follow it with get_job. Only when the " + "operator asks for it. Settings, storage and deletes are not reachable from here. " + @@ -491,6 +492,11 @@ export const ARCHIVAL_TOOLS = [ channel: { type: "string", description: "The channel slug (the editor's)." }, full: { type: "boolean", description: "sync: sweep the whole listing now; fetch-posts: re-walk the timeline." }, older: { type: "boolean", description: "fetch-posts: walk back below the oldest archived post." }, + backfill: { + type: "boolean", + description: + "fetch-posts: resume the timeline's unfinished full-history walk from its saved point (without it, fetch-posts syncs new posts only).", + }, bucket: { type: "string", description: "retry-bucket: the bucket name (e.g. noTranscript, partialDownloads)." }, ids: { type: "array", diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -40,6 +40,8 @@ // EXAMPLES // // pnpm ops sync --json '{"slug":"the-quartering"}' --wait +// pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait +// pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait @@ -435,9 +437,12 @@ const ACTIONS = [ // The TRANSCRIBE half of a channel's "downloaded, not transcribed" bucket // (retry-bucket is the download retry and skips audio already on disk). "transcribe-bucket", - // A social channel's post fetch: new posts, the full re-walk ("full"), or - // the walk back below the oldest archived post ("older"). + // A social channel's post fetch: SYNC NEW (plain), RESUME BACKFILL + // ("backfill": true), the full re-walk ("full"), or the walk back below the + // oldest archived post ("older"). "fetch-posts", + // RESUME BACKFILL by its own name: fetch-posts "backfill": true. + "resume-backfill", // A screenshot and the attached media of specific archived posts. "capture-posts", // Publishing as stages (release 18): {"verb": "index" | "build" | "deploy" | @@ -1519,7 +1524,11 @@ export function usage() { ' bucket on the transcription queue, as the channel page\'s Transcribe button', ' does: {"slug"}. "ids": [...] narrows it the same way as on retry-bucket.', "", - 'fetch-posts fetches a social channel\'s new posts: {"slug"}. "full": true', + 'fetch-posts fetches a social channel\'s new posts: {"slug"} is SYNC NEW —', + ' from the top of the timeline down to the newest archived post (a sync that', + ' stopped part-way continues down to the watermark it began with). It never', + ' reads or clears an unfinished backfill\'s resume point. "backfill": true', + ' is RESUME BACKFILL instead (the same as resume-backfill). "full": true', ' re-walks the whole timeline; "older": true walks back from the oldest', " archived post through search (X; needs a login), saving its place for", ' the next run, down to "floor": "YYYY-MM-DD" when given; "from":', @@ -1531,10 +1540,22 @@ export function usage() { ' "full": true is its full re-walk (every page, edits updated).', ' "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default', ' in settings) waits out a challenge or refusal page and runs again, max', - ' tries in all. "full" and "older" together are refused. An', + ' tries in all. "full", "older" and "backfill" are one at a time. An', ' older walk over an account that shows no posts (nothing archived, and', ' the last timeline fetch read none) is refused unless "force": true. A', - " drained fetch stops at its next resume point and the next run resumes.", + " drained fetch stops at its next resume point and the next run of the", + " same walk resumes there.", + "", + 'resume-backfill continues a social channel\'s unfinished full-history', + ' timeline walk (X, Bluesky) from its saved resume point, with no', + ' watermark: {"slug"} ("limit"? caps the posts this run reads). The walk', + " is left part-way by a first fetch, a full re-walk or a backfill that", + " stopped; the channel page then says \"backfill unfinished — N archived\"", + " and shows Resume backfill. Nothing resumes it but this (or fetch-posts", + ' "backfill": true): a plain fetch-posts, Sync and the scheduler sync new', + " posts and keep its place. Refused when none is part-way, on a forum", + " thread (every fetch catches up, then continues its history) and on an X", + " search channel.", "", 'capture-posts captures archived posts of a social channel (X, forum,', ' Bluesky): a screenshot of each through the connected X profile (a forum',