commit efd657eabdc650ec88efdc35ff7ab1bab448ffa7
parent 36387cf2ce84e782680aa354317f472fb52f492f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 19:26:00 -0500
channels: pnpm ops channel-rank places one channel in the order the lanes follow
Only /channels' "Add to top" could move a channel, and it also sets the tier
to normal and turns the download lane on. channel-rank moves the rank alone —
{slug} and one of rank (n | null), top, bottom, before, after — as a "rank"
edit through saveChannelPriorityAction, so the four lane roots recompile in
the same write. Every other channel keeps its order (a taken rank shifts it
and everything below it down one); placeChannelRank and rankedOrder are pure,
in common/lib/channelPriority.ts. Refused before any write: an unknown channel
or anchor, an unranked anchor, a bad rank, a channel paused everywhere.
COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 434 insertions(+), 1 deletion(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -123,6 +123,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| action | what it does | example |
|---|---|---|
| `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` |
+| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": <n> (a rank already held, and every rank below it, shift down one) or null (unranked), "top": true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked channel). Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` |
| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "<regex with named groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` |
| `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` |
| `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` |
diff --git a/common/lib/channelPriority.ts b/common/lib/channelPriority.ts
@@ -635,6 +635,94 @@ export function renameChannelInPriority(
return { focus, channels };
}
+// --- Placing one channel's rank ---------------------------------------------
+
+// WHERE A CHANNEL GOES IN THE ORDER (`pnpm ops channel-rank`). The model has
+// ONE rank per channel, ascending, unranked after every ranked channel (then by
+// slug) — the same order inside every tier group (`orderWithin`). A placement
+// moves one channel and leaves the order of every other exactly as it was:
+//
+// rank n the channel takes rank n; when another channel holds n,
+// it and every channel ranked below it shift down one;
+// top / bottom before every ranked channel / after every ranked channel;
+// before / after immediately before / after another RANKED channel (an
+// unranked one has no place to be next to — refused);
+// unrank the rank removed: last in its tier, by slug.
+//
+// Only the rank moves. Unlike "Add to top" (the deck's promote, which also
+// sets the tier to normal and turns the download lane on), a placement never
+// changes a tier, an override, a focus or an auto-pause.
+export type RankPlacement =
+ | { kind: "rank"; rank: number }
+ | { kind: "top" }
+ | { kind: "bottom" }
+ | { kind: "before"; slug: string }
+ | { kind: "after"; slug: string }
+ | { kind: "unrank" };
+
+// A placement the document cannot carry out, in the words the caller sees.
+export class RankPlacementError extends Error {}
+
+export function placeChannelRank(
+ model: ChannelPriority,
+ rawSlug: string,
+ place: RankPlacement,
+): ChannelPriority {
+ const slug = rawSlug.trim();
+ if (!slug) throw new RankPlacementError("No channel slug supplied.");
+ const current = model.channels[slug];
+ if (place.kind === "unrank") {
+ if (current?.rank === undefined) return model;
+ const { rank: _dropped, ...rest } = current;
+ return { ...model, channels: { ...model.channels, [slug]: rest } };
+ }
+ const others = Object.entries(model.channels).filter(
+ ([s, e]) => s !== slug && e.rank !== undefined,
+ ) as [string, ChannelPriorityEntry & { rank: number }][];
+ let rank: number;
+ if (place.kind === "rank") {
+ if (!Number.isInteger(place.rank) || place.rank < 0) {
+ throw new RankPlacementError(`A rank is a whole number, 0 or more (0 = first); got ${place.rank}.`);
+ }
+ rank = place.rank;
+ } else if (place.kind === "top") {
+ rank = others.length ? Math.min(...others.map(([, e]) => e.rank)) : 0;
+ } else if (place.kind === "bottom") {
+ rank = others.length ? Math.max(...others.map(([, e]) => e.rank)) + 1 : 0;
+ } else {
+ const anchor = place.slug.trim();
+ if (anchor === slug) {
+ throw new RankPlacementError(`"${slug}" cannot be placed ${place.kind} itself.`);
+ }
+ const anchorRank = model.channels[anchor]?.rank;
+ if (anchorRank === undefined) {
+ throw new RankPlacementError(
+ `"${anchor}" has no rank, so there is no place ${place.kind} it — rank it first ` +
+ `(top, bottom or a rank), or place "${slug}" by rank.`,
+ );
+ }
+ rank = place.kind === "before" ? anchorRank : anchorRank + 1;
+ }
+ const taken = others.some(([, e]) => e.rank === rank);
+ const channels: Record<string, ChannelPriorityEntry> = {};
+ for (const [s, entry] of Object.entries(model.channels)) {
+ channels[s] =
+ taken && s !== slug && entry.rank !== undefined && entry.rank >= rank
+ ? { ...entry, rank: entry.rank + 1 }
+ : entry;
+ }
+ channels[slug] = { ...(current ?? { tier: DEFAULT_CHANNEL_TIER }), rank };
+ return { ...model, channels };
+}
+
+// The ranked channels in the order the lanes take them: rank, then slug.
+export function rankedOrder(model: ChannelPriority): { slug: string; rank: number }[] {
+ return Object.entries(model.channels)
+ .filter(([, e]) => e.rank !== undefined)
+ .map(([slug, e]) => ({ slug, rank: e.rank as number }))
+ .sort((a, b) => a.rank - b.rank || a.slug.localeCompare(b.slug));
+}
+
export function tierOrder(tier: ChannelTier): number {
const i = CHANNEL_TIERS.indexOf(tier);
return i < 0 ? CHANNEL_TIERS.length : i;
diff --git a/common/lib/channelRank.test.ts b/common/lib/channelRank.test.ts
@@ -0,0 +1,78 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ placeChannelRank,
+ rankedOrder,
+ RankPlacementError,
+ sanitizeChannelPriority,
+ type ChannelPriority,
+} from "./channelPriority";
+
+// `pnpm ops channel-rank`: one channel moved in the ONE order; every other
+// channel's order kept exactly; nothing but the rank changes.
+const doc = (channels: ChannelPriority["channels"]): ChannelPriority => ({ focus: { kind: "none" }, channels });
+const order = (m: ChannelPriority) => rankedOrder(m).map((r) => r.slug);
+const ABC = doc({
+ a: { tier: "normal", rank: 0 },
+ b: { tier: "low", rank: 1, overrides: { sync: "normal" } },
+ c: { tier: "normal", rank: 2 },
+ u: { tier: "paused", overrides: { sync: "normal" } },
+});
+
+test("top and bottom: first and last of the ranked channels; tier and overrides untouched", () => {
+ const top = placeChannelRank(ABC, "c", { kind: "top" });
+ assert.deepEqual(order(top), ["c", "a", "b"]);
+ assert.deepEqual(top.channels.b, { tier: "low", rank: 2, overrides: { sync: "normal" } });
+ const bottom = placeChannelRank(ABC, "a", { kind: "bottom" });
+ assert.deepEqual(order(bottom), ["b", "c", "a"]);
+ assert.equal(bottom.channels.a.rank, 3, "after the last rank; nothing else shifts");
+ assert.equal(bottom.channels.b.rank, 1);
+ // An unranked channel taken to the top keeps its tier and overrides.
+ const u = placeChannelRank(ABC, "u", { kind: "top" });
+ assert.deepEqual(order(u), ["u", "a", "b", "c"]);
+ assert.deepEqual(u.channels.u, { tier: "paused", overrides: { sync: "normal" }, rank: 0 });
+ // A channel with no entry at all gets one, at the default tier.
+ assert.deepEqual(placeChannelRank(ABC, "new", { kind: "bottom" }).channels.new, { tier: "normal", rank: 3 });
+ // Nothing ranked: top and bottom are both rank 0.
+ assert.equal(placeChannelRank(doc({}), "x", { kind: "top" }).channels.x.rank, 0);
+ assert.equal(placeChannelRank(doc({}), "x", { kind: "bottom" }).channels.x.rank, 0);
+});
+
+test("before and after another ranked channel", () => {
+ assert.deepEqual(order(placeChannelRank(ABC, "a", { kind: "before", slug: "c" })), ["b", "a", "c"]);
+ assert.deepEqual(order(placeChannelRank(ABC, "c", { kind: "after", slug: "a" })), ["a", "c", "b"]);
+ assert.deepEqual(order(placeChannelRank(ABC, "a", { kind: "after", slug: "c" })), ["b", "c", "a"]);
+ assert.deepEqual(order(placeChannelRank(ABC, "u", { kind: "before", slug: "a" })), ["u", "a", "b", "c"]);
+ assert.throws(
+ () => placeChannelRank(ABC, "a", { kind: "before", slug: "u" }),
+ (e: Error) => e instanceof RankPlacementError && /"u" has no rank, so there is no place before it/.test(e.message),
+ );
+ assert.throws(() => placeChannelRank(ABC, "a", { kind: "after", slug: "a" }), /cannot be placed after itself/);
+});
+
+test("rank n: taken pushes it and everything below down one; free takes the gap; unrank removes it", () => {
+ const taken = placeChannelRank(ABC, "c", { kind: "rank", rank: 1 });
+ assert.deepEqual(order(taken), ["a", "c", "b"]);
+ assert.deepEqual(rankedOrder(taken), [
+ { slug: "a", rank: 0 },
+ { slug: "c", rank: 1 },
+ { slug: "b", rank: 2 },
+ ]);
+ const gap = placeChannelRank(doc({ a: { tier: "normal", rank: 0 }, c: { tier: "normal", rank: 10 } }), "b", {
+ kind: "rank",
+ rank: 5,
+ });
+ assert.deepEqual(rankedOrder(gap), [
+ { slug: "a", rank: 0 },
+ { slug: "b", rank: 5 },
+ { slug: "c", rank: 10 },
+ ]);
+ assert.throws(() => placeChannelRank(ABC, "a", { kind: "rank", rank: -1 }), /a whole number, 0 or more/);
+ assert.throws(() => placeChannelRank(ABC, "a", { kind: "rank", rank: 1.5 }), /a whole number, 0 or more/);
+ const un = placeChannelRank(ABC, "b", { kind: "unrank" });
+ assert.deepEqual(order(un), ["a", "c"]);
+ assert.deepEqual(un.channels.b, { tier: "low", overrides: { sync: "normal" } });
+ // A channel whose entry said only its rank is dropped by the sanitizer.
+ assert.equal(sanitizeChannelPriority(placeChannelRank(ABC, "a", { kind: "unrank" })).channels.a, undefined);
+ assert.equal(placeChannelRank(ABC, "u", { kind: "unrank" }), ABC, "nothing to remove: the input");
+});
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: if the rank is already taken, that channel and every one below it shift down one. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
- **Configure's Caption languages field (`subLangs`) is checked when you save.** Before, any text was saved, and a value yt-dlp's `--sub-langs` cannot use failed every caption download on the channel at the moment it ran. Configure and `pnpm ops channel-config` (`patch.subLangs`) now refuse it, in the field's words, with what you typed kept. Refused: an empty entry (two commas, or one at an end), a space inside an entry, a bare `-`, an entry that is not a regular expression, or a value over 200 characters. Spaces around an entry are dropped (`en.* , es` saves as `en.*,es`). `all` and `-<lang>` exclusions are accepted as before (`common/lib/channelConfig.ts` `subLangsProblem`).
- **Transcribe refuses a video that is live.** On 4 Nov a transcribe-one on a live YouTube video downloaded the stream at 1x and held `platform:youtube` for the stream's whole length. Now the video page's Transcribe and `pnpm ops transcribe-one` refuse a video whose `metadata.info.json` says it is live (`is_live`), scheduled (`is_upcoming`) or still processing its VOD (`post_live`), before anything is queued. The refusal names `pnpm ops record-live` for the stream (not for `post_live`), says to wait for the VOD otherwise, and names `refresh-metadata` to re-read the record once the stream has ended. The job checks again just before its download, in case the record was re-read while it waited. A video whose audio or container is already on disk still transcribes, since nothing is downloaded. A finished stream (`was_live`) downloads as before (`common/lib/liveNow.ts`).
- **The X run console: several X channels' posts fetched as one job that stops when the cookies go stale.** On 8 and 9 Nov an agent ran X fetch-posts by hand, one channel after another, watching the cookie jar age and putting off the rest once it went stale. `/review`'s new **X run** section lists the X posts channels in priority order (focus, tier, rank; paused ones unticked), with a tick and up/down buttons for each, and **Start X run** queues ONE `x-run` job on X's queue. The job fetches each channel in turn (new posts only, at most 200 each), waits X's queue gap (`pacing.jobGapSeconds.twitter`) between two channels, and checks the cookie jar again before EACH one. Once the jar is past `social.x.maxCookieAgeMinutes`, or the X alert is up, the run stops and the rest are **deferred until the next refresh**. It never refreshes cookies itself. The console shows each channel's state (queued, running, done with its new posts, deferred, failed), "N done, M deferred until the next refresh", the jar's age counted down to the limit, and the wait before the next channel. **Resume** runs the deferred channels after the operator presses Refresh cookies on /settings. A Retry of the job, and "Re-run stopped jobs", do the same. A restart does not resume a run: an interrupted run ends deferred. `pnpm ops x-run {"channels": [...]}` / `{"resume": "<run id>"}` and `pnpm ops get x-run` do the same from a terminal.
diff --git a/editor/app/api/ops/channel-rank/route.test.ts b/editor/app/api/ops/channel-rank/route.test.ts
@@ -0,0 +1,64 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { setupOpsCorpus, callPost } from "../_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/channel-rank/route.test.ts"
+//
+// `channel-rank`: one channel placed in the order through the deck's one
+// writer. Every REFUSAL here is answered before anything is written; the
+// writes end in revalidatePath, which a bare tsx process has no request store
+// for, so they are driven over HTTP in e2e/ops-api.spec.ts.
+
+const corpus = await setupOpsCorpus(null);
+for (const slug of ["alpha", "beta", "gamma", "off"]) {
+ await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` });
+}
+await corpus.writeSettings({
+ channelPriority: {
+ focus: { kind: "none" },
+ channels: { alpha: { tier: "normal", rank: 0 }, beta: { tier: "normal", rank: 1 }, off: { tier: "paused" } },
+ },
+});
+const { POST } = await import("./route");
+test.after(() => corpus.cleanup());
+const settingsText = () => readFile(corpus.settingsFile, "utf8");
+
+test("exactly one placement, of the right type; unknown keys refused", async () => {
+ const before = await settingsText();
+ for (const [body, re] of [
+ [{ slug: "alpha" }, /give exactly one placement/],
+ [{ slug: "alpha", top: true, bottom: true }, /give exactly one placement .*; got "top", "bottom"/],
+ [{ slug: "alpha", rank: -1 }, /"rank" must be a whole number, 0 or more/],
+ [{ slug: "alpha", rank: 1.5 }, /"rank" must be a whole number/],
+ [{ slug: "alpha", rank: "2" }, /"rank" must be a whole number/],
+ [{ slug: "alpha", top: false }, /"top" must be true/],
+ [{ slug: "alpha", before: "../x" }, /not a valid channel slug/],
+ [{ slug: "alpha", first: true }, /first/],
+ ] as const) {
+ const r = await callPost(POST, body);
+ assert.equal(r.status, 400, JSON.stringify(body));
+ assert.match(String(r.body.error), re, JSON.stringify(r.body));
+ }
+ assert.equal(await settingsText(), before, "nothing written");
+});
+
+test("an unknown channel is a 404; an unknown anchor, an unranked anchor, a paused-everywhere channel are refused", async () => {
+ const before = await settingsText();
+ const missing = await callPost(POST, { slug: "nope", top: true });
+ assert.equal(missing.status, 404);
+ assert.match(String(missing.body.error), /Channel "nope" not found/);
+ const anchor = await callPost(POST, { slug: "alpha", after: "nope" });
+ assert.equal(anchor.status, 400);
+ assert.match(String(anchor.body.error), /Channel "nope" not found \(the "after" anchor\)/);
+ const unranked = await callPost(POST, { slug: "alpha", before: "gamma" });
+ assert.equal(unranked.status, 400);
+ assert.match(String(unranked.body.error), /"gamma" has no rank, so there is no place before it/);
+ const self = await callPost(POST, { slug: "beta", after: "beta" });
+ assert.match(String(self.body.error), /cannot be placed after itself/);
+ const paused = await callPost(POST, { slug: "off", top: true });
+ assert.equal(paused.status, 400);
+ assert.match(String(paused.body.error), /"off" is paused for every operation/);
+ assert.equal(await settingsText(), before, "nothing written");
+});
diff --git a/editor/app/api/ops/channel-rank/route.ts b/editor/app/api/ops/channel-rank/route.ts
@@ -0,0 +1,85 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ rankOf,
+ rankedOrder,
+ type RankPlacement,
+} from "yt-dlp-transcript-common/lib/channelPriority";
+import { channelExists } from "yt-dlp-transcript-common/controller/channels";
+import { setChannelRankAction } from "../../../channels/actions";
+import { OpsInputError, ops, opsFail, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, rank: <n> | null } | { slug, top: true } | { slug, bottom: true }
+// | { slug, before: <slug> } | { slug, after: <slug> }
+// -> { ok, slug, rank, order: [{slug, rank}, …] }
+//
+// ONE CHANNEL PLACED IN THE ORDER — the rank inside its tier that every lane
+// and the sync scheduler follow (one rank per channel; unranked after every
+// ranked channel, then by slug). Before this only /channels' "Add to top"
+// moved a channel, and it also sets the tier to normal and turns the download
+// lane on. This moves the rank alone, through the deck's one writer
+// (saveChannelPriorityAction), which recompiles the four lane roots in the
+// same write. Every other channel keeps its order: a rank already held is
+// made room for by shifting it and everything below it down one.
+//
+// Exactly one placement. `rank: null` removes the rank. Refused before any
+// write: an unknown channel or anchor, an anchor with no rank (nothing to be
+// next to), a rank that is not a whole number ≥ 0, a channel paused for every
+// operation (it is in no order; its rank would not be kept).
+// The answer is the saved rank and the whole ranked order.
+const PLACEMENTS = ["rank", "top", "bottom", "before", "after"] as const;
+
+export async function POST(request: Request) {
+ return ops(request, ["slug", ...PLACEMENTS], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const given = PLACEMENTS.filter((k) => body[k] !== undefined);
+ if (given.length !== 1) {
+ throw new OpsInputError(
+ `give exactly one placement — "rank" (a number, or null to unrank), "top": true, "bottom": true, ` +
+ `"before": "<slug>" or "after": "<slug>"${given.length ? `; got ${given.map((k) => `"${k}"`).join(", ")}` : ""}`,
+ );
+ }
+ const paths = getPaths();
+ if (!(await channelExists(paths, slug))) {
+ return opsFail(`Channel "${slug}" not found`, 404);
+ }
+ const place = await readPlacement(body, given[0], async (anchor) => {
+ if (!(await channelExists(paths, anchor))) {
+ throw new OpsInputError(`Channel "${anchor}" not found (the "${given[0]}" anchor)`);
+ }
+ });
+ const result = await setChannelRankAction(slug, place);
+ if (result?.error) return opsFail(result.error);
+ const saved = getSettings().channelPriority;
+ return NextResponse.json({ ok: true, slug, rank: rankOf(saved, slug), order: rankedOrder(saved) });
+ });
+}
+
+async function readPlacement(
+ body: Record<string, unknown>,
+ key: (typeof PLACEMENTS)[number],
+ checkAnchor: (slug: string) => Promise<void>,
+): Promise<RankPlacement> {
+ const v = body[key];
+ if (key === "rank") {
+ if (v === null) return { kind: "unrank" };
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 0) {
+ throw new OpsInputError('"rank" must be a whole number, 0 or more (0 = first), or null to remove the rank');
+ }
+ return { kind: "rank", rank: v };
+ }
+ if (key === "top" || key === "bottom") {
+ if (v !== true) throw new OpsInputError(`"${key}" must be true`);
+ return { kind: key };
+ }
+ const anchor = reqSlug(body, key);
+ await checkAnchor(anchor);
+ return { kind: key, slug: anchor };
+}
+
+export function GET() {
+ return NextResponse.json({ ok: false, error: "POST only" }, { status: 405 });
+}
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -53,6 +53,8 @@ import {
isChannelPaused,
clearAutoPause,
isDefaultChannelPriority,
+ placeChannelRank,
+ RankPlacementError,
rankOf,
renameChannelInPriority,
resolveFocusSlugs,
@@ -62,6 +64,7 @@ import {
type ChannelPriority,
type ChannelPriorityEntry,
type PriorityOperation,
+ type RankPlacement,
type SiteChannelIndex,
type StoredChannelTier,
} from "yt-dlp-transcript-common/lib/channelPriority";
@@ -837,6 +840,10 @@ export type ChannelPriorityEdit =
// `paused` channel ranked first is still behind (or absent from) every
// normal one. See prioritizeChannelDownloadAction.
| { kind: "promote"; slug: string }
+ // ONE CHANNEL MOVED IN THE ORDER (`pnpm ops channel-rank`): its rank alone,
+ // every other channel's order kept — placeChannelRank in the model. No tier,
+ // override, focus or lane changes, unlike promote.
+ | { kind: "rank"; slug: string; place: RankPlacement }
// NOT AN EDIT: the channel POPULATION changed (a channel was created or
// deleted), so the four trees have to be re-derived from an unchanged
// document. Never seeds — see the writer.
@@ -868,6 +875,7 @@ function applyPriorityEdit(
return renameChannelInPriority(model, edit.from, edit.to);
}
if (edit.kind === "focus") return { ...model, focus: edit.focus };
+ if (edit.kind === "rank") return placeChannelRank(model, edit.slug, edit.place);
if (edit.kind === "promote") {
const slug = edit.slug.trim();
if (!slug) return model;
@@ -992,7 +1000,29 @@ export async function saveChannelPriorityAction(
settings.autoQueue,
)
: stored;
- const next = sanitizeChannelPriority(applyPriorityEdit(base, edit));
+ let next: ChannelPriority;
+ try {
+ next = sanitizeChannelPriority(applyPriorityEdit(base, edit));
+ } catch (e) {
+ // A placement the document cannot carry out (next to an unranked channel,
+ // a rank that is not one) is the caller's to fix, said before any write.
+ if (e instanceof RankPlacementError) return { error: e.message };
+ throw e;
+ }
+ // A rank the sanitizer drops: a channel paused for every operation is in no
+ // group anywhere, so it orders nothing and its rank is not kept. Said, not
+ // saved as a silent no-op.
+ if (
+ edit.kind === "rank" &&
+ edit.place.kind !== "unrank" &&
+ next.channels[edit.slug.trim()]?.rank === undefined
+ ) {
+ return {
+ error:
+ `"${edit.slug.trim()}" is paused for every operation, so it is in no order a rank could place it in — ` +
+ `give it a tier first (pnpm ops channel-priority), then rank it.`,
+ };
+ }
// WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the
// question are different corpora.
//
@@ -1116,6 +1146,18 @@ export async function prioritizeChannelDownloadPriorityAction(
);
}
+// Place one channel in the order (`pnpm ops channel-rank`): rank n, top,
+// bottom, before or after another ranked channel, or unranked. Through the one
+// writer, so the four lane roots are recompiled in the same write.
+export async function setChannelRankAction(
+ slug: string,
+ place: RankPlacement,
+): Promise<ActionResult> {
+ const trimmed = (slug ?? "").trim();
+ if (!trimmed) return { error: "No channel slug supplied." };
+ return saveChannelPriorityAction({ kind: "rank", slug: trimmed, place });
+}
+
export async function endFocusAction(): Promise<ActionResult> {
return saveChannelPriorityAction({ kind: "focus", focus: { kind: "none" } });
}
diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts
@@ -340,6 +340,64 @@ test("channel-priority sets and ends the focus", async ({ request }) => {
await expect.poll(async () => (await focusOf())?.kind ?? "none").toBe("none");
});
+// channel-rank (lane editor-gaps): one channel moved in the order through the
+// deck's one writer — the rank alone; the tier and the lanes untouched, and
+// the four lane roots recompiled in the same write.
+test("channel-rank places a channel top, after another, by rank and unranked", async ({ request }) => {
+ await resetData("empty");
+ for (const slug of ["rank-a", "rank-b", "rank-c"]) await writeChannelConfig(slug, {});
+ await writeSettings({
+ minFreeDiskGB: 0,
+ channelPriority: {
+ focus: { kind: "none" },
+ channels: {
+ "rank-a": { tier: "normal", rank: 0 },
+ "rank-b": { tier: "low", rank: 1 },
+ "rank-c": { tier: "normal", rank: 2 },
+ },
+ },
+ });
+ type Prio = { channelPriority?: { channels?: Record<string, { tier: string; rank?: number }> } };
+ const ranks = async () => {
+ const c = (await readJson<Prio>(testPaths().settingsFile)).channelPriority?.channels ?? {};
+ return Object.fromEntries(Object.entries(c).map(([s, e]) => [s, e.rank ?? null]));
+ };
+
+ const top = await ops(request, "channel-rank", { slug: "rank-c", top: true });
+ expect(top.status, JSON.stringify(top.body)).toBe(200);
+ expect(top.body).toMatchObject({
+ ok: true,
+ slug: "rank-c",
+ rank: 0,
+ order: [
+ { slug: "rank-c", rank: 0 },
+ { slug: "rank-a", rank: 1 },
+ { slug: "rank-b", rank: 2 },
+ ],
+ });
+ await expect.poll(ranks).toEqual({ "rank-a": 1, "rank-b": 2, "rank-c": 0 });
+ const tiers = (await readJson<Prio>(testPaths().settingsFile)).channelPriority?.channels ?? {};
+ expect(tiers["rank-b"]?.tier).toBe("low");
+
+ const after = await ops(request, "channel-rank", { slug: "rank-b", after: "rank-c" });
+ expect(after.body).toMatchObject({ ok: true, rank: 1 });
+ await expect.poll(ranks).toEqual({ "rank-a": 2, "rank-b": 1, "rank-c": 0 });
+
+ const unrank = await ops(request, "channel-rank", { slug: "rank-a", rank: null });
+ expect(unrank.body).toMatchObject({ ok: true, slug: "rank-a", rank: null });
+ await expect.poll(ranks).toEqual({ "rank-b": 1, "rank-c": 0 });
+
+ // The compiled download root lists the channels in that order.
+ type Root = { autoQueue?: { download?: { root?: unknown } } };
+ const root = JSON.stringify((await readJson<Root>(testPaths().settingsFile)).autoQueue?.download?.root ?? null);
+ expect(root.indexOf("rank-c")).toBeGreaterThan(-1);
+ expect(root.indexOf("rank-c")).toBeLessThan(root.indexOf("rank-a"));
+
+ const refused = await ops(request, "channel-rank", { slug: "rank-c", before: "rank-a" });
+ expect(refused.status).toBe(400);
+ expect(refused.body.error).toMatch(/"rank-a" has no rank/);
+});
+
test("metadata-scan starts a job, and the job says it is a metadata-scan", async ({
request,
}) => {
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -88,6 +88,9 @@
// pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'
// pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'
// pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'
+// pnpm ops channel-rank --json '{"slug":"x","top":true}'
+// pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'
+// pnpm ops channel-rank --json '{"slug":"x","rank":null}'
// pnpm ops lane --json '{"lane":"download","held":true}'
// pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'
// pnpm ops render-mode --json '{"on":false}'
@@ -373,6 +376,9 @@ export const JOB_VERBS = [
const ACTIONS = [
"channel-priority",
+ // One channel placed in the order the lanes follow ({slug} and one of rank
+ // | top | bottom | before | after), through the deck's one writer.
+ "channel-rank",
"channel-config",
// A site's cited-only channels and its publish policy ({siteId,
// citedChannels?, publishAuto?}), through the site form's own writer.
@@ -1315,6 +1321,16 @@ export function usage() {
' {"kind": "none"}} alone is the deck\'s focus bar: those channels lead',
' every lane (a site focus follows its membership); "none" ends it.',
"",
+ 'channel-rank places one channel in the order every lane and the sync',
+ ' scheduler follow inside a tier (one rank per channel, 0 first; unranked',
+ ' channels come after every ranked one, by slug): {"slug"} and exactly one',
+ ' of "rank": <n> (a rank already held, and every rank below it, shift down',
+ ' one) or null (unranked), "top": true, "bottom": true, "before": "<slug>",',
+ ' "after": "<slug>" (a ranked channel). Only the rank moves — no tier,',
+ ' override or lane changes, unlike /channels\' "Add to top". Refused: an',
+ ' unknown channel, an unranked anchor, a channel paused for every',
+ ' operation. Answers {slug, rank, order: [{slug, rank}, …]}.',
+ "",
'sync lists a channel and downloads what is new, as its Sync button does:',
' {"slug"}. "full": true runs the periodic whole-listing sweep now (else',
' the configured cadence decides); "queueKey" picks another queue. On the',