Archilyzer · Source

archilyzer

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

commit a90e3e9bab5b3d885627cb93d83d887e49d9cbfb
parent 480a6cd14989bcf33c209819bb220b3e8cb0f2ca
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 25 Oct 2026 22:51:20 -0400

Merge lane/ops-cli: the download filter's ^ and $ anchor to the title; archilyzer corpus grep (the live corpus, offline); pnpm ops get x-session (the X guard's own verdict)

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

# Conflicts:
#	editor/CHANGELOG.md

Diffstat:
MCHANNEL.md | 4++--
MCOMMANDS.md | 12++++++++++++
MOPERATING.md | 8++++++++
Mcommon/bin/archilyzer.ts | 16++++++++++++++++
Acommon/bin/corpus-grep.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/corpusGrep.test.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/corpusGrep.ts | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/keepVideosMatching.ts | 7++++---
Mcommon/controller/videoCues.ts | 20++++++++++++++++++--
Mcommon/jobs/networkGuard.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/jobs/pacingGuard.test.ts | 26++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 4++--
Mcommon/lib/downloadFilters.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/downloadFilters.ts | 37+++++++++++++++++++++++++++++++------
Meditor/CHANGELOG.md | 3+++
Meditor/app/api/ops/_read.test.ts | 20+++++++++++++++++++-
Aeditor/app/api/ops/x-session/route.ts | 27+++++++++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 4++--
Mscripts/archilyzer-ops.mjs | 18++++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 10++++++++++
20 files changed, 887 insertions(+), 42 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -57,8 +57,8 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Default | Description | |---|---|---| -| `include` | absent | Case-insensitive regex SOURCE (no delimiters, no flags) a video's `title + "\n" + description` must match to be downloaded. Trimmed; blank = no include rule. | -| `exclude` | absent | Case-insensitive regex source that rejects a matching video. Wins over `include`. Trimmed; blank = no exclude rule. | +| `include` | absent | Case-insensitive regex SOURCE (no delimiters, no flags) a video must match to be downloaded. It is tested against the title alone AND against `title + "\n" + description`, and either match counts — so `^` and `$` anchor to the title (`^EPISODE (12\|13)$` matches that exact title). Trimmed; blank = no include rule. | +| `exclude` | absent | Case-insensitive regex source that rejects a matching video, tested the same way as `include` (title alone, or title + description; `^`/`$` anchor to the title). Wins over `include`. Trimmed; blank = no exclude rule. | | `includeLivestreams` | absent | Opt every livestream VOD in, whatever it is called. A SECOND positive selector beside `include`, not a modifier of it — so `{ includeLivestreams: true }` alone rejects plain uploads and passes livestreams. Stored only when `true`. | | `rejectedLivestreams` | absent | What to do with a livestream the filter REJECTED: `"skip"` (default, and what every channel predating the field did) or `"chat-only"` — the video is not downloaded, its live chat is, and it joins the corpus as a chat track with no captions. Stored only when not `"skip"`, and only beside a real filter: with nothing to reject it names a decision that can never be taken. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -76,6 +76,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer verify transcripts` | `--channel <slug>` | list duplicate and missing transcripts *(passthrough)* | | `archilyzer migrate channel-priority` | `[--dry-run]` | the one-shot channel-priority migration (plans/channel-priority.md, S5) *(passthrough)* | | `archilyzer storage report` | `[<slug>…] [--json]` | each channel's media (tierable), text and clip bytes and where its media is — off the reports, no drive touched; totals per place (the corpus disk's is what a move would free) | +| `archilyzer corpus grep` | `--regex <re> [--channels a,b] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--window 30] [--limit N] [--case-sensitive] [--json]` | search the LIVE corpus's transcripts off disk, no index and no editor: each held video's cues (transcript.cues.json, else its best caption track, en-orig before en, rolling repeats collapsed), dated by metadata.info.json upload\_date; prints date, channel, id, start second, title and the window's text (case-insensitive unless --case-sensitive), then the videos in range with no transcript yet; a channel whose text is unreadable is skipped and named; default every channel that is not social; TRANSCRIPTS\_DIR picks the corpus; writes nothing | | `archilyzer storage migrate-tier` | `<slug>…\|--all [--order smallest] [--include-large] [--dry-run] [--reclaim]` | bring a channel off the retired whole-directory layout onto the media tier, its text home to the corpus disk (editor stopped; --all stops before the three big-text channels) *(passthrough)* | | `archilyzer brand media` | `[--out <dir>] [--video-kit]` | render the Archilyzer Media channel's assets *(passthrough)* | | `archilyzer mcp` | `[--local <dir>\|--remote <url>\|--hub <url>]` | start the MCP server on stdio (as `pnpm --filter yt-dlp-transcript-mcp exec tsx src/index.ts`) *(passthrough)* | @@ -205,6 +206,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get storage | sites | workers | auto-queue | scheduler pnpm ops get saved-alternates [<slug>] pnpm ops get services + pnpm ops get x-session [<slug>] pnpm ops get cleanup <slug> pnpm ops get remote-listing <slug> [--wait-timeout <seconds>] pnpm ops get transcript <videoId> [--slug <slug>] @@ -254,6 +256,16 @@ get services is the dashboard's cookie refresh alerts: each service (rumble, youtube, odysee, archive.today, a forum host) whose cookies look stale, or are OK again with the jobs the alert stopped; "pending" lists a first Rumble embed 403 waiting for a second video. +get x-session [<slug>] is the X login an X job would use and whether one + would start NOW, from the same check that refuses a stale-cookie X job: + source ("profile": the exported jar under transcripts/.x-session; + "browser": cookiesFromBrowser, whose age cannot be read), hasCookies, + looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes + (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up, + allowed, and reason (the refusal an X job would get). <slug> names a + channel whose own cookiesFromBrowser may decide the source. Nothing is + asked of X: a refresh is Refresh cookies / Connect X account on + /settings. Ask it before queueing fetch-posts or capture-posts on X. get cleanup <slug> is one channel's /cleanup row: what each sweep would reclaim (they overlap — never add them), what holds the rest, and the failed-transcriptions count. measured: false means unknown, not zero. diff --git a/OPERATING.md b/OPERATING.md @@ -280,6 +280,9 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait press Refresh cookies (or Connect X account) on /settings, then fetch again.` Refreshing is a click on /settings — it loads x.com — so the editor never refreshes on its own. With the browser login the age cannot be read; the job logs that and proceeds. + `pnpm ops get x-session` answers the same check before anything is queued: the login source, the jar's + age in minutes, the limit, `allowed`, and the refusal an X job would get (`reason`). An agent asks it + first and, when `allowed` is false, asks the operator for a refresh instead of queueing. - `capture-posts` saves a screenshot and the attached media of named posts (and a linked X Article). - A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page to the newest held post, then continues the history from where it stopped, down to page 1 — `"pages": N` caps @@ -658,4 +661,9 @@ pnpm archilyzer publish build example-site --out /srv/example-private notes: `notes` (with `UMTOOL_URL`). Settings, storage and deletes stay `pnpm ops`. - `generation_policy` and `generate` route a generation task by the policy ("Generate and iterate" above); `/gen` wraps them. +- The MCP reads a PUBLISHED archive. For the live corpus — a video downloaded an hour ago, a channel no site + carries — `pnpm archilyzer corpus grep --regex '<re>' --channels a,b --since YYYY-MM-DD` searches the + transcripts on disk (no index, no editor; `--json`, `--window`, `--until`, `--limit`), and ends with the + videos in range that have no transcript yet. From a worktree, set `TRANSCRIPTS_DIR` to the primary + checkout's `transcripts/`. - Tools and their arguments: [mcp/README.md](mcp/README.md). diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -902,6 +902,22 @@ export const COMMANDS: Command[] = [ json: flags.json === true, }), }, + { + path: ["corpus", "grep"], + usage: + "--regex <re> [--channels a,b] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--window 30] [--limit N] [--case-sensitive] [--json] search the LIVE corpus's transcripts off disk, no index and no editor: each held video's cues (transcript.cues.json, else its best caption track, en-orig before en, rolling repeats collapsed), dated by metadata.info.json upload_date; prints date, channel, id, start second, title and the window's text (case-insensitive unless --case-sensitive), then the videos in range with no transcript yet; a channel whose text is unreadable is skipped and named; default every channel that is not social; TRANSCRIPTS_DIR picks the corpus; writes nothing", + flags: { + regex: "string", + channels: "string", + since: "string", + until: "string", + window: "string", + limit: "string", + "case-sensitive": "boolean", + json: "boolean", + }, + run: async ({ flags }) => (await import("./corpus-grep")).main(flags), + }, script(["storage", "migrate-tier"], "migrate-media-tier.ts", "<slug>…|--all [--order smallest] [--include-large] [--dry-run] [--reclaim] bring a channel off the retired whole-directory layout onto the media tier, its text home to the corpus disk (editor stopped; --all stops before the three big-text channels)"), { diff --git a/common/bin/corpus-grep.ts b/common/bin/corpus-grep.ts @@ -0,0 +1,123 @@ +// `archilyzer corpus grep --regex <re> [--channels a,b] [--since YYYY-MM-DD] +// [--until YYYY-MM-DD] [--window 30] [--limit N] [--case-sensitive] [--json]` +// +// A regex over the LIVE corpus's transcripts (controller/corpusGrep.ts): every +// held video of the named channels (default: every channel that is not social), +// dated by metadata.info.json's upload_date, its cues read as the ops +// transcript route reads them. Prints each hit's date, channel, id, start +// second, title and window text, then how many videos in range have no +// transcript yet, and lists them. Needs no editor and no index; writes nothing. +// The corpus is TRANSCRIPTS_DIR, else the checkout's transcripts/ (from a +// worktree, point TRANSCRIPTS_DIR at the primary checkout's). + +import { getPaths } from "../lib/paths"; +import { corpusGrep, parseGrepDate, type CorpusGrepResult } from "../controller/corpusGrep"; +import type { FlagValue } from "./_parseFlags"; + +function str(v: FlagValue | undefined): string | undefined { + return typeof v === "string" ? v : undefined; +} + +function clock(s: number): string { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + const mm = String(m).padStart(2, "0"); + const ss = String(sec).padStart(2, "0"); + return h ? `${h}:${mm}:${ss}` : `${m}:${ss}`; +} + +export function formatCorpusGrep(r: CorpusGrepResult): string { + const lines: string[] = []; + for (const h of r.hits) { + lines.push(`${h.date || "undated"} ${h.slug} ${h.id} ${h.start}s (${clock(h.start)}) ${h.title}`); + lines.push(` ${h.text}`); + } + const range = + r.since || r.until ? ` uploaded ${r.since ? `from ${r.since}` : ""}${r.since && r.until ? " " : ""}${r.until ? `to ${r.until}` : ""}` : ""; + lines.push(""); + lines.push( + `${r.totalHits} hit${r.totalHits === 1 ? "" : "s"}${r.hits.length < r.totalHits ? ` (${r.hits.length} shown)` : ""} ` + + `for /${r.pattern}/ in ${r.videosSearched} transcribed video${r.videosSearched === 1 ? "" : "s"}${range} ` + + `across ${r.channels.length} channel${r.channels.length === 1 ? "" : "s"} (${r.windowSeconds} s windows).`, + ); + if (r.since || r.until) { + if (r.undated) lines.push(`${r.undated} video${r.undated === 1 ? "" : "s"} with no metadata.info.json (no date) left out.`); + } + lines.push(`${r.noTranscript.length} video${r.noTranscript.length === 1 ? "" : "s"} in range with no transcript yet${r.noTranscript.length ? ":" : "."}`); + for (const p of r.noTranscript) { + const dur = p.duration !== undefined ? ` ${clock(Math.round(p.duration))}` : ""; + lines.push(` ${p.date || "undated"} ${p.slug} ${p.id}${dur} ${p.title}`); + } + for (const s of r.skippedChannels) lines.push(`skipped ${s.slug}: ${s.reason}`); + for (const e of r.errors) lines.push(`unreadable ${e.slug}/${e.id}: ${e.error}`); + return lines.join("\n"); +} + +export async function main(flags: Record<string, FlagValue>): Promise<number> { + const source = str(flags.regex); + if (!source) { + console.error("corpus grep: --regex <pattern> is required"); + return 2; + } + let pattern: RegExp; + try { + pattern = new RegExp(source, flags["case-sensitive"] === true ? "" : "i"); + } catch (err) { + console.error(`corpus grep: --regex does not parse: ${(err as Error).message}`); + return 2; + } + const dates: Record<"since" | "until", string | undefined> = { since: undefined, until: undefined }; + for (const key of ["since", "until"] as const) { + const raw = flags[key]; + if (raw === undefined) continue; + const day = typeof raw === "string" ? parseGrepDate(raw) : null; + if (!day) { + console.error(`corpus grep: --${key} is a date, YYYY-MM-DD`); + return 2; + } + dates[key] = day; + } + const num = (key: string, min: number): number | undefined | null => { + const raw = flags[key]; + if (raw === undefined) return undefined; + const n = typeof raw === "string" ? Number(raw) : NaN; + return Number.isInteger(n) && n >= min ? n : null; + }; + const windowSeconds = num("window", 1); + if (windowSeconds === null) { + console.error("corpus grep: --window is a whole number of seconds, 1 or more"); + return 2; + } + const limit = num("limit", 0); + if (limit === null) { + console.error("corpus grep: --limit is a whole number"); + return 2; + } + const channelsRaw = flags.channels; + if (channelsRaw === true) { + console.error("corpus grep: --channels takes a comma-separated list of slugs"); + return 2; + } + const channels = channelsRaw + ?.split(",") + .map((s) => s.trim()) + .filter(Boolean); + let result: CorpusGrepResult; + try { + result = await corpusGrep({ + paths: getPaths(), + pattern, + ...(channels?.length ? { channels } : {}), + ...(dates.since ? { since: dates.since } : {}), + ...(dates.until ? { until: dates.until } : {}), + ...(windowSeconds !== undefined ? { windowSeconds } : {}), + ...(limit !== undefined ? { limit } : {}), + }); + } catch (err) { + console.error(`corpus grep: ${(err as Error).message}`); + return 1; + } + console.log(flags.json === true ? JSON.stringify(result, null, 2) : formatCorpusGrep(result)); + return 0; +} diff --git a/common/controller/corpusGrep.test.ts b/common/controller/corpusGrep.test.ts @@ -0,0 +1,123 @@ +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/corpusGrep.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { corpusGrep, grepCues, parseGrepDate } from "./corpusGrep"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "corpus-grep-")); +const paths = { transcriptsDir: ROOT, channelsDir: path.join(ROOT, "channels") } as Paths; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const vtt = (cues: [number, number, string][]) => + "WEBVTT\n\n" + + cues + .map(([a, b, t]) => { + const ts = (s: number) => `00:${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`; + return `${ts(a)} --> ${ts(b)}\n${t}\n`; + }) + .join("\n"); + +async function channel(slug: string, config: Record<string, unknown> = {}) { + const dir = path.join(paths.channelsDir, slug); + await mkdir(path.join(dir, "data"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "youtube", name: slug, ...config })); +} + +async function video( + slug: string, + id: string, + opts: { date?: string; title: string; files?: Record<string, string>; old?: boolean }, +) { + const dir = path.join(paths.channelsDir, slug, "data", id); + await mkdir(dir, { recursive: true }); + if (opts.date) { + const meta = path.join(dir, "metadata.info.json"); + await writeFile(meta, JSON.stringify({ id, title: opts.title, upload_date: opts.date, duration: 600, webpage_url: `https://example.com/${id}` })); + if (opts.old) { + const t = new Date("2020-01-01T00:00:00Z"); + await utimes(meta, t, t); + } + } + for (const [name, body] of Object.entries(opts.files ?? {})) await writeFile(path.join(dir, name), body); +} + +await channel("show"); +// en-orig is the speaker's words; en a rewrite. The rule reads en-orig. +await video("show", "a1", { + date: "20261022", + title: "Episode one", + files: { + "transcript.en-orig.vtt": vtt([ + [0, 5, "hello and welcome"], + [10, 15, "my dog Huck went to the vet"], + [40, 45, "nothing here"], + [70, 75, "Huck is doing better"], + ]), + "transcript.en.vtt": vtt([[0, 5, "a rewritten track that says Huck"]]), + }, +}); +await video("show", "a2", { date: "20261023", title: "No transcript yet" }); +await video("show", "a3", { + date: "20251001", + title: "Old one", + old: true, + files: { "transcript.en.vtt": vtt([[0, 5, "Huck in the old days"]]) }, +}); +await channel("posts", { sourceKind: "social", platform: "twitter" }); +await channel("gone", { dataDir: "/nonexistent/archilyzer-corpus-grep" }); + +test("parseGrepDate takes both spellings and refuses a day that does not exist", () => { + assert.equal(parseGrepDate("2026-10-21"), "20261021"); + assert.equal(parseGrepDate("20261021"), "20261021"); + assert.equal(parseGrepDate("2026-02-30"), null); + assert.equal(parseGrepDate("yesterday"), null); +}); + +test("grepCues: one hit per moment, at the cue the match begins in", () => { + const cues = [ + { start: 0, end: 5, text: "a" }, + { start: 12, end: 15, text: "the word\nhere" }, + { start: 20, end: 25, text: "b" }, + { start: 50, end: 55, text: "word again" }, + ]; + const hits = grepCues(cues, /word/i, 30); + assert.deepEqual( + hits.map((h) => h.start), + [12, 50], + ); + assert.equal(hits[0].text, "a the word here b"); +}); + +test("corpus grep: date floor, caption-track rule, pending videos, guards", async () => { + const r = await corpusGrep({ paths, pattern: /\bhuck\b/i, since: "20261021" }); + assert.deepEqual(r.channels, ["show"]); + // The legacy channel is skipped and named; the social one is left out. + assert.deepEqual(r.skippedChannels.map((s) => s.slug), ["gone"]); + assert.deepEqual( + r.hits.map((h) => [h.date, h.slug, h.id, h.start, h.title]), + [ + ["2026-10-22", "show", "a1", 10, "Episode one"], + ["2026-10-22", "show", "a1", 70, "Episode one"], + ], + ); + assert.equal(r.hits[0].url, "https://example.com/a1"); + assert.equal(r.videosInRange, 2); + assert.equal(r.videosSearched, 1); + assert.deepEqual(r.noTranscript.map((p) => [p.id, p.title, p.duration]), [["a2", "No transcript yet", 600]]); +}); + +test("corpus grep: no date bound searches the old video too; --until bounds; limit counts all", async () => { + const all = await corpusGrep({ paths, pattern: /huck/i, channels: ["show"], limit: 1 }); + assert.equal(all.totalHits, 3); + assert.equal(all.hits.length, 1); + assert.equal(all.hits[0].id, "a3"); + const until = await corpusGrep({ paths, pattern: /huck/i, channels: ["show"], until: "20251231" }); + assert.deepEqual(until.hits.map((h) => h.id), ["a3"]); + await assert.rejects(corpusGrep({ paths, pattern: /x/, channels: ["nope"] }), /Channel "nope" not found/); + const named = await corpusGrep({ paths, pattern: /x/, channels: ["posts"] }); + assert.match(named.skippedChannels[0].reason, /social/); +}); diff --git a/common/controller/corpusGrep.ts b/common/controller/corpusGrep.ts @@ -0,0 +1,303 @@ +// CORPUS GREP — a regex over the LIVE corpus's transcripts, off disk, with no +// index and no editor (`archilyzer corpus grep`). +// +// The published shards and the MCP (TRANSCRIPT_LOCAL_DIR is a composed public +// dir) only know what the last publish built. A video downloaded an hour ago, +// a private channel, or a channel no site carries is invisible to them. This +// reads `transcripts/channels/<slug>/data/<id>/` itself: each video's cues the +// way the ops transcript route reads them (readCuesInVideoDir — a fresh +// transcript.cues.json, else what normalize would write: the caption-track +// rule, en-orig before en, YouTube's rolling-caption repeats collapsed by +// parseVtt), dated by metadata.info.json's upload_date. +// +// A WINDOW is `windowSeconds` (30) of cues starting at a cue, stepped by half a +// window; a window is a hit when the pattern matches its text, and the next hit +// in the same video starts after that window ends, so one moment is one hit. +// Each hit names the start second of the cue the match begins in. +// +// Read-only. A channel whose text is not readable (its drive is not answering, +// a legacy layout, a move in flight — assertChannelTextReadable) is skipped +// with its reason, never read as "no videos". A social channel holds posts, +// not transcripts, and is left out. +// +// Reference: an agent's hand-written ~/reports/quartering-huck/search/since.py +// (2026-10-25), which this replaces. + +import path from "node:path"; +import { readFile, stat } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import type { Cue } from "../lib/vtt"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { isSocialChannel } from "../lib/channelConfig"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import { mapConcurrent } from "../lib/concurrency"; +import { listChannelConfigs, readChannelConfig } from "./channels"; +import { heldVideoIds, readCuesInVideoDir } from "./videoCues"; + +export type CorpusGrepHit = { + // YYYY-MM-DD, or "" for an undated video (searched only with no date bound). + date: string; + slug: string; + id: string; + // The start second of the cue the match begins in. + start: number; + title: string; + // The whole window's text. + text: string; + url?: string; +}; + +export type CorpusGrepPending = { + date: string; + slug: string; + id: string; + title: string; + duration?: number; +}; + +export type CorpusGrepResult = { + pattern: string; + since: string | null; + until: string | null; + windowSeconds: number; + channels: string[]; + skippedChannels: { slug: string; reason: string }[]; + // Videos in range (by upload date) and how many of them had a transcript. + videosInRange: number; + videosSearched: number; + // In range with no transcript yet: still to download or transcribe. + noTranscript: CorpusGrepPending[]; + // No metadata.info.json (so no date): left out when a date bound is set. + undated: number; + // Every hit, before `limit`. + totalHits: number; + hits: CorpusGrepHit[]; + // Videos whose transcript could not be read, with the error. + errors: { slug: string; id: string; error: string }[]; +}; + +export type CorpusGrepOptions = { + paths: Paths; + pattern: RegExp; + // Absent: every channel that is not social. + channels?: readonly string[]; + // YYYYMMDD, inclusive. + since?: string; + until?: string; + windowSeconds?: number; + // Hits returned (all are counted in totalHits). Absent: all. + limit?: number; + onNote?: (line: string) => void; +}; + +const DAY_MS = 24 * 60 * 60 * 1000; + +// "2026-10-21" or "20261021" -> "20261021"; anything else null. +export function parseGrepDate(raw: string): string | null { + const m = /^(\d{4})-?(\d{2})-?(\d{2})$/.exec(raw.trim()); + if (!m) return null; + const [, y, mo, d] = m; + const t = Date.UTC(Number(y), Number(mo) - 1, Number(d)); + const back = new Date(t); + if (back.getUTCMonth() !== Number(mo) - 1 || back.getUTCDate() !== Number(d)) return null; + return `${y}${mo}${d}`; +} + +function dashed(day: string): string { + return day.length === 8 ? `${day.slice(0, 4)}-${day.slice(4, 6)}-${day.slice(6)}` : day; +} + +// The windows of one video's cues that the pattern matches (see the header). +export function grepCues( + cues: readonly Cue[], + pattern: RegExp, + windowSeconds = 30, +): { start: number; text: string }[] { + const re = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")); + const half = windowSeconds / 2; + const out: { start: number; text: string }[] = []; + const n = cues.length; + let i = 0; + let blockedUntil = -Infinity; + while (i < n) { + const t0 = cues[i].start; + if (t0 >= blockedUntil) { + let text = ""; + const offsets: { at: number; cue: number }[] = []; + for (let j = i; j < n && cues[j].start < t0 + windowSeconds; j++) { + const piece = cues[j].text.replace(/\s+/g, " ").trim(); + if (!piece) continue; + if (text) text += " "; + offsets.push({ at: text.length, cue: j }); + text += piece; + } + const m = text ? re.exec(text) : null; + if (m) { + let cue = offsets[0].cue; + for (const o of offsets) { + if (o.at <= m.index) cue = o.cue; + else break; + } + out.push({ start: Math.floor(cues[cue].start), text }); + blockedUntil = t0 + windowSeconds; + } + } + let k = i + 1; + while (k < n && cues[k].start < t0 + half) k++; + i = k; + } + return out; +} + +type Meta = { + upload_date?: unknown; + release_date?: unknown; + timestamp?: unknown; + title?: unknown; + fulltitle?: unknown; + duration?: unknown; + webpage_url?: unknown; +}; + +function metaDay(m: Meta): string { + for (const v of [m.upload_date, m.release_date]) { + if (typeof v === "string" && /^\d{8}$/.test(v)) return v; + } + if (typeof m.timestamp === "number" && Number.isFinite(m.timestamp)) { + return new Date(m.timestamp * 1000).toISOString().slice(0, 10).replace(/-/g, ""); + } + return ""; +} + +async function grepChannel( + opts: CorpusGrepOptions, + slug: string, + config: ChannelConfig, + result: CorpusGrepResult, +): Promise<void> { + const dataDir = path.join(opts.paths.channelsDir, slug, "data"); + const ids = [...(await heldVideoIds(dataDir))].sort(); + const since = opts.since ?? null; + const until = opts.until ?? null; + const dated = since !== null || until !== null; + // A video uploaded on or after `since` cannot have had its metadata written + // before that day: an mtime two days earlier (timezone slack) rules it out + // with one stat and no parse. Only false positives get through, and the + // upload_date check below settles those. + const floorMs = since + ? Date.UTC(Number(since.slice(0, 4)), Number(since.slice(4, 6)) - 1, Number(since.slice(6))) - 2 * DAY_MS + : null; + const windowSeconds = opts.windowSeconds ?? 30; + await mapConcurrent(ids, 8, async (id) => { + const videoDir = path.join(dataDir, id); + const metaPath = path.join(videoDir, "metadata.info.json"); + const st = await stat(metaPath).catch(() => null); + let meta: Meta | null = null; + if (st) { + if (floorMs !== null && st.mtimeMs < floorMs) return; + try { + meta = JSON.parse(await readFile(metaPath, "utf8")) as Meta; + } catch { + meta = null; + } + } + const day = meta ? metaDay(meta) : ""; + if (!day) { + result.undated++; + if (dated) return; + } else { + if (since && day < since) return; + if (until && day > until) return; + } + result.videosInRange++; + const titleOf = (m: Meta | null) => + typeof m?.title === "string" ? m.title : typeof m?.fulltitle === "string" ? m.fulltitle : ""; + let read; + try { + read = await readCuesInVideoDir({ slug, id, videoDir, configName: config.name }); + } catch (err) { + result.errors.push({ slug, id, error: (err as Error).message }); + return; + } + if (!read || read.cues.length === 0) { + result.noTranscript.push({ + date: dashed(day), + slug, + id, + title: titleOf(meta), + ...(typeof meta?.duration === "number" ? { duration: meta.duration } : {}), + }); + return; + } + result.videosSearched++; + const title = read.title ?? titleOf(meta); + const url = read.webpageUrl ?? (typeof meta?.webpage_url === "string" ? meta.webpage_url : undefined); + for (const w of grepCues(read.cues, opts.pattern, windowSeconds)) { + result.hits.push({ date: dashed(day), slug, id, start: w.start, title, text: w.text, ...(url ? { url } : {}) }); + } + }); +} + +export async function corpusGrep(opts: CorpusGrepOptions): Promise<CorpusGrepResult> { + const result: CorpusGrepResult = { + pattern: opts.pattern.source, + since: opts.since ? dashed(opts.since) : null, + until: opts.until ? dashed(opts.until) : null, + windowSeconds: opts.windowSeconds ?? 30, + channels: [], + skippedChannels: [], + videosInRange: 0, + videosSearched: 0, + noTranscript: [], + undated: 0, + totalHits: 0, + hits: [], + errors: [], + }; + let targets: { slug: string; config: ChannelConfig }[]; + if (opts.channels && opts.channels.length) { + targets = []; + for (const slug of opts.channels) { + const config = await readChannelConfig(opts.paths, slug); + if (!config) throw new Error(`Channel "${slug}" not found in ${opts.paths.channelsDir}`); + targets.push({ slug, config }); + } + } else { + targets = await listChannelConfigs(opts.paths); + } + for (const { slug, config } of targets) { + if (isSocialChannel(config)) { + if (opts.channels?.length) { + result.skippedChannels.push({ slug, reason: "a social channel: posts, not transcripts" }); + } + continue; + } + try { + await assertChannelTextReadable(opts.paths, slug, config); + } catch (err) { + const reason = (err as Error).message; + result.skippedChannels.push({ slug, reason }); + opts.onNote?.(`skipped ${slug}: ${reason}`); + continue; + } + result.channels.push(slug); + try { + await grepChannel(opts, slug, config, result); + } catch (err) { + // data/ could not be listed (not ENOENT — that is a channel holding + // nothing): say so rather than count it as empty. + result.channels.pop(); + result.skippedChannels.push({ slug, reason: (err as Error).message }); + opts.onNote?.(`skipped ${slug}: ${(err as Error).message}`); + } + } + const order = (a: { date: string; slug: string; id: string }, b: typeof a) => + a.date.localeCompare(b.date) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id); + result.hits.sort((a, b) => order(a, b) || a.start - b.start); + result.noTranscript.sort(order); + result.totalHits = result.hits.length; + if (opts.limit !== undefined && result.hits.length > opts.limit) { + result.hits = result.hits.slice(0, opts.limit); + } + return result; +} diff --git a/common/controller/keepVideosMatching.ts b/common/controller/keepVideosMatching.ts @@ -26,9 +26,10 @@ import { loadRoster } from "./rosterStore"; // // "MATCHES" MEANS WHAT THE DOWNLOAD FILTER MEANS BY IT. The pattern is compiled // by `compileDownloadFilter` (case-insensitive, the same source a channel's -// `downloadFilter.include` holds) and tested by `classifyAgainstFilter` over -// `downloadFilterText` — title + "\n" + description, the description capped -// exactly as the filter caps it. So a pattern that keeps the right videos here +// `downloadFilter.include` holds) and tested by `classifyAgainstFilter` +// against the title alone and `downloadFilterText` — title + "\n" + +// description, the description capped exactly as the filter caps it (so `^` +// and `$` anchor to the title). So a pattern that keeps the right videos here // is one that would download the right ones there, and vice versa. There is no // second matcher. `fields` narrows the SUBJECT, not the matcher: a field left // out is passed as empty. diff --git a/common/controller/videoCues.ts b/common/controller/videoCues.ts @@ -131,6 +131,22 @@ export async function readVideoCues( const st = await stat(videoDir).catch(() => null); if (!st?.isDirectory()) return { error: `Channel "${slug}" holds no video "${id}"`, status: 404 }; + const read = await readCuesInVideoDir({ slug, id, videoDir, configName: config.name }); + if (read) return read; + return { error: `${slug}/${id} has no transcript to read (no transcript.json and no English VTT)`, status: 404 }; +} + +// The read itself, for a caller that has already found the channel and passed +// its text guard (corpus grep walks every video of a channel through this): +// a fresh transcript.cues.json, else what normalize would write, else the +// English VTT alone. null when the video has no transcript to read. +export async function readCuesInVideoDir(opts: { + slug: string; + id: string; + videoDir: string; + configName?: string; +}): Promise<VideoCues | null> { + const { slug, id, videoDir } = opts; const files = await readVideoFiles(videoDir); const freshness = await isCuesJsonFresh(videoDir); const cuesJson: VideoCues["cuesJson"] = files.entries.includes(CUES_JSON_FILENAME) @@ -142,11 +158,11 @@ export async function readVideoCues( const t = await readNormalizedTranscript(freshness.cuesPath); if (t) return fromNormalized(slug, id, t, "cues.json", cuesJson); } - const built = await buildNormalizedTranscript({ videoDir, channelSlug: slug, configName: config.name }, files); + const built = await buildNormalizedTranscript({ videoDir, channelSlug: slug, configName: opts.configName }, files); if (built.status === "built") return fromNormalized(slug, id, built.transcript, "built", cuesJson); if (built.reason === "no-metadata") { const read = await readEnglishVttCues(videoDir, files.entries); if (read) return { slug, id, source: "vtt", cuesJson, file: read.filename, cues: read.cues }; } - return { error: `${slug}/${id} has no transcript to read (no transcript.json and no English VTT)`, status: 404 }; + return null; } diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -32,7 +32,12 @@ import { noteServiceStoppedJob, raisedServiceAlert, } from "../lib/serviceCookies-server"; -import { readXSessionStatus, type XSessionStatus } from "../social/xSessionBroker"; +import { + readXSessionStatus, + xCookieFile, + xProfileDir, + type XSessionStatus, +} from "../social/xSessionBroker"; import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource"; import { jobKindLabel, kindIsNetwork } from "./jobKinds"; import { queueGapPlatform } from "./queueGap"; @@ -166,38 +171,96 @@ export type XGuardResult = | { ok: true; note?: string } | { ok: false; message: string; alert: boolean }; -export async function xJobGuard(opts: { +// WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and +// its verdict in one record, for `pnpm ops get x-session` (an agent asks it +// before it queues an X fetch). xJobGuard below is this record's verdict, so +// the report and the refusal are one computation, not two that look alike. +export type XSessionReport = { + // The login source in use ("profile": the session broker's exported jar; + // "browser": cookiesFromBrowser), and whether settings chose it. + source: XCookieSource; + sourceChosen: boolean; + browserSpec?: string; + profileDir: string; + cookieFile: string; + hasProfile: boolean; + hasCookies: boolean; + looksAuthenticated: boolean; + // When the jar was last written (Connect X / Refresh cookies), and its age. + cookiesUpdatedAt: string | null; + ageMinutes: number | null; + // social.x.maxCookieAgeMinutes, resolved (0 = off). + maxAgeMinutes: number; + // False when the age is not checked: the browser source, or a limit of 0. + ageChecked: boolean; + // The X cookie alert, when it is up (a challenge or a login wall). + alert: { raisedAt: string; line: string } | null; + // Would an X job start now? `reason` is the refusal it would get. + allowed: boolean; + reason: string | null; + note?: string; +}; + +export async function xSessionReport(opts: { paths: Paths; channelSlug?: string; now?: number; -}): Promise<XGuardResult> { +}): Promise<XSessionReport> { const now = opts.now ?? Date.now(); - const alert = await raisedServiceAlert(opts.paths, X_SERVICE); - if (alert) { - const at = (alert.raisedAt ?? alert.since).slice(11, 16); - return { - ok: false, - alert: true, - message: - `X answered with a challenge at ${at} UTC (${alert.evidence.line}) and its cookie alert is up, ` + - `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, - }; - } - const settings = settingsNow(); - if (!settings) return { ok: true }; const status = await readXSessionStatus(opts.paths); + const settings = settingsNow(); const resolved = resolveXCookieSource({ - stored: settings.social?.x?.cookieSource, - browserSpec: await channelCookieSpec(opts.paths, opts.channelSlug, settings), + stored: settings?.social?.x?.cookieSource, + browserSpec: settings ? await channelCookieSpec(opts.paths, opts.channelSlug, settings) : undefined, profileConnected: status.looksAuthenticated, }); - const verdict = xJarVerdict({ + const maxAgeMinutes = + settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x); + const ageMinutes = status.cookiesUpdatedAt + ? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000)) + : null; + const base = { source: resolved.source, - status, - maxAgeMinutes: settings.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings.social?.x), - now, - }); - return verdict.ok ? verdict : { ok: false, message: verdict.message, alert: false }; + sourceChosen: resolved.chosen, + ...(resolved.browserSpec ? { browserSpec: resolved.browserSpec } : {}), + profileDir: xProfileDir(opts.paths), + cookieFile: xCookieFile(opts.paths), + hasProfile: status.hasProfile, + hasCookies: status.hasCookies, + looksAuthenticated: status.looksAuthenticated, + cookiesUpdatedAt: status.cookiesUpdatedAt ?? null, + ageMinutes, + maxAgeMinutes, + ageChecked: resolved.source === "profile" && maxAgeMinutes > 0, + }; + const raised = await raisedServiceAlert(opts.paths, X_SERVICE); + if (raised) { + const at = (raised.raisedAt ?? raised.since).slice(11, 16); + return { + ...base, + alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line }, + allowed: false, + reason: + `X answered with a challenge at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` + + `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, + }; + } + // Settings unreadable: the guard has nothing to apply and lets the job run. + if (!settings) return { ...base, alert: null, allowed: true, reason: null }; + const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); + return verdict.ok + ? { ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) } + : { ...base, alert: null, allowed: false, reason: verdict.message }; +} + +export async function xJobGuard(opts: { + paths: Paths; + channelSlug?: string; + now?: number; +}): Promise<XGuardResult> { + const r = await xSessionReport(opts); + if (r.allowed) return r.note ? { ok: true, note: r.note } : { ok: true }; + return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null }; } // ── the one entry point ──────────────────────────────────────────────────── diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -234,6 +234,32 @@ test("a stale jar is refused at enqueue, and at the start of a job queued while assert.match(c.ok ? "" : c.error, /holds no login/); }); +test("get x-session reports what the guard would answer: source, age, limit, allowed", async () => { + await reset(); + const { xSessionReport, xJobGuard } = await import("./networkGuard"); + await writeJar(5 * 60_000); + const fresh = await xSessionReport({ paths }); + assert.equal(fresh.source, "profile"); + assert.equal(fresh.sourceChosen, true); + assert.equal(fresh.looksAuthenticated, true); + assert.equal(fresh.maxAgeMinutes, 60); + assert.equal(fresh.ageChecked, true); + assert.ok(fresh.ageMinutes !== null && fresh.ageMinutes >= 4 && fresh.ageMinutes <= 6, String(fresh.ageMinutes)); + assert.equal(fresh.allowed, true); + assert.equal(fresh.reason, null); + assert.equal(fresh.profileDir, path.join(transcripts, ".x-session", "profile")); + assert.deepEqual(await xJobGuard({ paths }), { ok: true }); + + await writeJar(2 * 60 * 60_000); + const stale = await xSessionReport({ paths }); + assert.equal(stale.allowed, false); + assert.ok(stale.ageMinutes !== null && stale.ageMinutes >= 119); + assert.match(stale.reason ?? "", /^X cookies were last refreshed 2 h ago \(limit 60 min\)/); + const guard = await xJobGuard({ paths }); + assert.equal(guard.ok, false); + assert.equal(guard.ok ? "" : guard.message, stale.reason); +}); + test("a network job is never run unqueued: the override \"\" is refused", async () => { await reset(); await writeJar(60_000); diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -87,9 +87,9 @@ export type DownloadFilterConfig = { export const DOWNLOAD_FILTER_FIELD_DOCS: FieldDocs<DownloadFilterConfig> = { include: - "Case-insensitive regex SOURCE (no delimiters, no flags) a video's `title + \"\\n\" + description` must match to be downloaded. Trimmed; blank = no include rule.", + "Case-insensitive regex SOURCE (no delimiters, no flags) a video must match to be downloaded. It is tested against the title alone AND against `title + \"\\n\" + description`, and either match counts — so `^` and `$` anchor to the title (`^EPISODE (12|13)$` matches that exact title). Trimmed; blank = no include rule.", exclude: - "Case-insensitive regex source that rejects a matching video. Wins over `include`. Trimmed; blank = no exclude rule.", + "Case-insensitive regex source that rejects a matching video, tested the same way as `include` (title alone, or title + description; `^`/`$` anchor to the title). Wins over `include`. Trimmed; blank = no exclude rule.", includeLivestreams: "Opt every livestream VOD in, whatever it is called. A SECOND positive selector beside `include`, not a modifier of it — so `{ includeLivestreams: true }` alone rejects plain uploads and passes livestreams. Stored only when `true`.", rejectedLivestreams: diff --git a/common/lib/downloadFilters.test.ts b/common/lib/downloadFilters.test.ts @@ -8,6 +8,7 @@ import { downloadFilterPatternProblem, downloadFilterText, evaluateDownloadFilters, + titleFilterReason, titleFilterRejects, titleFilterWantsChat, type DownloadFilterContext, @@ -498,3 +499,55 @@ test("evaluateDownloadFilters marks the decision, and it is still a skip", () => assert.match(decision.reason, /live chat only/); }); + +// `^` and `$` anchor to the TITLE (downloadFilterPatternMatches). Before, the +// pattern only saw title + "\n" + description, where `$` is the end of the +// description, so an exact-title include selected nothing +// (h3-podcast-audio-feed, 2026-10-25). +test("a $-anchored include matches the exact title", () => { + const f = compiled("^ROOSTER(123|456)$"); + const hit = meta({ title: "Rooster456", description: "An episode." }); + assert.equal(classifyAgainstFilter(f, hit), "text"); + assert.equal(titleFilterRejects(f, hit), false); + // Still anchored: a longer title does not match. + assert.equal( + titleFilterRejects(f, meta({ title: "Rooster456 part 2", description: "" })), + true, + ); +}); + +test("an exclude ending in $ rejects a title ending that way", () => { + const f = compiled(undefined, "\\(rerun\\)$"); + const rerun = meta({ title: "Big show (rerun)", description: "A long description." }); + assert.equal(titleFilterRejects(f, rerun), true); + assert.match(titleFilterReason(f, rerun), /matches exclude/); + assert.equal( + titleFilterRejects(f, meta({ title: "Big show", description: "not a (rerun) here" })), + false, + ); +}); + +test("description-only matches behave exactly as before", () => { + const f = compiled("special guest"); + const inDesc = meta({ title: "Episode 9", description: "With a special guest." }); + assert.equal(classifyAgainstFilter(f, inDesc), "text"); + assert.equal( + titleFilterRejects(f, meta({ title: "Episode 9", description: "Solo." })), + true, + ); + // A $ at the end of the description still matches the joined text. + const end = compiled("guest\\.$"); + assert.equal(classifyAgainstFilter(end, inDesc), "text"); + // An exclude matching only the description still wins. + const ex = compiled("episode", "sponsor"); + assert.equal( + titleFilterRejects(ex, meta({ title: "Episode 9", description: "Our sponsor today" })), + true, + ); +}); + +test("an empty title is not tested alone (a pattern matching the empty string)", () => { + const f = compiled("^$"); + assert.equal(titleFilterRejects(f, meta({ title: "", description: "words" })), true); + assert.equal(titleFilterRejects(f, meta({ title: "Episode", description: "" })), true); +}); diff --git a/common/lib/downloadFilters.ts b/common/lib/downloadFilters.ts @@ -180,6 +180,30 @@ export function downloadFilterText( return `${meta?.title ?? ""}\n${description}`; } +// Does one of a filter's patterns match this video? It matches when it +// matches the TITLE ALONE or the title + "\n" + description text, so `^` and +// `$` anchor to the title. Before this, the pattern only ever saw the joined +// text (flags "i", no "m"), where `$` is the end of the DESCRIPTION — so +// `^ROOSTER(123|456)$` could never match a title, and the +// h3-podcast-audio-feed channel's filter selected nothing for two days. +// Every pattern that does not anchor to the end behaves exactly as before: a +// match inside the title is also a match inside the joined text, so the +// title-alone test only ever ADDS the matches an end anchor (or a lookahead +// past the title's end) used to miss. +export function downloadFilterPatternMatches( + pattern: RegExp, + meta: FilterableVideo | null | undefined, +): boolean { + // An empty title is not tested alone: a pattern that matches the empty + // string (`^$`, `^(?!…)`) would otherwise pass every untitled video — and + // every video of a keep-videos run narrowed to the description. + const title = meta?.title ?? ""; + return ( + (title !== "" && pattern.test(title)) || + pattern.test(downloadFilterText(meta)) + ); +} + // Is this pattern safe to hand to the matcher? The operator's regex runs over // every stored title+description on every snapshot, every sync page and every // render of the Configure stage, on the server's single thread — so a @@ -233,7 +257,8 @@ export type DownloadFilterVerdict = // 2. With NO positive selector (an exclude-only filter), everything else // passes. // 3. Otherwise a video must satisfy at least one positive selector: the -// `include` pattern over title + "\n" + description, or — when +// `include` pattern over the title alone or title + "\n" + description +// (downloadFilterPatternMatches), or — when // `includeLivestreams` is on — being a livestream. // // THE CORNER WORTH STATING: `{ includeLivestreams: true }` with no `include` @@ -245,13 +270,14 @@ export function classifyAgainstFilter( compiled: CompiledDownloadFilter, meta: FilterableVideo, ): DownloadFilterVerdict { - const text = downloadFilterText(meta); - if (compiled.exclude && compiled.exclude.test(text)) { + if (compiled.exclude && downloadFilterPatternMatches(compiled.exclude, meta)) { return rejection(compiled, meta); } const hasPositive = Boolean(compiled.include || compiled.includeLivestreams); if (!hasPositive) return "text"; - if (compiled.include && compiled.include.test(text)) return "text"; + if (compiled.include && downloadFilterPatternMatches(compiled.include, meta)) { + return "text"; + } if (compiled.includeLivestreams && isLivestream(meta)) return "livestream"; return rejection(compiled, meta); } @@ -297,8 +323,7 @@ export function titleFilterReason( compiled: CompiledDownloadFilter, meta: FilterableVideo, ): string { - const text = downloadFilterText(meta); - if (compiled.exclude && compiled.exclude.test(text)) { + if (compiled.exclude && downloadFilterPatternMatches(compiled.exclude, meta)) { return `title/description matches exclude /${compiled.exclude.source}/i`; } const wants: string[] = []; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,6 +3,9 @@ ## [Unreleased] - **A take of part of a cut (`--at`) now shows the clips its own changes add.** The window is timed against the project's cut so every take of a group covers the same clips, and a clip only the take adds (a montage line, an extra beat) was never in it: the Huck cut's pitch-count take rendered seven of its eight pitches. A clip the take adds right after one the window covers now renders with it. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). - **An assistant can now change a report video's timeline, find a clip's scene cuts, and add a post from the archive, all from the command line.** `umtool timeline <project>` lists the cut (index, id, type, video, start–end, date and title) and does what the Cut tab's timeline does: `insert --after <id> <channel>/<video>@<start>-<end>` with `--title`, `--date`, `--quote` and `--cite`, `move <id> --to <index>`, `remove`, `duplicate`, `post`, `post-remove`, `teaser` and `undo`. It goes through the same writers as the page, so each change saves an undo point first, is refused when the build would refuse it, and leaves an edit note on a generated manifest. A bad `--date` is refused before anything is written. `umtool scenes <project> <clip>` prints where the picture cuts and where it goes black in the clip's fetched window, in the recording's own seconds, for setting a blur's from and to or a trim: the Huck dog clip is black 250.49–251.09 and cuts at 251.09. It fetches nothing. `umtool posts add <project> <channel>/<postId>` makes a post card from the posts archive (its words, date, link, handle and screenshot, with `--attach <clip>` and `--flag`) and copies the capture into the project's `posts-media/`. A post with no screenshot is refused, and the message names the `pnpm ops capture-posts` to run first. +- **A download filter's `^` and `$` now anchor to the video's title.** A filter pattern was only ever matched against the title and the description joined together, where `$` means the end of the description, so a pattern that names exact titles (`^ROOSTER(123|456)$`) could never match: the h3-podcast-audio-feed channel's filter selected nothing for two days. Include and exclude now match when the pattern matches the title alone or the title and description together, as before. A pattern with no `$` at its end behaves exactly as it did. The channel's Playlist stage, the download lane, Download missing and `pnpm ops keep-videos` all use the same rule, and the Configure form's hints say so. Needs a restart of the editor. +- **`pnpm archilyzer corpus grep` searches the live corpus's transcripts from a terminal, with no editor and no index.** `--regex '<pattern>'` with `--channels a,b`, `--since YYYY-MM-DD`, `--until`, `--window 30`, `--limit N`, `--case-sensitive` and `--json`. It reads each held video's transcript the way the video page does (the cues file, else the best English caption track, en-orig before en), dates it by the video's upload date, and prints each hit's date, channel, id, start second, title and 30 seconds of text, then the videos in range that have no transcript yet. A channel whose drive is not answering is skipped and named. The MCP and the sites read only what was last published; this reads what is on disk now. It writes nothing. +- **`pnpm ops get x-session` says whether an X job would start now, and why not.** It answers the X login in use (the connected profile's cookie jar, or the browser's cookies), when the jar was last refreshed and its age in minutes, the limit (`social.x.maxCookieAgeMinutes`), whether X's cookie alert is up, `allowed`, and the refusal an X job would get. It is the same check that refuses a stale-cookie X job, so an assistant can ask before it queues an X fetch instead of finding out from a refusal. Needs a restart of the editor. - **A tall post screenshot in the posts feed grows into the room the column has, instead of shrinking to a thumbnail.** A screenshot was capped at the height of a card of words and drawn smaller to fit it, so a post with a picture (the Huck video's "Hucks home!!!!!! God Is Good!!!") came out a narrow strip beside empty space. Now a picture cut by that cap grows, up to its own full-width height, into the room left in the column beside the card under it — that card stays on screen; only cards further down scroll out as before. A post that fits, and a card of words, are drawn as they were. Needs a restart of umtool and a rebuild of the video. - **Every wait before the archive asks a site now varies a little, and only ever upward.** A job every 20.0 s, a page every 3.0 s or a sync at the same minute each day is a machine's beat, so each such wait is now stretched by up to a quarter of itself at random, and never shortened: every pacing number stays a minimum (Rumble's 120 s, X's 5 min, the sleep between downloads). It covers the gap between two downloads and between two jobs on one platform, yt-dlp's `--sleep-requests` and `--sleep-subtitles` (drawn once per yt-dlp run, and shown in its logged command line), the archive.org, Wayback and web-fetch gaps, the rate-limit cooldowns and the platform hold's probe, the download lane's metadata-scan batches (60 to 75 titles) and its rests, Save Page Now's and the Kick recorder's polls, and each channel's sync interval (later by at most 30 minutes, the same on every tick until it syncs, and shown so on /operations/sync). The share is **Jitter on every wait before a request** on /settings (`pacing.jitter`, default 25 %; 0 turns it off). Three waits that already varied could come out SHORTER than their minimum and no longer do: the platform cooldown (±10 %), archive.org's back-off (±20 %) and a forum's page pause (as little as 0.85 of it, under its own 5 s floor). It now lands between the pause and 1.8 times it. Four loops that asked a site with no gap at all now wait between requests: a Bluesky feed's pages (3–6 s), a Nitter timeline's pages (4 s and up), the availability check's per-video probes (3 s and up) and umtool's network clip fetches in a build with no editor (one at a time per platform, 30 s apart, Rumble 120 s). Needs a restart of the editor and of umtool. - **The download lane's metadata scan reads 60 titles at a time and lets the downloads run in between.** A filtered channel's scan holds its platform's download queue while it runs, and the lane used to scan the whole backlog in one go: on 2026-10-25 the scan of h3-podcast's 1,163 unread titles, which started the moment the channel's download pause was lifted, held YouTube from 03:20 to 06:36 and nothing downloaded. The lane now scans 60 titles (about 10 minutes on YouTube), gives that platform 20 minutes of downloads, then scans the next 60, and its log says so: "1103 listed videos left to scan for h3-podcast; the next batch after 20 minutes of downloads." A scan that a platform stopped (a soft block, a rate limit) is still not retried until the next restart. **Run** on the metadata-scan operation still scans the whole backlog. Needs a restart of the editor. diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts @@ -46,7 +46,7 @@ const route = async (name: string) => (await import(`./${name}/route`)).GET as G test.after(() => corpus.cleanup()); test("every read route is behind the token", async () => { - for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates"]) { + for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates", "x-session"]) { const res = await callGet(await route(name), undefined, {}, {}); assert.equal(res.status, 401, name); } @@ -147,6 +147,24 @@ test("get saved-alternates lists the saved videos holding two copies (none here) assert.equal(bad.status, 400); }); +test("get x-session answers the X login and the guard's verdict: no jar here, so an X job would be refused", async () => { + const get = await route("x-session"); + const res = await callGet(get); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.source, "profile"); + assert.equal(res.body.hasCookies, false); + assert.equal(res.body.ageMinutes, null); + assert.equal(typeof res.body.maxAgeMinutes, "number"); + if ((res.body.maxAgeMinutes as number) > 0) { + assert.equal(res.body.allowed, false); + assert.match(String(res.body.reason), /No X cookie jar has been exported/); + } + const bad = await callGet(get, "http://localhost/api/ops/x-session?slug=../x"); + assert.equal(bad.status, 400); + const stray = await callGet(get, "http://localhost/api/ops/x-session?channel=x"); + assert.equal(stray.status, 400); +}); + test("/api/auto-queue/control is behind the ops token now", async () => { const { POST } = await import("../auto-queue/control/route"); const anon = await callPost(POST, { kind: "download", action: "stop" }, {}); diff --git a/editor/app/api/ops/x-session/route.ts b/editor/app/api/ops/x-session/route.ts @@ -0,0 +1,27 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import { readRoute } from "../_read"; +import { opsFail } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// GET /api/ops/x-session[?slug=<channel>] +// -> { ok, source, sourceChosen, browserSpec?, profileDir, cookieFile, +// hasProfile, hasCookies, looksAuthenticated, cookiesUpdatedAt, +// ageMinutes, maxAgeMinutes, ageChecked, alert, allowed, reason, note? } +// +// The X login an X job would use and whether one would start NOW: the +// fresh-jar rule's inputs (the source, the exported jar's age, the limit +// social.x.maxCookieAgeMinutes) and its verdict, from xSessionReport — the +// record the network guard refuses an X job with (common/jobs/networkGuard.ts). +// `slug` names a channel whose own cookiesFromBrowser may decide the source. +// Nothing is asked of X and nothing is written: a refresh is a human click on +// /settings (Refresh cookies / Connect X account). +export async function GET(request: Request) { + return readRoute(request, ["slug"], async (q) => { + const slug = q.get("slug")?.trim() || undefined; + if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); + return { ...(await xSessionReport({ paths: getPaths(), channelSlug: slug })) }; + }); +} diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -923,7 +923,7 @@ export function ChannelForm({ value={filterInclude} onChange={setFilterInclude} placeholder="(download everything)" - hint="Case-insensitive regex. Only videos whose title + description match are downloaded. Run Metadata scan on the Playlist stage to read the titles first — non-matching videos are then settled (never downloaded, never retried) until you change this. The listing and the roster stay complete either way." + hint="Case-insensitive regex. Only videos whose title, or title + description, match are downloaded; ^ and $ anchor to the title. Run Metadata scan on the Playlist stage to read the titles first — non-matching videos are then settled (never downloaded, never retried) until you change this. The listing and the roster stay complete either way." /> <Field label="Download filter: exclude (regex)" @@ -931,7 +931,7 @@ export function ChannelForm({ value={filterExclude} onChange={setFilterExclude} placeholder="(exclude nothing)" - hint="Case-insensitive regex, applied to title + description and winning over include. Matching videos are settled until you change this. Patterns are capped at 200 characters and must not nest quantifiers — this runs on the server for every stored title." + hint="Case-insensitive regex, applied like include (^ and $ anchor to the title) and winning over include. Matching videos are settled until you change this. Patterns are capped at 200 characters and must not nest quantifiers — this runs on the server for every stored title." /> <label className="flex items-start gap-2 text-sm"> <input diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -108,6 +108,7 @@ // pnpm ops fetch-windows --file windows.json --wait // pnpm ops get tags eva-collab // pnpm ops get services +// pnpm ops get x-session // pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}' // pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait @@ -259,6 +260,11 @@ const GETTERS = { // The dashboard's cookie refresh alerts: each service whose cookies look // stale (or are OK again, with the jobs the alert stopped). services: () => "/api/ops/services", + // The X login an X job would use and whether one would start now: the + // source, the exported jar's age, social.x.maxCookieAgeMinutes and the + // network guard's verdict (common/jobs/networkGuard.ts xSessionReport). + "x-session": (slug) => + slug ? `/api/ops/x-session?slug=${encodeURIComponent(slug)}` : "/api/ops/x-session", // One channel's cleanup row: what each sweep would reclaim, what holds the rest. cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`, // What a channel holds, by date, and its gaps (release 19 A9): each video @@ -308,6 +314,7 @@ const GET_ARG_OPTIONAL = new Set([ "auto-queue", "scheduler", "services", + "x-session", "generation-usage", ]); @@ -937,6 +944,7 @@ export function usage() { " pnpm ops get storage | sites | workers | auto-queue | scheduler", " pnpm ops get saved-alternates [<slug>]", " pnpm ops get services", + " pnpm ops get x-session [<slug>]", " pnpm ops get cleanup <slug>", " pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]", " pnpm ops get transcript <videoId> [--slug <slug>]", @@ -988,6 +996,16 @@ export function usage() { " (rumble, youtube, odysee, archive.today, a forum host) whose cookies look", " stale, or are OK again with the jobs the alert stopped; \"pending\" lists", " a first Rumble embed 403 waiting for a second video.", + "get x-session [<slug>] is the X login an X job would use and whether one", + " would start NOW, from the same check that refuses a stale-cookie X job:", + " source (\"profile\": the exported jar under transcripts/.x-session;", + " \"browser\": cookiesFromBrowser, whose age cannot be read), hasCookies,", + " looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes", + " (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up,", + " allowed, and reason (the refusal an X job would get). <slug> names a", + " channel whose own cookiesFromBrowser may decide the source. Nothing is", + " asked of X: a refresh is Refresh cookies / Connect X account on", + " /settings. Ask it before queueing fetch-posts or capture-posts on X.", "get cleanup <slug> is one channel's /cleanup row: what each sweep would", " reclaim (they overlap — never add them), what holds the rest, and the", " failed-transcriptions count. measured: false means unknown, not zero.", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -867,6 +867,16 @@ test("get services is a GET on its route; recheck/dismiss/rerun are POSTs named } }); +// X SESSION FRESHNESS: what an agent asks before it queues an X fetch. +test("get x-session is a GET on its route, with an optional channel", () => { + const g = parseArgs(["get", "x-session"]); + assert.equal(g.method, "GET"); + assert.equal(g.path, "/api/ops/x-session"); + assert.equal(parseArgs(["get", "x-session", "some-x"]).path, "/api/ops/x-session?slug=some-x"); + assert.match(usage(), /pnpm ops get x-session \[<slug>\]/); + assert.match(usage(), /maxAgeMinutes/); +}); + // RELEASE 36 LANE A: the clip finder's chain and one video's chat replay. test("fetch-chat and find-clips are POSTs named in the usage; find-clips --wait carries its marker", () => { for (const action of ["fetch-chat", "find-clips"]) {