Archilyzer · Source

archilyzer

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

commit 1c523befdde474edc25370caa871d709445baf46
parent 019aaca39dee45f3c9b66e97c67f4243c59e336d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 09:21:20 -0500

local media: a public site's build carries no local recording; a private one does

Review fix 3, the publish boundary (ruling: until slice 4 decides otherwise).
A record with platform "local" (or a local-<32 hex> id where only the id is
known; lib/localMedia.ts isLocalRecord) is built only into a PRIVATE-audience
site. A channel can mix local and online records, and compose copies each
channel's shared tree whole, so the split is per record and fails closed:

- buildIndex: the SHARED transcript tree (what every site copies) leaves local
  recordings out. A channel that holds one also gets the full tree under
  shared/private/transcripts/<slug> (its own page-hash keys), removed when it
  holds none. The per-site summaries loop skips them for a public site, so
  its pages, manifest totals (and so site.json, corpus.json, llms.txt counts)
  and tag counts have none, and the build log says once per public site:
  "Site <id>: N local recording(s) left out ...". A private site's fingerprint
  carries `private: true`, so flipping the audience rebuilds it.
- compose-site: transcriptsSourceFor() copies the private tree for a private
  site where it exists; a public site never reads the private root.
- buildStats: a public site's bundle and the hub's whole-pool bundle have no
  local recording; a private site's does; counts per channel from what is kept.
- duplicates.json: a public site's clusters drop local refs.
- composeReports: a public host (site or articles) refuses a citation of a
  local recording ("not-visible"); a private host carries it.
- For EVERY site in this slice: the shared subs and digests trees and the
  archive zips leave local recordings out (no private variant of those yet;
  the transcript is in the transcript tree, which is what search reads).

Sitemap and feeds list no per-video URL; no corpus.json spec change.
Tests: public vs private site summaries, counts and the one log line; the
shared vs private tree; compose's tree choice; per-site and whole-pool stats;
duplicates; report citations both ways; the archive zip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
Mcommon/bin/compose-site.ts | 31++++++++++++++++++++++++++++---
Mcommon/controller/archiveTranscripts.ts | 9+++++++++
Mcommon/controller/buildIndex.ts | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/controller/buildIndexLocalRecording.test.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/buildStats.ts | 31++++++++++++++++++++++---------
Mcommon/controller/localMediaLifecycle.test.ts | 19+++++++++++++++++++
Mcommon/lib/duplicates.test.ts | 13+++++++++++++
Mcommon/lib/duplicates.ts | 5++++-
Mcommon/lib/localMedia.ts | 10++++++++++
Mcommon/lib/paths.ts | 8++++++++
Mcommon/publish/composeReports.ts | 8++++++++
Mcommon/publish/composeReportsArticles.test.ts | 30++++++++++++++++++++++++++++++
12 files changed, 286 insertions(+), 28 deletions(-)

diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts @@ -21,10 +21,11 @@ // reports, site.json (no channels) and corpus.json (`site.scope: "cited"`) — // see composeCitedSite. +import { isLocalRecord } from "../lib/localMedia"; import path from "node:path"; import { cp, link, mkdir, rm, readdir, access, readFile, writeFile, stat, rename } from "node:fs/promises"; import type { Dirent } from "node:fs"; -import { getPaths, type Paths } from "../lib/paths"; +import { getPaths, sharedPrivateTranscriptsDir, type Paths } from "../lib/paths"; import { dirSignature } from "../lib/dirSignature"; import { getSite, resolveSocialLinks, resolveHubUrl, type Site } from "../lib/site"; import { getSettings } from "../lib/settings"; @@ -727,6 +728,24 @@ async function writeComposeCache(p: string, cache: ComposeCache): Promise<void> // under a constant signature and the contract stays unconditional. export const MANIFEST_ONLY_SIGNATURE = "manifest-only"; +// WHICH TRANSCRIPT TREE A SITE COPIES (lane/local-media slice 1 ruling). The +// shared tree leaves local recordings out; a channel that holds one also has a +// full tree under sharedPrivateTranscriptsDir. A PRIVATE-audience site copies +// that one where it exists; every other site, and every channel without one, +// copies the shared tree. Fail-closed: a public site never reads the private root. +export function transcriptsSourceFor( + paths: Pick<Paths, "exportSharedDir" | "exportSharedTranscriptsDir">, + privateSite: boolean, +): (slug: string) => Promise<string> { + return async (slug) => { + if (privateSite) { + const full = path.join(sharedPrivateTranscriptsDir(paths), slug); + if (await exists(full)) return full; + } + return path.join(paths.exportSharedTranscriptsDir, slug); + }; +} + export async function reconcileChannelTree( kind: string, srcRoot: string, @@ -734,6 +753,9 @@ export async function reconcileChannelTree( memberSlugs: string[], prev: Record<string, string>, log: (m: string) => void, + // Where one member's tree comes from, when not `srcRoot/<slug>`: the + // transcripts of a private-audience site (transcriptsSourceFor). + srcFor?: (slug: string) => Promise<string>, ): Promise<Record<string, string>> { // A linked tree (a worktree's public/<tree> → the primary's) becomes this // checkout's own before anything is copied into or pruned from it. @@ -743,7 +765,7 @@ export async function reconcileChannelTree( let copied = 0; let skipped = 0; for (const slug of memberSlugs) { - const src = path.join(srcRoot, slug); + const src = srcFor ? await srcFor(slug) : path.join(srcRoot, slug); const dest = path.join(destRoot, slug); // Exclude the per-channel manifest.json — its `generatedAt` churns every // mutation build; the page files capture real content changes. @@ -912,6 +934,7 @@ export async function main( memberSlugs, cache.transcripts, console.log, + transcriptsSourceFor(paths, isPrivateSite(site)), ); cache.subs = await reconcileChannelTree( "subs", @@ -1169,7 +1192,9 @@ export async function main( } const clusters = report.clusters .filter((c) => clusterIsPublishable(c, dupOverrides)) - .map((c) => filterClusterToChannels(c, memberSet)) + .map((c) => filterClusterToChannels(c, memberSet, + // A local recording only in a private-audience site's duplicates. + isPrivateSite(site) ? undefined : (r) => !isLocalRecord(r))) .filter((c): c is NonNullable<typeof c> => c !== null); if (clusters.length > 0) { const filtered: DuplicateReport = { diff --git a/common/controller/archiveTranscripts.ts b/common/controller/archiveTranscripts.ts @@ -19,6 +19,7 @@ // prettyPrint is overridden, staging rewrites each cues file instead of // hard-linking it (slower, but bounded). +import { LOCAL_RECORDING_ID_RE } from "../lib/localMedia"; import path from "node:path"; import { access, @@ -164,6 +165,14 @@ async function stageChannel( } catch { videoIds = []; } + // A local recording (its dir is its `local-<32 hex>` id) is in no archive zip + // in lane/local-media slice 1: the zip is a published download, and the cache + // is one per channel across every site, public and private. + const localIds = videoIds.filter((id) => LOCAL_RECORDING_ID_RE.test(id)); + if (localIds.length > 0) { + videoIds = videoIds.filter((id) => !LOCAL_RECORDING_ID_RE.test(id)); + log(`Archive ${ch.slug}: ${localIds.length} local recording(s) left out of the zip`); + } log(`Archive ${ch.slug}: scanning ${videoIds.length} videos`); diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -93,6 +93,7 @@ import { siteSummariesDir, siteSubsDir, } from "../lib/site"; +import { isPrivateSite } from "../lib/siteSchema"; import { type ChannelConfig, type ChannelHandling, @@ -107,7 +108,7 @@ import { heldReason, } from "../lib/channelMediaHold"; import { resolveChannelGroupId } from "../lib/channelGroups"; -import type { Paths } from "../lib/paths"; +import { sharedPrivateTranscriptsDir, type Paths } from "../lib/paths"; import { CAPTION_TRACK_RULE_VERSION, captionInputs, @@ -176,6 +177,7 @@ import { tagsForSite } from "../lib/curatedTags"; import { compileRecordedDateRule, deriveRecordedDate } from "../lib/recordedDate"; import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server"; import { localRecordingProblem } from "../lib/localRecordingMetadata"; +import { isLocalRecord } from "../lib/localMedia"; // v10: multi-site build. Shared per-channel transcript/subs pages are written // once; per-site summaries + subs manifests are filtered selections. Bumped to @@ -1579,12 +1581,18 @@ export async function buildIndex({ }; if (sharedNeedsBuild) { - for (const channelSlug of Array.from(channelConfigs.keys()).sort()) { - // A held channel's pages are left exactly as the last build wrote them: - // not rewritten, not pruned, and (below) not removed. After a full rebuild - // its records are gone, and a rewrite would publish it empty. - if (held.has(channelSlug)) continue; - const channelDir = path.join(transcriptsOutDir, channelSlug); + // One channel's transcript tree into `channelDir`. The SHARED tree (what every + // site copies) leaves local recordings out; a channel that holds one also + // gets a FULL tree under sharedPrivateTranscriptsDir, copied into private- + // audience sites only (lib/localMedia.ts isLocalRecord). `hashSlug` keys the + // page hashes, so the two trees never share a page's hash. + const writeTranscriptTree = async ( + channelSlug: string, + channelDir: string, + hashSlug: string, + includeLocal: boolean, + ): Promise<{ sawLocal: boolean }> => { + let sawLocal = false; await mkdir(channelDir, { recursive: true }); const writer = createPageWriter({ @@ -1592,22 +1600,26 @@ export async function buildIndex({ fileName: pageFileName, maxPageBytes: maxTranscriptPageBytes, ensureDir: false, - getPrevHash: (idx) => pageHashes.get([channelSlug, idx])?.hash, + getPrevHash: (idx) => pageHashes.get([hashSlug, idx])?.hash, setHash: (idx, record) => { - pageHashes.put([channelSlug, idx], record); + pageHashes.put([hashSlug, idx], record); }, onLog: log, }); for (const { key } of byChannel.getRange({ start: [channelSlug], - end: [channelSlug, "￿"], + end: [channelSlug, "\uffff"], })) { const ck = key as ChannelKey; if (ck[0] !== channelSlug) continue; const indexKey: IndexKey = [ck[1], ck[0], ck[2]]; const summary = sums.get(indexKey); if (!summary) continue; + if (isLocalRecord(summary)) { + sawLocal = true; + if (!includeLocal) continue; + } const cueList = cues.get(indexKey); // `track` + `altTracks` only on a record that has an alternate, so every // other record's page bytes are what they were. @@ -1637,8 +1649,8 @@ export async function buildIndex({ pagesDeleted++; } for (const { key } of pageHashes.getRange({ - start: [channelSlug, pageCount], - end: [channelSlug, Number.MAX_SAFE_INTEGER], + start: [hashSlug, pageCount], + end: [hashSlug, Number.MAX_SAFE_INTEGER], })) { pageHashes.remove(key as PageHashKey); } @@ -1655,6 +1667,38 @@ export async function buildIndex({ path.join(channelDir, "manifest.json"), channelManifest, ); + return { sawLocal }; + }; + + const privateTranscriptsOutDir = sharedPrivateTranscriptsDir(paths); + for (const channelSlug of Array.from(channelConfigs.keys()).sort()) { + // A held channel's pages are left exactly as the last build wrote them: + // not rewritten, not pruned, and (below) not removed. After a full rebuild + // its records are gone, and a rewrite would publish it empty. + if (held.has(channelSlug)) continue; + const { sawLocal } = await writeTranscriptTree( + channelSlug, path.join(transcriptsOutDir, channelSlug), channelSlug, false, + ); + const privateHashSlug = `private:${channelSlug}`; + if (sawLocal) { + await writeTranscriptTree( + channelSlug, path.join(privateTranscriptsOutDir, channelSlug), privateHashSlug, true, + ); + } else { + await rm(path.join(privateTranscriptsOutDir, channelSlug), { recursive: true, force: true }); + for (const { key } of pageHashes.getRange({ + start: [privateHashSlug, 0], + end: [privateHashSlug, Number.MAX_SAFE_INTEGER], + })) { + pageHashes.remove(key as PageHashKey); + } + } + } + // A private tree for a channel that is gone goes with it. + for (const e of await readdir(privateTranscriptsOutDir, { withFileTypes: true }).catch(() => [] as Dirent[])) { + if (!channelConfigs.has(e.name)) { + await rm(path.join(privateTranscriptsOutDir, e.name), { recursive: true, force: true }); + } } await pageHashes.flushed; @@ -1818,6 +1862,10 @@ export async function buildIndex({ if (!stored || stored.length === 0) continue; const summary = sums.get(indexKey); if (!summary) continue; + // A local recording's caption track is its transcript, carried in the + // transcript trees; the shared subs tree leaves it out for every site + // in lane/local-media slice 1 (no private subs variant). + if (isLocalRecord(summary)) continue; const display = toDisplaySummary(summary, { state: stateByIndexKey.get(indexKeyId(indexKey)), }); @@ -2195,6 +2243,8 @@ export async function buildIndex({ const indexKey: IndexKey = [ck[1], ck[0], ck[2]]; const digest = digests.get(indexKey); if (!digest) continue; + // Shared digests leave local recordings out for every site (slice 1). + if (isLocalRecord({ id: ck[2], platform: sums.get(indexKey)?.platform })) continue; await digestWriter.push(JSON.stringify(digest), digest.id); digestCount++; } @@ -2343,6 +2393,7 @@ export async function buildIndex({ .map((c) => c.slug) .filter((slug) => !memberSlugs.includes(slug)); const slugSet = new Set(memberSlugs); + const sitePrivate = isPrivateSite(site); const slugGroup = new Map<string, string>(); for (const m of site.channels) { slugGroup.set( @@ -2375,6 +2426,10 @@ export async function buildIndex({ // Only when the visibility rule withholds a member, so a site it does // not touch keeps the fingerprint it had. ...(withheld.length > 0 ? { withheld } : {}), + // A private site carries local recordings a public one leaves out + // (lib/localMedia.ts isLocalRecord): flipping the audience rebuilds it. + // Only on a private site, so a public site keeps the fingerprint it had. + ...(sitePrivate ? { private: true } : {}), }); const fpKey = `siteFp:${site.siteId}`; if ( @@ -2438,11 +2493,18 @@ export async function buildIndex({ // streaming every member record — no second walk of the corpus. compose // joins these to the site's effective vocabulary to write /tags.json. const tagCounter = createTagCounter(); + let localLeftOut = 0; for (const { key, value } of sums.getRange({ reverse: true })) { const ik = key as IndexKey; if (!slugSet.has(ik[1])) continue; const stored = value as TranscriptSummary; + // A local recording is built only into a PRIVATE-audience site (until + // slice 4): not in a public site's pages, counts or tags. + if (!sitePrivate && isLocalRecord(stored)) { + localLeftOut++; + continue; + } // A tag scoped to other sites (curated `sites`) is not this site's: // dropped from its summaries and its counts. A copy only when it moves — // the stored value is the LMDB cursor's. @@ -2462,6 +2524,11 @@ export async function buildIndex({ if (buffer.length >= pageSize) await flushPage(); } await flushPage(); + if (localLeftOut > 0) { + log( + `Site ${site.siteId}: ${localLeftOut} local recording(s) left out — a public site carries none until private playback (slice 4); a private-audience site carries them.`, + ); + } // Written even when empty (a tiny `{tags:{}}`), so a site that loses its // last tagged video does not keep serving a stale count file. compose diff --git a/common/controller/buildIndexLocalRecording.test.ts b/common/controller/buildIndexLocalRecording.test.ts @@ -55,8 +55,10 @@ function summaries(): Array<{id: string; platform: string; uploadDate: string; r return Array.from(sums.getRange(), ({value}) => value); } finally { root.close(); } } -function pages(): string { - const dir = path.join(paths.exportSharedTranscriptsDir, channel); +// The FULL tree (local recordings included) a private-audience site copies; +// the shared tree every other site copies leaves them out (review fix 3). +function pages(root = path.join(paths.exportSharedDir, "private", "transcripts")): string { + const dir = path.join(root, channel); return readdirSync(dir).filter(f => f.endsWith(".json")).map(f => readFileSync(path.join(dir,f),"utf8")).join("\n"); } @@ -65,7 +67,7 @@ test("source-less commits reach real search pages; retries and title rules retai writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling: "youtube", name: "Classroom"}); mkdirSync(dataDirectory, {recursive: true}); writeJson(path.join(paths.sitesDir,"localtest","site.json"), { - siteId: "localtest", siteTitle: "Test", siteDescription: "fixture", headerTitle: "Test", + siteId: "localtest", siteTitle: "Test", siteDescription: "fixture", headerTitle: "Test", audience: "private", homeTagline: "", socialLinks: [], groups: [{id:"default",name:"All",selectedByDefault:true}], defaultGroupId: "default", channels: [{slug:channel,groupId:"default"}], }); @@ -76,6 +78,8 @@ test("source-less commits reach real search pages; retries and title rules retai assert.match(pages(), /Synthetic classroom discovery phrase/); assert.match(pages(), /"platform":\s*"local"/); assert.doesNotMatch(pages(), /youtube.com/); + // The shared tree, which a public site copies, carries no local recording. + assert.doesNotMatch(pages(paths.exportSharedTranscriptsDir), /"platform":\s*"local"/); assert.deepEqual(await commit(first), {status:"occupied"}); assert.deepEqual(await commit(second, "2024-02-29"), {status:"imported"}); const online = path.join(dataDirectory,"online-no-date"); @@ -158,3 +162,52 @@ test("an undated local record pages last, keeps a stats row, and reads as unknow } finally { await recency.close(); } rmSync(online, {recursive: true, force: true}); }); + +// Review fix 3 (the publish boundary): a PUBLIC site's build leaves local +// recordings out — its summaries, counts and stats — and says so once with the +// count; a PRIVATE-audience site carries them; compose picks the private +// transcript tree for the private site only; the hub's whole-pool stats have none. +test("a public site leaves local recordings out and says so; a private one carries them", async () => { + const { siteSummariesDir, siteStatsDir } = await import("../lib/site"); + const { buildStats } = await import("./buildStats"); + const { transcriptsSourceFor } = await import("../bin/compose-site"); + const online = path.join(dataDirectory, "onlinepublic"); + writeJson(path.join(online, "metadata.info.json"), {id: "onlinepublic", title: "Online public", extractor_key: "Youtube", + upload_date: "20250102", webpage_url: "https://www.youtube.com/watch?v=onlinepublic"}); + writeFileSync(path.join(online, "transcript.en.vtt"), transcript); + writeJson(path.join(paths.sitesDir, "publictest", "site.json"), { + siteId: "publictest", siteTitle: "Public", siteDescription: "fixture", headerTitle: "Public", + homeTagline: "", socialLinks: [], groups: [{id: "default", name: "All", selectedByDefault: true}], + defaultGroupId: "default", channels: [{slug: channel, groupId: "default"}], + }); + const logs: string[] = []; + await buildIndex({paths, onLog: line => logs.push(line)}); + const listed = (site: string) => { + const dir = siteSummariesDir(paths, site); + const ids = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)) + .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id); + const manifest = JSON.parse(readFileSync(path.join(dir, "manifest.json"), "utf8")) as {totalCount: number}; + return {ids, total: manifest.totalCount}; + }; + const pub = listed("publictest"), priv = listed("localtest"); + assert.deepEqual(pub.ids, ["onlinepublic"]); + assert.equal(pub.total, 1); + assert.ok(priv.ids.includes(first) && priv.ids.includes(second) && priv.ids.includes("onlinepublic"), priv.ids.join()); + assert.equal(logs.filter(l => /Site publictest: 2 local recording\(s\) left out/.test(l)).length, 1, logs.join("\n")); + assert.ok(!logs.some(l => /Site localtest: .* local recording/.test(l))); + + // Compose's choice of transcript tree: the private one only for a private site. + assert.equal(await transcriptsSourceFor(paths, false)(channel), path.join(paths.exportSharedTranscriptsDir, channel)); + assert.equal(await transcriptsSourceFor(paths, true)(channel), path.join(paths.exportSharedDir, "private", "transcripts", channel)); + assert.equal(await transcriptsSourceFor(paths, true)("no-locals"), path.join(paths.exportSharedTranscriptsDir, "no-locals")); + + const pool = path.join(ROOT, "pool-stats"); + await buildStats({paths, onLog: () => {}, wholePoolStatsDir: pool}); + const statsIds = (dir: string) => readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)) + .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id); + assert.deepEqual(statsIds(siteStatsDir(paths, "publictest")), ["onlinepublic"]); + assert.ok(statsIds(siteStatsDir(paths, "localtest")).includes(first)); + assert.deepEqual(statsIds(pool), ["onlinepublic"]); + rmSync(online, {recursive: true, force: true}); + rmSync(path.join(paths.sitesDir, "publictest"), {recursive: true, force: true}); +}); diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts @@ -31,6 +31,8 @@ // other scanned, when the other can publish truncated pages. The editor's build // jobs share the "build" queue by default; the CLI is outside every queue. +import { isLocalRecord } from "../lib/localMedia"; +import { isPrivateSite } from "../lib/siteSchema"; import path from "node:path"; import { createHash } from "node:crypto"; import { @@ -637,19 +639,22 @@ export async function buildStats({ const sites = listSites(paths); const siteIds = new Set(sites.map((s) => s.siteId)); - const siteFingerprint = (slugs: string[]): string => + const siteFingerprint = (slugs: string[], privateSite: boolean): string => JSON.stringify({ gen: generation, max: STATS_MAX_PAGE_BYTES, channels: slugs, state: stateSignature, + // A private site's bundle carries local recordings (lib/localMedia.ts + // isLocalRecord); only there, so a public site keeps its fingerprint. + ...(privateSite ? { private: true } : {}), }); // Decide which sites need a rebuild before paying to collect the dataset. const plans = await Promise.all( sites.map(async (site) => { const slugs = site.channels.map((c) => c.slug); - const fp = siteFingerprint(slugs); + const fp = siteFingerprint(slugs, isPrivateSite(site)); const outDir = siteStatsDir(paths, site.siteId); const siteManifestPath = path.join(outDir, "manifest.json"); const stored = meta.get(`statsFp:${site.siteId}`) as string | undefined; @@ -709,7 +714,10 @@ export async function buildStats({ } signal?.throwIfAborted(); const slugSet = new Set(plan.slugs); - const filtered = all.filter((s) => slugSet.has(s.channelSlug)); + // A local recording only in a PRIVATE-audience site's bundle (until slice 4). + const sitePrivate = isPrivateSite(plan.site); + const filtered = all.filter((s) => slugSet.has(s.channelSlug) && (sitePrivate || !isLocalRecord(s))); + const siteCounts = countByChannel(filtered); const { pageCount } = await writePages( plan.outDir, filtered, @@ -719,7 +727,7 @@ export async function buildStats({ .map((slug) => ({ slug, name: channels.get(slug)?.name ?? slug, - count: perChannel.get(slug) ?? 0, + count: siteCounts.get(slug) ?? 0, })) .sort((a, b) => a.slug.localeCompare(b.slug)); const manifest: StatsManifest = { @@ -750,10 +758,9 @@ export async function buildStats({ // bundles. Always rewritten when requested (stats records are small). if (wholePoolStatsDir) { const unlistedOnly = channelsOnlyOnUnlistedSites(sites); - const pooled = - unlistedOnly.size > 0 - ? all.filter((s) => !unlistedOnly.has(s.channelSlug)) - : all; + // The hub and homepage are public: no local recording (until slice 4). + const pooled = all.filter((s) => !unlistedOnly.has(s.channelSlug) && !isLocalRecord(s)); + const poolCounts = countByChannel(pooled); const { pageCount } = await writePages( wholePoolStatsDir, pooled, @@ -764,7 +771,7 @@ export async function buildStats({ .map((slug) => ({ slug, name: channels.get(slug)?.name ?? slug, - count: perChannel.get(slug) ?? 0, + count: poolCounts.get(slug) ?? 0, })) .sort((a, b) => a.slug.localeCompare(b.slug)); const manifest: StatsManifest = { @@ -819,3 +826,9 @@ export async function buildStats({ durationMs: Date.now() - t0, }; } + +function countByChannel(stats: readonly VideoStat[]): Map<string, number> { + const out = new Map<string, number>(); + for (const s of stats) out.set(s.channelSlug, (out.get(s.channelSlug) ?? 0) + 1); + return out; +} diff --git a/common/controller/localMediaLifecycle.test.ts b/common/controller/localMediaLifecycle.test.ts @@ -102,3 +102,22 @@ test("deleting a channel removes corpus references but preserves external source assert.deepEqual(await readdir(f.paths.channelsDir),[]); assert.deepEqual(await f.hashes(),f.before); }); + +// Review fix 3: a local recording is in no archive zip in slice 1 (the zip is +// a published download, cached once per channel across public and private sites). +test("a local recording is left out of the channel's archive zip, and the log says so",async t=>{ + const f=await fixture(t); + const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata"); + const id="local-"+"9".repeat(32); + const data=path.join(f.paths.channelsDir,"sample","data"); + assert.equal((await commitLocalMediaRecord({dataDirectory:data,directoryId:id, + metadata:JSON.stringify(prepareManualLocalRecordingMetadata({id,filename:"talk.mp4"})), + transcript:"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nLocal only cue\n", + reference:{version:1,kind:"external",sourceId:f.sourceId,relativePath:"talk.mp4"}})).status,"imported"); + const logs:string[]=[]; + const result=await archiveTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip",includeMetadata:true},onLog:l=>logs.push(l)}); + const entries=await inspectZip(result.archives[0].archivePath); + assert.deepEqual(Object.keys(entries).sort(),["sample/channel.json","sample/record1/transcript.cues.json"]); + assert.equal(JSON.stringify(entries).includes("Local only cue"),false); + assert.ok(logs.some(l=>l.includes("1 local recording(s) left out of the zip")),logs.join("\n")); +}); diff --git a/common/lib/duplicates.test.ts b/common/lib/duplicates.test.ts @@ -562,3 +562,16 @@ test("a contained cluster (clip of a longer video) never shares", () => { true, ); }); + +// lane/local-media review fix 3: a public site's duplicates keep no local recording. +test("filterClusterToChannels takes a per-record rule: a local recording left out", () => { + const c = cluster([ + ref({ slug: "a/1", channelSlug: "a", platform: "youtube" }), + ref({ slug: "a/local-" + "a".repeat(32), channelSlug: "a", platform: "local", id: "local-" + "a".repeat(32) }), + ref({ slug: "b/2", channelSlug: "b", platform: "rumble" }), + ]); + const out = filterClusterToChannels(c, new Set(["a", "b"]), (r) => r.platform !== "local"); + assert.deepEqual(out?.videoRefs.map((r) => r.slug), ["a/1", "b/2"]); + assert.equal(filterClusterToChannels(c, new Set(["a"]), (r) => r.platform !== "local"), null); + assert.equal(filterClusterToChannels(c, new Set(["a", "b"]))?.videoRefs.length, 3); +}); diff --git a/common/lib/duplicates.ts b/common/lib/duplicates.ts @@ -725,9 +725,12 @@ export function strongerMatch( export function filterClusterToChannels( cluster: DuplicateCluster, channelSlugs: Set<string>, + // A further per-record rule: a public site keeps no local recording + // (lib/localMedia.ts isLocalRecord; bin/compose-site.ts). + keepRef?: (ref: DuplicateVideoRef) => boolean, ): DuplicateCluster | null { const videoRefs = cluster.videoRefs.filter((r) => - channelSlugs.has(r.channelSlug), + channelSlugs.has(r.channelSlug) && (keepRef ? keepRef(r) : true), ); if (videoRefs.length < 2) return null; return { diff --git a/common/lib/localMedia.ts b/common/lib/localMedia.ts @@ -65,3 +65,13 @@ export function localMediaFetchRefusal( return `${localRecord ? `"${id}" is a local recording` : `"${slug}" is a local media library channel`}` + " with no online source, so no clip can be fetched for it."; } + +// A record of a local media library's own (platform "local", or its +// `local-<32 hex>` id where only the id is known). Until private playback +// (slice 4) decides otherwise, such a record is built only into PRIVATE-audience +// sites: a public site's shards, counts, stats, duplicates and reports leave it +// out (controller/buildIndex.ts, controller/buildStats.ts, bin/compose-site.ts, +// publish/composeReports.ts). Review ruling, lane/local-media slice 1. +export function isLocalRecord(rec: { platform?: string | null; id?: string | null }): boolean { + return rec.platform === "local" || (typeof rec.id === "string" && LOCAL_RECORDING_ID_RE.test(rec.id)); +} diff --git a/common/lib/paths.ts b/common/lib/paths.ts @@ -373,3 +373,11 @@ function findMonorepoRoot(): string { } return start; } + +// The FULL per-channel transcript trees, local recordings included, written +// beside the shared (public-safe) ones only for a channel that holds a local +// recording, and copied into PRIVATE-audience sites only (lib/localMedia.ts +// isLocalRecord; controller/buildIndex.ts, bin/compose-site.ts). +export function sharedPrivateTranscriptsDir(paths: Pick<Paths, "exportSharedDir">): string { + return path.join(paths.exportSharedDir, "private", "transcripts"); +} diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -69,6 +69,7 @@ // thrown together (ComposeReportsError), so a failed compose leaves no half // set of reports behind. +import { isLocalRecord } from "../lib/localMedia"; import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view"; import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -646,6 +647,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol problems.push({ kind: "missing-record", citation: ref, report: report.id, message: `no record ${c.channel}/${c.id} (no metadata or transcript in its data dir)` }); continue; } + // A local recording publishes only on a private host (lane/local-media + // slice 1 ruling; lib/localMedia.ts isLocalRecord): its quote and cues + // never reach a public site or the public articles. + if (host.audience !== "private" && isLocalRecord({ id: c.id, platform: (record.summary as { platform?: string } | null)?.platform })) { + problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `${carrier} is public and may not carry the local recording ${c.channel}/${c.id} (local media is private until slice 4)` }); + continue; + } if (record.cues.length === 0) { problems.push({ kind: "no-cues", citation: ref, report: report.id, message: `${c.channel}/${c.id} has no transcript cues to check the quote against` }); continue; diff --git a/common/publish/composeReportsArticles.test.ts b/common/publish/composeReportsArticles.test.ts @@ -262,3 +262,33 @@ test("nothing published: the stage writes nothing and clears the output root's r assert.deepEqual(composed, { reports: [], moments: [], allowed: [] }); assert.deepEqual(filesUnder(OUT), []); }); + +// lane/local-media review fix 3: a local recording publishes only on a private +// host — a public build refuses a citation of one; a private build carries it. +test("refused: a local recording cited in a public build; a private build carries it", async () => { + const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata"); + const LOCAL = "local-" + "f".repeat(32); + const dir = path.join(paths.channelsDir, LONE, "data", LOCAL); + writeJson(path.join(dir, "metadata.info.json"), prepareManualLocalRecordingMetadata({ id: LOCAL, filename: "talk.mp4", title: "A local talk" })); + writeFileSync(path.join(dir, "transcript.en.vtt"), readFileSync(path.join(paths.channelsDir, LONE, "data", "abc123", "transcript.en.vtt"))); + seedArticle("art-local", { c01: { ...SPAN, id: LOCAL } }); + await configureArticle("art-local", { published: true, audience: "public" }, paths); + try { + const pub = await articlesReportHost(paths, { audience: "public" }); + await assert.rejects(composeHostReports({ paths, host: pub, publicDir: OUT, settings: {}, ...quiet }), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.filter((p) => p.citation === "art-local#c01").map((p) => [p.kind, p.message]), + [["not-visible", `the articles is public and may not carry the local recording ${LONE}/${LOCAL} (local media is private until slice 4)`]], + ); + return true; + }); + const priv = await articlesReportHost(paths, { audience: "private" }); + const composed = await composeHostReports({ paths, host: priv, publicDir: OUT, settings: {}, ...quiet }).catch((e: unknown) => e); + const problems = composed instanceof ComposeReportsError ? composed.problems : []; + assert.deepEqual(problems.filter((p) => p.citation === "art-local#c01"), []); + } finally { + await configureArticle("art-local", { published: false }, paths); + rmSync(dir, { recursive: true, force: true }); + } +});