commit 26578d986efeacb8ab6f32e0d8dee1f5f5b5cc77
parent f407a8231674eb5b662f0fbec17407a3978946a0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 06:16:45 -0500
archives: connect a published archive as a source -- settings.remoteArchives, one resolver for the editor, umtool and the MCP (demo epic D1 item 1)
A published archive (any origin serving /corpus.json) is connected once by its
origin: the editor's /sites "Connected archives" panel (Read it -> Connect),
umtool's Source chip ("Connect an archive...") or `pnpm ops archives
{connect}`. The probe reads corpus.json once and shows its title, totals and
channels; a hub, a cited-only site, a site with no channels or an origin that
does not answer is refused with a sentence. TRANSCRIPT_SITE_URL is the default
archive: listed (fromEnv) and never written.
lib/remoteArchives.ts (pure: shape, origin rule, sanitizer, env default) and
lib/remoteArchives-server.ts (the probe) are the one resolver: umtool's
listSources and the MCP's list_sources list connected archives through
connectedArchives, the editor writes them through controller/remoteArchives.ts
under its one settings writer. The key is `remoteArchives`, not the spec's
`archives`: that key is the page-import sources' (archive.today, release 37).
settings patch refuses it (the archives action owns it). SETTINGS.md,
settings.json.example and COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
24 files changed, 1106 insertions(+), 9 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -131,6 +131,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` |
| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
+| `archives` | archives connects a published archive as a source: {"connect": "<origin>"} reads <origin>/corpus.json once (its title, totals and channels) and saves it in settings.remoteArchives; "dryRun"? answers the probe and writes nothing; an origin connected already writes nothing. A federation hub, a cited-only site, one with no channels or one that does not answer is refused. {"remove": "<id or origin>"} drops one. Create, research and the MCP offer each connected archive; a sweep over it cites it. | `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'` |
| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose pool or cited scope names it is rewritten without it (answered as "sitesUpdated"; a site whose write is refused is a "warnings" line). No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
@@ -295,6 +296,8 @@ get saved-alternates [<slug>] lists every saved video holding two copies:
get sites lists every site: id, title, siteUrl, Pages project, audience,
listed, search, publish policy, channels, citedChannels. (`get publish`
is the status.)
+get archives lists the connected archives: id, origin, title, addedAt;
+ TRANSCRIPT_SITE_URL's, when set and not stored, is listed with fromEnv.
get workers, get auto-queue and get scheduler are /workers, the four lanes
of /operations, and /operations/sync — the payloads those pages poll.
get services is the dashboard's cookie refresh alerts: each service
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -49,6 +49,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`attribution`](#attribution) | object — see below |
| [`archiveOrg`](#archiveorg) | object — see below |
| [`archives`](#archives) | object — see below |
+| [`remoteArchives`](#remotearchives) | `[]` |
| [`publish`](#publish) | object — see below |
| [`reportSchedule`](#reportschedule) | object — see below |
| [`seeder`](#seeder) | object — see below |
@@ -899,6 +900,27 @@ Default:
}
```
+## `remoteArchives`
+
+The PUBLISHED ARCHIVES this machine reads as sources (demo epic D1, lib/remoteArchives.ts): each a site serving `/corpus.json`, connected once by its origin (the editor's /sites → Connect an archive, umtool's Source chip, or `pnpm ops archives`). Create, research and the MCP offer each one; a sweep over one cites that origin; a clip window cited from one registers a REMOTE-ONLY channel (CHANNEL.md `remoteOnly`) to fetch it. TRANSCRIPT_SITE_URL, when set and not listed here, is offered too without being written. Empty = none. See RemoteArchive.
+
+#### `remoteArchives[]`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `id` | A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is free, else one made from its host. What `pnpm ops archives` removes by. |
+| `origin` | The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is served. Sweeps over it cite it (`remote:<origin>`), whatever `generation.citationOrigin` says. |
+| `title` | The archive's `site.title`, as its corpus.json said when it was connected. |
+| `addedAt` | When it was connected (ISO-8601). |
+
+Default:
+
+```json
+[]
+```
+
## `publish`
The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.
diff --git a/common/controller/remoteArchives.test.ts b/common/controller/remoteArchives.test.ts
@@ -0,0 +1,73 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectRemoteArchive, removeRemoteArchive, RemoteArchiveError, type RemoteArchiveDeps } from "./remoteArchives";
+import type { RemoteArchive } from "../lib/remoteArchives";
+import type { FetchLike } from "../lib/remoteArchives-server";
+
+const CORPUS = {
+ spec: 6,
+ kind: "site",
+ generatedAt: "2026-11-08T00:00:00.000Z",
+ site: { id: "stubalyzer", title: "Stubalyzer" },
+ totals: { channels: 1, videos: 3 },
+ channels: [{ slug: "alpha", name: "Alpha", videoCount: 3 }],
+};
+
+function world(initial: RemoteArchive[] = [], env: Record<string, string> = {}) {
+ let stored: unknown = initial;
+ const writes: RemoteArchive[][] = [];
+ const asked: string[] = [];
+ const fetch: FetchLike = async (url) => {
+ asked.push(url);
+ return new Response(JSON.stringify(CORPUS), { status: 200 });
+ };
+ const deps: RemoteArchiveDeps = {
+ stored: () => stored,
+ save: async (next) => {
+ writes.push(next);
+ stored = next;
+ },
+ fetch,
+ now: () => new Date("2026-11-11T12:00:00Z"),
+ env,
+ };
+ return { deps, writes, asked, stored: () => stored };
+}
+
+test("connect: probed once, saved with the archive's own id and title", async () => {
+ const w = world();
+ const r = await connectRemoteArchive({ origin: "https://stub.test/" }, w.deps);
+ assert.deepEqual(w.asked, ["https://stub.test/corpus.json"]);
+ assert.equal(r.already, false);
+ assert.deepEqual(w.writes, [[{ id: "stubalyzer", origin: "https://stub.test", title: "Stubalyzer", addedAt: "2026-11-11T12:00:00.000Z" }]]);
+ // Again: nothing written, it says so.
+ const again = await connectRemoteArchive({ origin: "stub.test" }, w.deps);
+ assert.equal(again.already, true);
+ assert.equal(w.writes.length, 1);
+});
+
+test("a dry run reads and writes nothing", async () => {
+ const w = world();
+ const r = await connectRemoteArchive({ origin: "https://stub.test", dryRun: true }, w.deps);
+ assert.equal(r.already, null);
+ assert.equal(r.probe.totals.videos, 3);
+ assert.equal(w.writes.length, 0);
+});
+
+test("the environment's archive can be connected (stored) but not removed", async () => {
+ const w = world([], { TRANSCRIPT_SITE_URL: "https://stub.test" });
+ await assert.rejects(removeRemoteArchive("https://stub.test", w.deps), (e: unknown) => e instanceof RemoteArchiveError && /TRANSCRIPT_SITE_URL/.test((e as Error).message));
+ const r = await connectRemoteArchive({ origin: "https://stub.test" }, w.deps);
+ assert.equal(r.already, false);
+ assert.equal(w.writes.length, 1);
+});
+
+test("remove by id or by origin; an unknown one is refused, naming what is connected", async () => {
+ const a: RemoteArchive = { id: "a", origin: "https://a.test", title: "A", addedAt: "2026-11-11T00:00:00.000Z" };
+ const b: RemoteArchive = { id: "b", origin: "https://b.test", title: "B", addedAt: "2026-11-11T00:00:00.000Z" };
+ const w = world([a, b]);
+ assert.deepEqual(await removeRemoteArchive("a", w.deps), a);
+ assert.deepEqual(await removeRemoteArchive("https://b.test/", w.deps), b);
+ assert.deepEqual(w.stored(), []);
+ await assert.rejects(removeRemoteArchive("zzz", w.deps), /no connected archive "zzz" — connected: none/);
+});
diff --git a/common/controller/remoteArchives.ts b/common/controller/remoteArchives.ts
@@ -0,0 +1,65 @@
+// CONNECT AN ARCHIVE (demo epic D1, item 1): the one place
+// settings.remoteArchives is changed. The editor's ops action
+// (`pnpm ops archives`) and its /sites form call these; umtool's Source chip
+// asks the editor's action — so every connect is probed the same way and
+// written by the editor's one settings writer.
+//
+// connect probe `<origin>/corpus.json` (lib/remoteArchives-server.ts) and,
+// unless `dryRun`, add { id, origin, title, addedAt }. An origin
+// already connected answers what it is and writes nothing.
+// remove drop the entry by id (or origin). The TRANSCRIPT_SITE_URL entry
+// is not stored, so it cannot be removed here: it goes with the
+// variable.
+
+import { connectedArchives, findConnectedArchive, freeArchiveId, sanitizeRemoteArchives, archiveOriginOf, type ConnectedArchive, type RemoteArchive } from "../lib/remoteArchives";
+import { probeArchive, type ArchiveProbe, type FetchLike } from "../lib/remoteArchives-server";
+
+export type RemoteArchiveDeps = {
+ // The stored list (settings.remoteArchives).
+ stored: () => unknown;
+ // Write the whole list (the editor's saveSettings({ remoteArchives })).
+ save: (next: RemoteArchive[]) => Promise<void>;
+ fetch?: FetchLike;
+ now?: () => Date;
+ env?: Record<string, string | undefined>;
+};
+
+export type ConnectResult = {
+ probe: ArchiveProbe;
+ archive: ConnectedArchive;
+ // true: it was connected already (nothing written); false: added now; null: a dry run.
+ already: boolean | null;
+};
+
+export async function connectRemoteArchive(o: { origin: string; dryRun?: boolean }, deps: RemoteArchiveDeps): Promise<ConnectResult> {
+ const probe = await probeArchive(o.origin, { fetch: deps.fetch });
+ const list = connectedArchives(deps.stored(), deps.env);
+ const have = findConnectedArchive(list, probe.origin);
+ if (have && !have.fromEnv) return { probe, archive: have, already: true };
+ const stored = sanitizeRemoteArchives(deps.stored());
+ const archive: RemoteArchive = {
+ id: freeArchiveId(probe.origin, stored.map((a) => a.id), probe.siteId),
+ origin: probe.origin,
+ title: probe.title,
+ addedAt: (deps.now?.() ?? new Date()).toISOString(),
+ };
+ if (o.dryRun) return { probe, archive, already: null };
+ await deps.save([...stored, archive]);
+ return { probe, archive, already: false };
+}
+
+export class RemoteArchiveError extends Error {}
+
+/** Remove a stored archive by id or origin; answers the removed entry. */
+export async function removeRemoteArchive(which: string, deps: RemoteArchiveDeps): Promise<RemoteArchive> {
+ const stored = sanitizeRemoteArchives(deps.stored());
+ const origin = archiveOriginOf(which);
+ const hit = stored.find((a) => a.id === which || (origin !== null && a.origin === origin));
+ if (!hit) {
+ const env = connectedArchives(deps.stored(), deps.env).find((a) => a.fromEnv && (a.id === which || a.origin === origin));
+ if (env) throw new RemoteArchiveError(`${env.origin} comes from TRANSCRIPT_SITE_URL, not settings.json — unset the variable to stop offering it`);
+ throw new RemoteArchiveError(`no connected archive "${which}" — connected: ${stored.map((a) => a.id).join(", ") || "none"}`);
+ }
+ await deps.save(stored.filter((a) => a !== hit));
+ return hit;
+}
diff --git a/common/lib/remoteArchives-server.ts b/common/lib/remoteArchives-server.ts
@@ -0,0 +1,118 @@
+// THE REMOTE-ARCHIVE RESOLVER's network half (./remoteArchives.ts is the pure
+// one): what a published archive says about itself, read from its
+// `/corpus.json` — the title, the totals and the channels the Connect form
+// shows before anything is saved.
+//
+// One request per probe, sequential, never in a loop. The fetch is injectable
+// (every test passes a fake; no test calls a real site).
+
+import { archiveOriginOf } from "./remoteArchives";
+
+export type FetchLike = (url: string, init?: { signal?: AbortSignal; headers?: Record<string, string> }) => Promise<Response>;
+
+export type ArchiveProbeChannel = {
+ slug: string;
+ name: string;
+ videoCount: number | null;
+ // Spec 6 (corpus.json carries them); absent from an older archive's entry.
+ platform?: string;
+ url?: string;
+};
+
+export type ArchiveProbe = {
+ origin: string;
+ // corpus.json's own: site.id, site.title, spec, generatedAt.
+ siteId: string | null;
+ title: string;
+ description: string;
+ spec: number | null;
+ generatedAt: string | null;
+ totals: { channels: number; videos: number };
+ channels: ArchiveProbeChannel[];
+};
+
+export class ArchiveProbeError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ this.name = "ArchiveProbeError";
+ }
+}
+
+const PROBE_TIMEOUT_MS = 15_000;
+
+const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
+const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
+
+/**
+ * Read `<origin>/corpus.json` and say what the archive is. Refused, with a
+ * sentence: not an origin, unreachable, not JSON, a federation hub (connect
+ * one of its sites), a cited-only site (it publishes reports, no corpus), or
+ * a site listing no channels.
+ */
+export async function probeArchive(rawOrigin: string, opts: { fetch?: FetchLike; timeoutMs?: number } = {}): Promise<ArchiveProbe> {
+ const origin = archiveOriginOf(rawOrigin);
+ if (!origin) throw new ArchiveProbeError(`"${rawOrigin}" is not an archive's address — type its origin, e.g. https://jeralyzer.pages.dev`);
+ const doFetch = opts.fetch ?? (fetch as unknown as FetchLike);
+ const url = `${origin}/corpus.json`;
+ let res: Response;
+ try {
+ res = await doFetch(url, { signal: AbortSignal.timeout(opts.timeoutMs ?? PROBE_TIMEOUT_MS), headers: { accept: "application/json" } });
+ } catch (e) {
+ throw new ArchiveProbeError(`${url} did not answer: ${(e as Error).message}`, 502);
+ }
+ if (!res.ok) throw new ArchiveProbeError(`${url} answered HTTP ${res.status} — is ${origin} a published archive?`, 502);
+ let j: Record<string, unknown>;
+ try {
+ j = (await res.json()) as Record<string, unknown>;
+ } catch {
+ throw new ArchiveProbeError(`${url} is not JSON — ${origin} does not serve an archive's contract`, 502);
+ }
+ if (!j || typeof j !== "object" || Array.isArray(j)) throw new ArchiveProbeError(`${url} is not an archive's corpus.json`, 502);
+ if (j.kind === "hub" || Array.isArray(j.sites)) {
+ const sites = Array.isArray(j.sites) ? (j.sites as Record<string, unknown>[]) : [];
+ const names = sites
+ .map((s) => str(s?.url))
+ .filter((u): u is string => !!u)
+ .slice(0, 6);
+ throw new ArchiveProbeError(
+ `${origin} is a federation hub of ${sites.length} site(s), not one archive — connect one of its sites${names.length ? `: ${names.join(", ")}` : ""}`,
+ );
+ }
+ const site = (j.site && typeof j.site === "object" ? j.site : {}) as Record<string, unknown>;
+ if (site.scope === "cited") {
+ throw new ArchiveProbeError(`${origin} publishes only its reports and the moments they cite — it has no corpus to search`);
+ }
+ const rawChannels = Array.isArray(j.channels) ? (j.channels as Record<string, unknown>[]) : [];
+ const channels: ArchiveProbeChannel[] = [];
+ for (const c of rawChannels) {
+ const slug = str(c?.slug);
+ if (!slug) continue;
+ const platform = str(c.platform);
+ const curl = str(c.url);
+ channels.push({
+ slug,
+ name: str(c.name) ?? slug,
+ videoCount: num(c.videoCount),
+ ...(platform ? { platform } : {}),
+ ...(curl ? { url: curl } : {}),
+ });
+ }
+ if (channels.length === 0) throw new ArchiveProbeError(`${origin}'s corpus.json lists no channels — there is nothing to search`);
+ const totals = (j.totals && typeof j.totals === "object" ? j.totals : {}) as Record<string, unknown>;
+ return {
+ origin,
+ siteId: str(site.id),
+ title: str(site.title) ?? origin.replace(/^https?:\/\//, ""),
+ description: str(site.description) ?? "",
+ spec: num(j.spec),
+ generatedAt: str(j.generatedAt),
+ totals: {
+ channels: num(totals.channels) ?? channels.length,
+ videos: num(totals.videos) ?? channels.reduce((n, c) => n + (c.videoCount ?? 0), 0),
+ },
+ channels,
+ };
+}
diff --git a/common/lib/remoteArchives.test.ts b/common/lib/remoteArchives.test.ts
@@ -0,0 +1,133 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ archiveHandle,
+ archiveOriginOf,
+ connectedArchives,
+ findConnectedArchive,
+ freeArchiveId,
+ originOfHandle,
+ sanitizeRemoteArchives,
+} from "./remoteArchives";
+import { ArchiveProbeError, probeArchive, type FetchLike } from "./remoteArchives-server";
+import { defaults } from "./settingsSchema";
+
+test("an archive origin is normalized: https assumed, trailing slash and /corpus.json dropped", () => {
+ assert.equal(archiveOriginOf("jeralyzer.pages.dev"), "https://jeralyzer.pages.dev");
+ assert.equal(archiveOriginOf(" https://Jeralyzer.pages.dev/ "), "https://jeralyzer.pages.dev");
+ assert.equal(archiveOriginOf("https://x.test/corpus.json"), "https://x.test");
+ assert.equal(archiveOriginOf("http://127.0.0.1:4100/arch/"), "http://127.0.0.1:4100/arch");
+ for (const bad of ["", "ftp://x.test", "https://u:p@x.test", "https://x.test/?q=1", "https://x.test/#a", 7, null]) {
+ assert.equal(archiveOriginOf(bad), null, String(bad));
+ }
+});
+
+test("a handle names its archive and back", () => {
+ assert.equal(archiveHandle("https://a.test"), "remote:https://a.test");
+ assert.equal(originOfHandle("remote:https://a.test/"), "https://a.test");
+ assert.equal(originOfHandle("local:/x"), null);
+ assert.equal(originOfHandle(undefined), null);
+});
+
+test("ids: the archive's own site id when free, else from the host, made unique", () => {
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], "jeralyzer"), "jeralyzer");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", ["jeralyzer"], "jeralyzer"), "jeralyzer-2");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], null), "jeralyzer-pages-dev");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], "Not A Slug"), "jeralyzer-pages-dev");
+});
+
+test("the stored list is sanitized: bad entries and later duplicates dropped", () => {
+ const out = sanitizeRemoteArchives([
+ { id: "a", origin: "https://a.test/", title: "A", addedAt: "2026-11-11T00:00:00Z" },
+ { id: "b", origin: "https://a.test" }, // same origin
+ { id: "a", origin: "https://other.test" }, // same id
+ { id: "BAD", origin: "https://c.test" },
+ { id: "d", origin: "not a url at all ::" },
+ "junk",
+ { id: "e", origin: "https://e.test" },
+ ]);
+ assert.deepEqual(out, [
+ { id: "a", origin: "https://a.test", title: "A", addedAt: "2026-11-11T00:00:00.000Z" },
+ { id: "e", origin: "https://e.test", title: "e.test", addedAt: "1970-01-01T00:00:00.000Z" },
+ ]);
+ assert.deepEqual(sanitizeRemoteArchives({ not: "an array" }), []);
+ assert.deepEqual(defaults().remoteArchives, []);
+});
+
+test("TRANSCRIPT_SITE_URL is the default archive, listed but never stored, and not twice", () => {
+ const none = connectedArchives([], {});
+ assert.deepEqual(none, []);
+ const env = connectedArchives([], { TRANSCRIPT_SITE_URL: "https://jeralyzer.pages.dev/" });
+ assert.equal(env.length, 1);
+ assert.equal(env[0].origin, "https://jeralyzer.pages.dev");
+ assert.equal(env[0].fromEnv, true);
+ const stored = connectedArchives([{ id: "jeralyzer", origin: "https://jeralyzer.pages.dev", title: "Jeralyzer", addedAt: "2026-11-11T00:00:00Z" }], {
+ TRANSCRIPT_SITE_URL: "https://jeralyzer.pages.dev",
+ });
+ assert.equal(stored.length, 1);
+ assert.equal(stored[0].fromEnv, undefined);
+ assert.equal(findConnectedArchive(stored, "jeralyzer.pages.dev/")?.id, "jeralyzer");
+ assert.equal(findConnectedArchive(stored, "https://elsewhere.test"), null);
+});
+
+// ─── probeArchive, against a fake fetch only ───
+
+const respond = (body: unknown, status = 200): Response =>
+ new Response(typeof body === "string" ? body : JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+function fakeFetch(map: Record<string, () => Response>): FetchLike & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ const r = map[url];
+ if (!r) return respond({ error: "nope" }, 404);
+ return r();
+ }) as FetchLike & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+const CORPUS = {
+ spec: 6,
+ kind: "site",
+ generatedAt: "2026-11-08T08:26:37.854Z",
+ site: { id: "stubalyzer", title: "Stubalyzer", description: "A stub", url: "https://stub.test" },
+ totals: { channels: 2, videos: 30 },
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 20, platform: "youtube", url: "https://www.youtube.com/@alpha", manifests: {} },
+ { slug: "beta", name: "Beta", videoCount: 10, manifests: {} },
+ ],
+};
+
+test("a probe reads corpus.json once and says what the archive holds", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond(CORPUS) });
+ const p = await probeArchive("stub.test/", { fetch: f });
+ assert.deepEqual(f.asked, ["https://stub.test/corpus.json"]);
+ assert.equal(p.origin, "https://stub.test");
+ assert.equal(p.siteId, "stubalyzer");
+ assert.equal(p.title, "Stubalyzer");
+ assert.equal(p.spec, 6);
+ assert.deepEqual(p.totals, { channels: 2, videos: 30 });
+ assert.deepEqual(p.channels, [
+ { slug: "alpha", name: "Alpha", videoCount: 20, platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ { slug: "beta", name: "Beta", videoCount: 10 },
+ ]);
+});
+
+test("a probe refuses what is not one searchable archive, with a sentence", async () => {
+ const cases: [string, () => Response, RegExp][] = [
+ ["https://a.test/corpus.json", () => respond("<html>", 200), /is not JSON/],
+ ["https://b.test/corpus.json", () => respond({}, 500), /answered HTTP 500/],
+ ["https://c.test/corpus.json", () => respond({ kind: "hub", sites: [{ url: "https://m1.test" }] }), /federation hub of 1 site.*https:\/\/m1\.test/],
+ ["https://d.test/corpus.json", () => respond({ ...CORPUS, site: { scope: "cited" }, channels: [] }), /publishes only its reports/],
+ ["https://e.test/corpus.json", () => respond({ ...CORPUS, channels: [] }), /lists no channels/],
+ ];
+ for (const [url, r, re] of cases) {
+ await assert.rejects(probeArchive(url.replace("/corpus.json", ""), { fetch: fakeFetch({ [url]: r }) }), (e: unknown) => e instanceof ArchiveProbeError && re.test((e as Error).message));
+ }
+ await assert.rejects(probeArchive("ftp://x", { fetch: fakeFetch({}) }), /not an archive's address/);
+ const down = (async () => {
+ throw new Error("ECONNREFUSED");
+ }) as FetchLike;
+ await assert.rejects(probeArchive("https://f.test", { fetch: down }), /did not answer: ECONNREFUSED/);
+});
diff --git a/common/lib/remoteArchives.ts b/common/lib/remoteArchives.ts
@@ -0,0 +1,176 @@
+// settings.remoteArchives — the PUBLISHED ARCHIVES this machine reads as
+// sources (demo epic D1: "a public archive is a first-class source").
+//
+// A published archive is any origin serving the machine contract at
+// `/corpus.json` (common/lib/corpus.ts): jeralyzer.pages.dev, or a friend's.
+// Connecting one is the operator typing its origin once; from then on the
+// editor's Create form, umtool's Source chip and the MCP all offer it, its
+// sweeps cite it, and its clip windows are fetched for its channels — with no
+// local corpus and no site.json made by hand.
+//
+// THE ONE RESOLVER. This module is the pure half (the shape, the sanitizer, the
+// origin rule, the env default); remoteArchives-server.ts reads corpus.json and
+// a channel's facts over HTTP. The editor (settings + its ops action), umtool's
+// source picker (umtool/lib/research/sources.ts) and the MCP's list_sources all
+// list archives through `connectedArchives`, so the three never disagree about
+// what is connected.
+//
+// NOT `settings.archives`: that key was taken first, by the page-import sources
+// (archive.today, release 37 lane F — lib/archives/settings.ts).
+//
+// Pure, browser-safe: no node:* import.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type RemoteArchive = {
+ // A slug, unique among the connected archives: the archive's own site id
+ // when its corpus.json names one, else made from its host.
+ id: string;
+ // The archive's origin, normalized (archiveOriginOf): http(s), no trailing
+ // slash, no query or fragment. `<origin>/corpus.json` is its contract.
+ origin: string;
+ // What its corpus.json calls it (site.title) when it was connected.
+ title: string;
+ // When it was connected, ISO-8601.
+ addedAt: string;
+};
+
+// A connected archive as the pickers list it: the stored ones, then the one the
+// environment names (TRANSCRIPT_SITE_URL) when no stored entry has its origin.
+export type ConnectedArchive = RemoteArchive & {
+ // From TRANSCRIPT_SITE_URL, not settings.json: listed, never written, and
+ // gone when the variable is.
+ fromEnv?: true;
+};
+
+export const REMOTE_ARCHIVE_FIELD_DOCS: FieldDocs<RemoteArchive> = {
+ id:
+ "A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is " +
+ "free, else one made from its host. What `pnpm ops archives` removes by.",
+ origin:
+ "The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is " +
+ "served. Sweeps over it cite it (`remote:<origin>`), whatever `generation.citationOrigin` says.",
+ title: "The archive's `site.title`, as its corpus.json said when it was connected.",
+ addedAt: "When it was connected (ISO-8601).",
+};
+
+const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+/** Whether `v` is an archive id (a lowercase slug, at most 64 characters). */
+export function isArchiveId(v: unknown): v is string {
+ return typeof v === "string" && ID_RE.test(v);
+}
+
+/**
+ * An archive origin, normalized — `https://host[/path]` with no trailing
+ * slash — or null when `v` is not one: not http(s), carries credentials, a
+ * query or a fragment, or does not parse. A path is kept (an archive may be
+ * served under one); `/corpus.json` typed on the end is taken off.
+ */
+export function archiveOriginOf(v: unknown): string | null {
+ if (typeof v !== "string") return null;
+ let s = v.trim();
+ if (!s) return null;
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `https://${s}`;
+ let u: URL;
+ try {
+ u = new URL(s);
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (u.username || u.password || u.search || u.hash || !u.hostname) return null;
+ const p = u.pathname.replace(/\/corpus\.json$/i, "").replace(/\/+$/, "");
+ return `${u.protocol}//${u.host}${p}`;
+}
+
+/** The source handle a sweep over an archive names (mcp/src/sourceRegistry.ts). */
+export function archiveHandle(origin: string): string {
+ return `remote:${origin}`;
+}
+
+/** The origin a `remote:<origin>` handle names, normalized, or null for any other handle. */
+export function originOfHandle(handle: string | null | undefined): string | null {
+ const m = /^remote:(.+)$/s.exec(handle?.trim() ?? "");
+ return m ? archiveOriginOf(m[1]) : null;
+}
+
+/** A slug for an archive from its host (and path): `jeralyzer.pages.dev` → `jeralyzer-pages-dev`. */
+export function archiveIdFromOrigin(origin: string): string {
+ const bare = origin.replace(/^https?:\/\//, "").toLowerCase();
+ const slug = bare.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, "");
+ return slug && ID_RE.test(slug) ? slug : "archive";
+}
+
+/**
+ * The id a newly connected archive gets: `preferred` (its corpus.json's site
+ * id) when that is a free slug, else one from its origin, made unique with a
+ * numeric suffix.
+ */
+export function freeArchiveId(origin: string, taken: Iterable<string>, preferred?: string | null): string {
+ const used = new Set(taken);
+ const base = preferred && ID_RE.test(preferred) ? preferred : archiveIdFromOrigin(origin);
+ if (!used.has(base)) return base;
+ for (let n = 2; ; n++) {
+ const id = `${base.slice(0, 60)}-${n}`;
+ if (!used.has(id)) return id;
+ }
+}
+
+/**
+ * settings.json's `remoteArchives`, sanitized: an array of entries each with a
+ * valid id and origin; a later duplicate (same origin or id) is dropped; a
+ * missing title becomes the origin's host, a missing date the epoch. Total over
+ * `unknown` (the settings reader never throws).
+ */
+export function sanitizeRemoteArchives(v: unknown): RemoteArchive[] {
+ if (!Array.isArray(v)) return [];
+ const out: RemoteArchive[] = [];
+ const ids = new Set<string>();
+ const origins = new Set<string>();
+ for (const raw of v) {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
+ const r = raw as Record<string, unknown>;
+ const origin = archiveOriginOf(r.origin);
+ if (!origin || origins.has(origin)) continue;
+ const id = isArchiveId(r.id) ? r.id : null;
+ if (!id || ids.has(id)) continue;
+ const title = typeof r.title === "string" && r.title.trim() ? r.title.trim().slice(0, 200) : origin.replace(/^https?:\/\//, "");
+ const addedAt =
+ typeof r.addedAt === "string" && !Number.isNaN(Date.parse(r.addedAt)) ? new Date(r.addedAt).toISOString() : new Date(0).toISOString();
+ ids.add(id);
+ origins.add(origin);
+ out.push({ id, origin, title, addedAt });
+ }
+ return out;
+}
+
+type Env = Record<string, string | undefined>;
+
+/**
+ * Every connected archive, as the pickers list them: the stored ones in order,
+ * then — when it names an origin no stored entry has — TRANSCRIPT_SITE_URL's
+ * (the MCP's own remote, AGENTS.md "Working this repo with no local corpus"),
+ * marked `fromEnv`. That is the default a fresh clone gets: one archive, from
+ * the variable it was told to set.
+ */
+export function connectedArchives(stored: unknown, env: Env = typeof process !== "undefined" ? (process.env as Env) : {}): ConnectedArchive[] {
+ const list: ConnectedArchive[] = sanitizeRemoteArchives(stored);
+ const fromEnv = archiveOriginOf(env.TRANSCRIPT_SITE_URL);
+ if (fromEnv && !list.some((a) => a.origin === fromEnv)) {
+ list.push({
+ id: freeArchiveId(fromEnv, list.map((a) => a.id)),
+ origin: fromEnv,
+ title: fromEnv.replace(/^https?:\/\//, ""),
+ addedAt: new Date(0).toISOString(),
+ fromEnv: true,
+ });
+ }
+ return list;
+}
+
+/** The connected archive at `origin` (normalized first), or null. */
+export function findConnectedArchive(list: readonly ConnectedArchive[], origin: string | null | undefined): ConnectedArchive | null {
+ const want = archiveOriginOf(origin);
+ return want ? (list.find((a) => a.origin === want) ?? null) : null;
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -46,6 +46,7 @@ import {
GENERATION_VERDICT_BAR_FIELD_DOCS,
GENERATION_VERDICT_WINDOW_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
+ REMOTE_ARCHIVE_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
XENFORO_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -216,6 +217,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS },
],
socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }],
+ remoteArchives: [{ path: "remoteArchives[]", docs: REMOTE_ARCHIVE_FIELD_DOCS }],
savedVideoBackup: [
{
path: "savedVideoBackup",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -33,6 +33,7 @@ import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
import type { TtsSettings } from "./ttsSettings";
import type { ArchivesSettings } from "./archives/settings";
+import type { RemoteArchive } from "./remoteArchives";
import type { ClipsSettings } from "./clipSettings";
import type { JobsSettings } from "./jobsSettings";
import type { ServiceCookiesSettings } from "./serviceCookieSettings";
@@ -114,6 +115,8 @@ type PreSchemaSiteSettings = {
// How archive.org files are fetched: BitTorrent with seeding, else direct.
archiveOrg: ArchiveOrgFetchSettings;
archives: ArchivesSettings;
+ // The connected published archives (demo epic D1).
+ remoteArchives: RemoteArchive[];
// The publish lane (release 18).
publish: PublishSettings;
// The recurring reports' lane (umtool R5).
@@ -138,7 +141,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 46 fields, in file order", () => {
+test("SiteSettings keeps its 47 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -178,6 +181,7 @@ test("SiteSettings keeps its 46 fields, in file order", () => {
"attribution",
"archiveOrg",
"archives",
+ "remoteArchives",
"publish",
"reportSchedule",
"seeder",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -82,6 +82,7 @@ export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSetting
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
import { sanitizeVoice, type VoiceSettings } from "./voiceSettings";
import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
+import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings";
@@ -109,6 +110,7 @@ export {
type VoiceSettings,
} from "./voiceSettings";
export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
+export { REMOTE_ARCHIVE_FIELD_DOCS, type RemoteArchive } from "./remoteArchives";
export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings";
@@ -1988,6 +1990,9 @@ export const siteSettingsSchema = z.object({
archives: settingsField((v): ArchivesSettings => sanitizeArchives(v)).describe(
"The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings.",
),
+ remoteArchives: settingsField((v): RemoteArchive[] => sanitizeRemoteArchives(v)).describe(
+ "The PUBLISHED ARCHIVES this machine reads as sources (demo epic D1, lib/remoteArchives.ts): each a site serving `/corpus.json`, connected once by its origin (the editor's /sites → Connect an archive, umtool's Source chip, or `pnpm ops archives`). Create, research and the MCP offer each one; a sweep over one cites that origin; a clip window cited from one registers a REMOTE-ONLY channel (CHANNEL.md `remoteOnly`) to fetch it. TRANSCRIPT_SITE_URL, when set and not listed here, is offered too without being written. Empty = none. See RemoteArchive.",
+ ),
publish: settingsField((v): PublishSettings => sanitizePublish(v)).describe(
"The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.",
),
diff --git a/editor/app/api/ops/archives/route.ts b/editor/app/api/ops/archives/route.ts
@@ -0,0 +1,61 @@
+import { NextResponse } from "next/server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { ArchiveProbeError } from "yt-dlp-transcript-common/lib/remoteArchives-server";
+import {
+ RemoteArchiveError,
+ connectRemoteArchive,
+ removeRemoteArchive,
+ type RemoteArchiveDeps,
+} from "yt-dlp-transcript-common/controller/remoteArchives";
+import { saveSettings } from "../../../settings/saveSettings";
+import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// THE CONNECTED ARCHIVES (demo epic D1; lib/remoteArchives.ts): the published
+// archives this machine reads as sources — Create, research and the MCP offer
+// each, a sweep over one cites it, and a window it cites registers a
+// remote-only channel to fetch it.
+//
+// GET /api/ops/archives
+// -> { ok, archives: [{ id, origin, title, addedAt, fromEnv? }] }
+// (`fromEnv`: TRANSCRIPT_SITE_URL's, listed and never stored)
+// POST { connect: "<origin>", dryRun? }
+// -> { ok, archive, probe: { origin, siteId, title, spec, generatedAt,
+// totals, channels }, already }
+// reads <origin>/corpus.json once; a hub, a cited-only site, a site with
+// no channels or an origin that does not answer is refused (400/502).
+// dryRun answers the probe and writes nothing (already: null); an origin
+// connected already writes nothing (already: true).
+// POST { remove: "<id or origin>" } -> { ok, removed }
+
+const deps = (): RemoteArchiveDeps => ({
+ stored: () => getSettings().remoteArchives,
+ save: (next) => saveSettings({ remoteArchives: next }),
+});
+
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => ({ archives: connectedArchives(getSettings().remoteArchives) }));
+}
+
+export async function POST(request: Request) {
+ return ops(request, ["connect", "remove", "dryRun"], async (body) => {
+ const connect = optString(body, "connect")?.trim();
+ const remove = optString(body, "remove")?.trim();
+ if (!!connect === !!remove) throw new OpsInputError('send "connect" (an origin) or "remove" (an id or origin)');
+ try {
+ if (connect) {
+ const r = await connectRemoteArchive({ origin: connect, dryRun: optBool(body, "dryRun") === true }, deps());
+ return NextResponse.json({ ok: true, ...r });
+ }
+ if (optBool(body, "dryRun") !== undefined) throw new OpsInputError('"dryRun" goes with "connect"');
+ return NextResponse.json({ ok: true, removed: await removeRemoteArchive(remove!, deps()) });
+ } catch (e) {
+ if (e instanceof ArchiveProbeError) return opsFail(e.message, e.status);
+ if (e instanceof RemoteArchiveError) return opsFail(e.message);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts
@@ -8,6 +8,7 @@
// - autoQueue: a lane's tree is its policy editor's, or compiled from the
// channel priorities — and the editor refuses a tree edit while they rule.
// - workers: /workers validates each worker (templates, URLs) on save.
+// - remoteArchives: an archive's corpus.json is read when it is connected.
// - storage: a location is probed and its volume recorded when added or
// re-pointed (/storage); a raw root would skip both.
export const OWNED_KEYS: Readonly<Record<string, string>> = {
@@ -15,6 +16,7 @@ export const OWNED_KEYS: Readonly<Record<string, string>> = {
autoQueue:
"a lane's switch, hold and runner are `pnpm ops lane`; its tree is the policy editor's on /operations, or compiled from channel priorities",
workers: "workers are saved on /workers; `pnpm ops workers` enables and disables them",
+ remoteArchives: "an archive is probed (its corpus.json read) when it is connected — use `pnpm ops archives` or /sites → Connect an archive",
storage: "locations are added and re-pointed on /storage, which probes them; a channel's media moves with `pnpm ops relocate`",
};
diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts
@@ -10,6 +10,14 @@ import {
siteDeleteBlocked,
type SiteDeletePlan,
} from "yt-dlp-transcript-common/publish/siteDelete";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ connectRemoteArchive,
+ removeRemoteArchive,
+ type ConnectResult,
+ type RemoteArchiveDeps,
+} from "yt-dlp-transcript-common/controller/remoteArchives";
+import { saveSettings } from "../settings/saveSettings";
import { saveSiteFromForm, type SaveResult } from "./lib/saveSiteForm";
export type { SaveResult } from "./lib/saveSiteForm";
@@ -81,3 +89,36 @@ export async function migrateToSitesAction(): Promise<DeleteResult> {
// /settings is dynamic, rendered afresh on the next visit.
return { ok: true };
}
+
+// CONNECT AN ARCHIVE (demo epic D1): the /sites panel's two presses — Read it
+// (a dry run: corpus.json read, nothing written) and Connect — and Remove, all
+// through the one controller `pnpm ops archives` uses.
+export type ArchiveActionResult =
+ | { ok: true; result: ConnectResult }
+ | { ok: false; error: string };
+
+const archiveDeps = (): RemoteArchiveDeps => ({
+ stored: () => getSettings().remoteArchives,
+ save: (next) => saveSettings({ remoteArchives: next }),
+});
+
+export async function connectArchiveAction(origin: string, dryRun: boolean): Promise<ArchiveActionResult> {
+ try {
+ const result = await connectRemoteArchive(
+ { origin, dryRun },
+ archiveDeps(),
+ );
+ return { ok: true, result };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
+
+export async function removeArchiveAction(id: string): Promise<{ ok: true } | { ok: false; error: string }> {
+ try {
+ await removeRemoteArchive(id, archiveDeps());
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/sites/components/ConnectArchive.tsx b/editor/app/sites/components/ConnectArchive.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import type { ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import type { ArchiveProbe } from "yt-dlp-transcript-common/lib/remoteArchives-server";
+import { connectArchiveAction, removeArchiveAction } from "../actions";
+
+// CONNECTED ARCHIVES (demo epic D1): the published archives this machine reads
+// as sources. Type an origin → Read it (its corpus.json: title, channels,
+// videos, nothing saved) → Connect. Each row's Remove drops it; the one
+// TRANSCRIPT_SITE_URL names is listed and cannot be removed here.
+
+const nf = new Intl.NumberFormat("en-US");
+
+export function ConnectArchive({ archives }: { archives: ConnectedArchive[] }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [origin, setOrigin] = useState("");
+ const [probe, setProbe] = useState<ArchiveProbe | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [said, setSaid] = useState<string | null>(null);
+
+ const read = () =>
+ start(async () => {
+ setError(null);
+ setSaid(null);
+ setProbe(null);
+ const r = await connectArchiveAction(origin, true);
+ if (r.ok) setProbe(r.result.probe);
+ else setError(r.error);
+ });
+ const connect = () =>
+ start(async () => {
+ setError(null);
+ const r = await connectArchiveAction(probe?.origin ?? origin, false);
+ if (!r.ok) return setError(r.error);
+ setSaid(r.result.already ? `${r.result.archive.title} was connected already.` : `Connected ${r.result.archive.title}.`);
+ setProbe(null);
+ setOrigin("");
+ router.refresh();
+ });
+ const remove = (id: string) =>
+ start(async () => {
+ setError(null);
+ const r = await removeArchiveAction(id);
+ if (!r.ok) setError(r.error);
+ else router.refresh();
+ });
+
+ return (
+ <div className="flex flex-col gap-3" data-connected-archives="">
+ {archives.length > 0 ? (
+ <ul className="flex flex-col divide-y divide-border" aria-label="connected archives">
+ {archives.map((a) => (
+ <li key={a.origin} className="flex items-center justify-between gap-3 py-2" data-archive={a.id}>
+ <div className="min-w-0">
+ <div className="font-medium">{a.title}</div>
+ <div className="text-xs text-muted-foreground">
+ <code>{a.origin}</code>
+ {a.fromEnv ? " · from TRANSCRIPT_SITE_URL" : ` · connected ${a.addedAt.slice(0, 10)}`}
+ </div>
+ </div>
+ {!a.fromEnv && (
+ <button
+ type="button"
+ disabled={pending}
+ onClick={() => remove(a.id)}
+ aria-label={`remove ${a.title}`}
+ className="px-2 py-1 rounded border border-border text-xs disabled:opacity-50"
+ >
+ Remove
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm italic text-muted-foreground">No archive connected.</p>
+ )}
+ <form
+ className="flex flex-wrap items-center gap-2"
+ aria-label="connect an archive"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (probe && probe.origin) connect();
+ else read();
+ }}
+ >
+ <input
+ type="text"
+ aria-label="archive origin"
+ placeholder="https://jeralyzer.pages.dev"
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setProbe(null);
+ }}
+ className="w-80 rounded-md border border-border bg-background px-2 py-1 text-sm"
+ />
+ <button
+ type="button"
+ disabled={pending || !origin.trim()}
+ onClick={read}
+ className="px-3 py-1 rounded-md border border-border text-sm disabled:opacity-50"
+ >
+ {pending && !probe ? "Reading…" : "Read it"}
+ </button>
+ {probe && (
+ <button type="button" disabled={pending} onClick={connect} className="px-3 py-1 rounded-md bg-primary text-primary-foreground text-sm disabled:opacity-50">
+ Connect
+ </button>
+ )}
+ </form>
+ {probe && (
+ <div className="rounded-md border border-border px-3 py-2 text-sm" data-archive-probe={probe.origin}>
+ <div className="font-medium">{probe.title}</div>
+ <div className="text-xs text-muted-foreground">
+ {nf.format(probe.totals.channels)} channel{probe.totals.channels === 1 ? "" : "s"} · {nf.format(probe.totals.videos)} videos
+ {probe.generatedAt ? ` · built ${probe.generatedAt.slice(0, 10)}` : ""}
+ {probe.spec !== null ? ` · corpus spec ${probe.spec}` : ""}
+ </div>
+ <ul className="mt-1 flex flex-wrap gap-x-3 text-xs" aria-label="its channels">
+ {probe.channels.slice(0, 40).map((c) => (
+ <li key={c.slug}>
+ {c.name}
+ {c.videoCount !== null ? <span className="text-muted-foreground"> {nf.format(c.videoCount)}</span> : null}
+ </li>
+ ))}
+ {probe.channels.length > 40 && <li className="text-muted-foreground">…and {probe.channels.length - 40} more</li>}
+ </ul>
+ </div>
+ )}
+ {said && <p className="text-sm text-muted-foreground">{said}</p>}
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/sites/page.tsx b/editor/app/sites/page.tsx
@@ -22,6 +22,9 @@ import { AmendReleaseForm } from "./components/AmendReleaseForm";
import { HomepageConfigForm } from "./components/HomepageConfigForm";
import { PublishPanel, type PanelRow } from "./components/PublishPanel";
import { DeleteSiteButton, MigrateButton } from "./components/SiteListActions";
+import { ConnectArchive } from "./components/ConnectArchive";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Sites" };
@@ -129,6 +132,19 @@ export default async function SitesPage() {
</ul>
</section>
+ {/* Connected archives (demo epic D1): published archives read as
+ sources — Create, research and the MCP offer each one. */}
+ <section className="flex flex-col gap-3 border-t border-border pt-6" aria-labelledby="archives-heading">
+ <div>
+ <h2 id="archives-heading" className="text-lg font-semibold">Connected archives</h2>
+ <p className="text-sm text-muted-foreground">
+ Published archives this machine reads as sources: a sweep over one
+ cites it, and a clip it cites is fetched as a remote-only channel.
+ </p>
+ </div>
+ <ConnectArchive archives={connectedArchives(getSettings().remoteArchives)} />
+ </section>
+
{/* Release: stage the changelog before shipping anything. */}
<section className="flex flex-col gap-3 border-t border-border pt-6">
<div>
diff --git a/mcp/src/connectedArchives.test.ts b/mcp/src/connectedArchives.test.ts
@@ -0,0 +1,27 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { connectedArchivesHere } from "./sources";
+
+// list_sources offers the archives the editor connected (demo epic D1): read
+// from settings.json through the one resolver, TRANSCRIPT_SITE_URL's added.
+test("the MCP lists the connected archives from settings.json, the environment's after them", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "mcp-archives-"));
+ try {
+ const file = path.join(dir, "settings.json");
+ await writeFile(file, JSON.stringify({ remoteArchives: [{ id: "stub", origin: "https://stub.test/", title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }));
+ const list = connectedArchivesHere(file, { TRANSCRIPT_SITE_URL: "https://other.test" });
+ assert.deepEqual(
+ list.map((a) => [a.id, a.origin, a.fromEnv ?? false]),
+ [
+ ["stub", "https://stub.test", false],
+ ["other-test", "https://other.test", true],
+ ],
+ );
+ assert.deepEqual(connectedArchivesHere(path.join(dir, "missing.json"), {}), []);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -38,7 +38,7 @@ import {
type HubSite,
type ShardSource,
} from "./source";
-import type { SourceSpec } from "./sources";
+import { connectedArchivesHere, type SourceSpec } from "./sources";
import { SourceRegistry, type ResolvedSource } from "./sourceRegistry";
import type { Post } from "yt-dlp-transcript-common/lib/posts";
import {
@@ -2733,6 +2733,18 @@ async function handleListSources(
);
}
+ // The archives this machine's editor connected (demo epic D1): each a
+ // handle to pass, offered beside the default.
+ const connected = connectedArchivesHere();
+ if (connected.length > 0) {
+ lines.push(
+ `\nArchives connected on this machine (${connected.length}):\n` +
+ connected
+ .map((a) => ` - ${a.title} · ${a.origin}${a.fromEnv ? " (TRANSCRIPT_SITE_URL)" : ""}\n source: remote:${a.origin}`)
+ .join("\n"),
+ );
+ }
+
lines.push(
`\nPass a corpus per call, in each tool's own \`source\` argument — ` +
`'default', 'local:<dir>', 'remote:<url>', 'hub:<url>', or ` +
diff --git a/mcp/src/sources.ts b/mcp/src/sources.ts
@@ -1,3 +1,6 @@
+import { readFileSync } from "node:fs";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { connectedArchives, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
import {
LocalSource,
RemoteSource,
@@ -64,3 +67,21 @@ export function buildSource(spec: SourceSpec): ShardSource {
export function resolveSource(argv: string[]): ShardSource {
return buildSource(resolveSourceSpec(argv));
}
+
+// The archives this machine's editor has CONNECTED (settings.remoteArchives,
+// plus TRANSCRIPT_SITE_URL's — the one resolver, common/lib/remoteArchives.ts),
+// for list_sources: each one a `remote:<origin>` handle a call can pass. Read
+// from settings.json (SETTINGS_FILE, else the checkout's); a clone with none, or
+// no readable file, has only the environment's.
+export function connectedArchivesHere(
+ settingsFile: string = getPaths().settingsFile,
+ env: Record<string, string | undefined> = process.env,
+): ConnectedArchive[] {
+ let stored: unknown = [];
+ try {
+ stored = (JSON.parse(readFileSync(settingsFile, "utf8")) as { remoteArchives?: unknown })?.remoteArchives ?? [];
+ } catch {
+ stored = [];
+ }
+ return connectedArchives(stored, env);
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -125,6 +125,8 @@
// tag exists on, absent = every site — included)
// pnpm ops tag-videos --file ids.json
// pnpm ops persist-videos --file list.json --wait
+// pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'
+// pnpm ops get archives
// pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'
// pnpm ops fetch-windows --file windows.json --wait
// pnpm ops get tags eva-collab
@@ -277,6 +279,9 @@ const GETTERS = {
slug ? `/api/ops/saved-alternates?slug=${encodeURIComponent(slug)}` : "/api/ops/saved-alternates",
// Every site: id, title, siteUrl, Pages project, audience, policy, channels.
sites: () => "/api/ops/sites",
+ // The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's,
+ // marked fromEnv): the published archives this machine reads as sources.
+ archives: () => "/api/ops/archives",
// The transcription workers and what each is running.
workers: () => "/api/ops/workers",
// The four lanes: runner, policy, cooldowns, picks, pending.
@@ -344,6 +349,7 @@ const GET_ARG_OPTIONAL = new Set([
"storage",
"saved-alternates",
"sites",
+ "archives",
"workers",
"auto-queue",
"scheduler",
@@ -400,6 +406,10 @@ const ACTIONS = [
// Delete a site ({id, force?, dryRun?}): the plan, then sites/<id>/, its
// publish state and its staging. Channel data is never touched. Synchronous.
"delete-site",
+ // Connect a published archive as a source ({connect: "<origin>", dryRun?}:
+ // its corpus.json read once, then saved) or remove one ({remove: "<id>"}).
+ // Synchronous; no job.
+ "archives",
// The channel's lifecycle: the New channel form, and the channel page's
// Danger → Rename and Danger → Delete. Synchronous; no job.
"create-channel",
@@ -1111,6 +1121,8 @@ export function usage() {
"get sites lists every site: id, title, siteUrl, Pages project, audience,",
" listed, search, publish policy, channels, citedChannels. (`get publish`",
" is the status.)",
+ "get archives lists the connected archives: id, origin, title, addedAt;",
+ " TRANSCRIPT_SITE_URL's, when set and not stored, is listed with fromEnv.",
"get workers, get auto-queue and get scheduler are /workers, the four lanes",
" of /operations, and /operations/sync — the payloads those pages poll.",
"get services is the dashboard's cookie refresh alerts: each service",
@@ -1499,6 +1511,14 @@ export function usage() {
" own. Refused, force or not: no such site (404), a site dir that is a link,",
" a publish stage running.",
"",
+ 'archives connects a published archive as a source: {"connect": "<origin>"}',
+ " reads <origin>/corpus.json once (its title, totals and channels) and saves",
+ ' it in settings.remoteArchives; "dryRun"? answers the probe and writes',
+ " nothing; an origin connected already writes nothing. A federation hub, a",
+ " cited-only site, one with no channels or one that does not answer is",
+ ' refused. {"remove": "<id or origin>"} drops one. Create, research and the',
+ " MCP offer each connected archive; a sweep over it cites it.",
+ "",
'create-channel is the New channel form: {"fields": {"name", "handling":',
' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,',
' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else',
diff --git a/settings.json.example b/settings.json.example
@@ -213,6 +213,7 @@
"archiveTodayCooldownMinutes": 30,
"archiveTodayBrowser": true
},
+ "remoteArchives": [],
"publish": {
"enabled": false,
"held": false,
diff --git a/umtool/app/api/research/archives/route.ts b/umtool/app/api/research/archives/route.ts
@@ -0,0 +1,21 @@
+import { askEditor } from "@/lib/articles/generation";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// CONNECT AN ARCHIVE from the Source chip (demo epic D1): forwarded to the
+// editor's `archives` action, which reads the archive's corpus.json and — unless
+// `dryRun` — saves it in settings.remoteArchives (the one writer). The chip then
+// lists it (lib/research/sources.ts reads the same list).
+//
+// POST { origin, dryRun? } -> the editor's { ok, archive, probe, already }
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as { origin?: unknown; dryRun?: unknown } | null;
+ if (!body || typeof body.origin !== "string" || !body.origin.trim()) return Response.json({ error: "send { origin }: the archive's address" }, { status: 400 });
+ const answer = await askEditor("/api/ops/archives", { method: "POST", body: { connect: body.origin.trim(), ...(body.dryRun === true ? { dryRun: true } : {}) } });
+ return ok(answer);
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/components/research/ConnectArchive.tsx b/umtool/components/research/ConnectArchive.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { controlClass } from "@/components/ui/field";
+import { cn } from "@/lib/utils";
+
+// CONNECT AN ARCHIVE (demo epic D1), from the Source chip: type an origin, Read
+// it (its corpus.json: title, channels, videos — nothing saved), Connect. The
+// editor's `archives` action does both (POST /api/research/archives forwards),
+// so a connect here is the one /sites and `pnpm ops archives` make. Connected,
+// the page reloads its sources and the scope moves to the new one.
+
+type Probe = { origin: string; title: string; totals: { channels: number; videos: number }; channels: { slug: string; name: string; videoCount: number | null }[] };
+
+const nf = new Intl.NumberFormat("en-US");
+
+export default function ConnectArchive({ onConnected, onCancel }: { onConnected: (handle: string) => void; onCancel: () => void }) {
+ const router = useRouter();
+ const [origin, setOrigin] = useState("");
+ const [probe, setProbe] = useState<Probe | null>(null);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ async function ask(dryRun: boolean) {
+ setBusy(true);
+ setError("");
+ try {
+ const r = await fetch("/api/research/archives", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ origin: probe?.origin ?? origin, dryRun }),
+ });
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ if (dryRun) setProbe(b.probe);
+ else {
+ router.refresh();
+ onConnected(`remote:${b.archive.origin}`);
+ }
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <form
+ aria-label="connect an archive"
+ className="flex basis-full flex-col gap-1.5 rounded-[3px] border border-seam-2 bg-panel p-2.5 text-[12.5px]"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void ask(!probe);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ autoFocus
+ aria-label="archive origin"
+ placeholder="https://jeralyzer.pages.dev"
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setProbe(null);
+ }}
+ className={cn(controlClass, "w-72 py-[3px] text-[12px]")}
+ />
+ <Button type="submit" size="sm" variant={probe ? "go" : "outline"} disabled={busy || !origin.trim()}>
+ {busy ? "Reading…" : probe ? "Connect" : "Read it"}
+ </Button>
+ <Button type="button" size="sm" variant="quiet" onClick={onCancel}>
+ Cancel
+ </Button>
+ </div>
+ {probe && (
+ <p data-archive-probe={probe.origin} className="text-text-2">
+ <span className="font-medium text-text">{probe.title}</span> · {nf.format(probe.totals.channels)} channels · {nf.format(probe.totals.videos)} videos
+ <span className="text-muted">
+ {" "}
+ — {probe.channels.slice(0, 8).map((c) => c.name).join(", ")}
+ {probe.channels.length > 8 ? `, and ${probe.channels.length - 8} more` : ""}
+ </span>
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="text-bad">
+ {error}
+ </p>
+ )}
+ </form>
+ );
+}
diff --git a/umtool/components/research/ScopeBar.tsx b/umtool/components/research/ScopeBar.tsx
@@ -1,11 +1,15 @@
"use client";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { VIDEO_STATES, VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
import { badgeVariants } from "@/components/ui/badge";
import { controlClass } from "@/components/ui/field";
import { cn } from "@/lib/utils";
import type { Scope, ScopeSummary, SourceOption } from "@/lib/research/types";
+import ConnectArchive from "./ConnectArchive";
+
+// The Source select's last option: not a source, the Connect form (demo epic D1).
+const CONNECT = "connect:";
// ---------------------------------------------------------------------------
// The scope chips and the "holds …" line under them (canvas `.scope`): which
@@ -58,6 +62,7 @@ export default function ScopeBar({
onChange: (next: Scope) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
+ const [connecting, setConnecting] = useState(false);
// One click outside closes an open chip.
useEffect(() => {
const close = (e: MouseEvent) => {
@@ -92,7 +97,10 @@ export default function ScopeBar({
aria-label="Source"
disabled={disabled}
value={source?.handle ?? ""}
- onChange={(e) => onChange({ source: e.target.value })}
+ onChange={(e) => {
+ if (e.target.value === CONNECT) setConnecting(true);
+ else onChange({ source: e.target.value });
+ }}
className={cn(controlClass, "max-w-[260px] py-[3px] text-[12px]")}
>
{sources.map((s) => (
@@ -101,6 +109,7 @@ export default function ScopeBar({
{s.detail ? ` · ${s.detail}` : ""}
</option>
))}
+ <option value={CONNECT}>Connect an archive…</option>
</select>
<Pop
@@ -207,6 +216,15 @@ export default function ScopeBar({
</>
)}
</div>
+ {connecting && (
+ <ConnectArchive
+ onCancel={() => setConnecting(false)}
+ onConnected={(handle) => {
+ setConnecting(false);
+ onChange({ source: handle });
+ }}
+ />
+ )}
</div>
);
}
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -1,6 +1,7 @@
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
import { readCensus } from "./census.mjs";
import type { SourceOption } from "./types";
@@ -12,8 +13,11 @@ import type { SourceOption } from "./types";
// local the composed public dir on this machine, resolved as the MCP
// server's default resolves it: TRANSCRIPT_LOCAL_DIR, else
// EXPORT_PUBLIC_DIR, else <repo>/export/public
-// remote a published site: every transcripts/sites/*/site.json with a
-// `siteUrl` (a private site has none, and is not offered)
+// remote a published archive: every CONNECTED archive (settings.json
+// `remoteArchives`, plus TRANSCRIPT_SITE_URL's — the one resolver,
+// yt-dlp-transcript-common/lib/remoteArchives.ts), then every
+// transcripts/sites/*/site.json with a `siteUrl` not already
+// listed (a private site has none, and is not offered)
// hub TRANSCRIPT_HUB_URL, else settings.json `homepageUrl`
//
// Only an OFFERED handle opens: a request naming any other directory or origin
@@ -62,13 +66,24 @@ export async function listSources(): Promise<SourceOption[]> {
detail: corpus?.site?.title ? `this machine · ${corpus.site.title} build` : "this machine",
},
];
- const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
+ const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
+ const settings = await readJson<{ homepageUrl?: unknown; remoteArchives?: unknown }>(settingsFile);
const sites: SourceOption[] = [];
+ for (const a of connectedArchives(settings?.remoteArchives)) {
+ sites.push({
+ handle: `remote:${a.origin}`,
+ kind: "remote",
+ label: a.title,
+ detail: `connected · ${a.origin.replace(/^https?:\/\//, "")}`,
+ });
+ }
+ const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
for (const id of ids.sort()) {
if (id.startsWith("_") || id.startsWith(".")) continue;
const site = await readJson<{ siteUrl?: unknown; siteTitle?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json"));
const url = typeof site?.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : "";
if (!/^https?:\/\//.test(url)) continue;
+ if (sites.some((x) => x.handle === `remote:${url}`)) continue;
sites.push({
handle: `remote:${url}`,
kind: "remote",
@@ -77,8 +92,7 @@ export async function listSources(): Promise<SourceOption[]> {
});
}
out.push(...sites);
- const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
- const hub = hubUrl(await readJson<{ homepageUrl?: unknown }>(settingsFile));
+ const hub = hubUrl(settings);
if (hub) out.push({ handle: `hub:${hub}`, kind: "hub", label: "Hub", detail: `every listed site · ${hub.replace(/^https?:\/\//, "")}` });
return out;
}