Editorial corrections proposal: After Dark review, clash check, Ring X timing, name matching, adaptive film rest (read-only)
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m56s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m28s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 00:43:43 +00:00
co-authored by Claude Opus 5.5
parent 93f714f48b
commit 837f97a3bf
3 changed files with 429 additions and 0 deletions
@@ -0,0 +1,138 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
/**
* Read-only figures for the editorial corrections proposal (4 November 2026), from copies of the box's files:
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*EditorialCorrectionsAuditTest*'
* Four weeks of every channel topping up together as the box does (each avoiding the others' current plans), then:
* simultaneous screenings of the same title, Ring X weeknight start times (today, and with the weeknights on time),
* list titles the library doesn't match, and how each film channel keeps its rest. Writes editorial-corrections.txt.
*/
class EditorialCorrectionsAuditTest {
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
private val zone = java.time.ZoneId.of("Europe/London")
private val day = 24 * 60 * 60_000L
private val hour = 60 * 60_000L
private fun plan(file: File): ChannelPlan {
val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
val entries = (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n")
ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d),
o.getLong("a"), o.optString("w"), o.optString("p"))
}
val tallies = t.optJSONObject("tallies")?.let { all -> all.keys().asSequence().associateWith { b -> all.getJSONObject(b).let { r -> r.keys().asSequence().associateWith { r.getDouble(it) } } } }.orEmpty()
val runs = t.optJSONObject("runs")?.let { r -> r.keys().asSequence().associateWith { r.getLong(it) } }.orEmpty()
return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"),
marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } },
t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(),
t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty(), tallies, runs))
}
private fun pool(file: File): List<PoolSeries> {
val rows = JSONObject(file.readText()).getJSONArray("series")
return (0 until rows.length()).map { i ->
val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes")
PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j ->
val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5))
}, o.optString("group"))
}
}
private fun local(ms: Long) = java.time.Instant.ofEpochMilli(ms).atZone(zone)
/** Every channel topping up every six hours for four weeks, each avoiding the others' plans as they stand, as the box does. */
private fun network(programmings: List<ChannelProgramming>, pools: Map<Int, List<PoolSeries>>, start: Map<Int, ChannelPlan>, from: Long): Map<Int, List<ScheduleEntry>> {
val current = start.toMutableMap()
val all = start.mapValues { it.value.entries.toMutableList() }
var now = from
while (now < from + 28 * day) {
for (p in programmings) {
val plan = current[p.number] ?: continue
val others = clashesWith(current.filterKeys { it != p.number }.values.toList())
current[p.number] = topUpPlan(plan, plan.tail, pools.getValue(p.number), now, p.filmRestMs, p.finishTogether, p.dayParts, zone, others,
shuffle = p.shuffleEpisodes, mixed = p::mixes, weightOf = p.tierWeights?.let { p::weightOf }) ?: plan
current.getValue(p.number).entries.filter { e -> all.getValue(p.number).none { it.startMs == e.startMs } }.forEach { all.getValue(p.number) += it }
}
now += 6 * hour
}
return all.mapValues { (_, es) -> es.sortedBy { it.startMs }.filter { it.startMs < from + 28 * day } }
}
@Test fun figures() {
assumeTrue(dir != null && dir.isDirectory)
val out = StringBuilder("Editorial corrections: read-only figures from copies of the box's files taken 4 November 2026 00:40.\n\n")
val channels = SmartChannels.filter { File(dir, "schedule-${it.number}.json").exists() && File(dir, "episodes-${it.number}.json").exists() }
val pools = channels.associate { it.number to pool(File(dir, "episodes-${it.number}.json")) }
val plans = channels.associate { it.number to plan(File(dir, "schedule-${it.number}.json")) } +
(if (File(dir, "schedule-$DRIVE_IN_NUMBER.json").exists()) mapOf(DRIVE_IN_NUMBER to plan(File(dir, "schedule-$DRIVE_IN_NUMBER.json"))) else emptyMap())
val from = plans.values.minOf { it.entries.first().startMs } + SCHEDULE_KEEP_PAST_MS
val names = channels.associate { it.number to it.name } + (DRIVE_IN_NUMBER to "Drive-In")
// 2. The same title on two channels at once: in the committed plans, and in four weeks of new bookings.
val run = network(channels, pools, plans, from)
fun title(e: ScheduleEntry) = seriesKey(e.media.item.title.substringBefore(" / "))
val airings = run.flatMap { (n, es) -> es.map { n to it } }.groupBy { title(it.second) }
val committedStarts = plans.mapValues { (_, p) -> p.entries.map { it.startMs }.toSet() }
val clashes = airings.flatMap { (_, list) -> list.flatMapIndexed { i, a -> list.drop(i + 1).filter { b -> a.first != b.first && a.second.startMs < b.second.endMs && b.second.startMs < a.second.endMs }.map { a to it } } }
out.appendLine("== 2. The same title on two channels at once (four weeks, all channels, as the box tops up)")
out.appendLine(" ${clashes.size} overlaps; ${clashes.count { (a, b) -> a.second.startMs in committedStarts.getValue(a.first) && b.second.startMs in committedStarts.getValue(b.first) }} between two committed bookings, " +
"${clashes.count { (a, b) -> (a.second.startMs in committedStarts.getValue(a.first)) != (b.second.startMs in committedStarts.getValue(b.first)) }} between a committed and a new one, " +
"${clashes.count { (a, b) -> a.second.startMs !in committedStarts.getValue(a.first) && b.second.startMs !in committedStarts.getValue(b.first) }} between two new ones")
clashes.sortedBy { it.first.second.startMs }.forEach { (a, b) ->
fun d(x: Pair<Int, ScheduleEntry>) = "${names[x.first]} ${local(x.second.startMs).toLocalDateTime().withSecond(0).withNano(0)}${if (x.second.startMs in committedStarts.getValue(x.first)) " (committed)" else ""} [${x.second.why.take(90)}]"
out.appendLine(" ${a.second.media.item.title.substringBefore(" / ").take(40)}: ${d(a)} / ${d(b)}")
}
// Titles in more than one film channel's pool: the ones that can clash.
val filmPools = channels.filter { it.filmRestMs != null }
val shared = filmPools.flatMap { p -> pools.getValue(p.number).filter { it.isFilm }.map { seriesKey(it.title) to p.number } }.groupBy({ it.first }, { it.second }).filterValues { it.size > 1 }
out.appendLine(" films in more than one film channel's pool: ${shared.size}")
out.appendLine()
// 3. Ring X weeknights: when the night's flagship starts, today and with the weeknights on time.
val ring = channels.firstOrNull { it.number == 401 }
if (ring != null) {
out.appendLine("== 3. Ring X weeknights, 18:00 Monday to Saturday: how late the night starts")
val onTime = ring.copy(dayParts = ring.dayParts.map { if (it.days.size == 1 && it.fromHour == 18) it.copy(onTime = true) else it })
for ((label, p) in listOf("Today" to ring, "Weeknights on time" to onTime)) {
val es = network(listOf(p), pools, mapOf(401 to plans.getValue(401)), from).getValue(401).filter { it.startMs >= plans.getValue(401).endMs }
val lates = es.filter { val l = local(it.startMs); l.hour in 18..19 && "event 18-23" in it.why }.groupBy { local(it.startMs).toLocalDate() }
.map { (date, x) -> date to (x.minOf { it.startMs } - date.atTime(18, 0).atZone(zone).toInstant().toEpochMilli()) / 60_000 }.sortedBy { it.first }
out.appendLine(" $label: ${lates.size} nights; started late by " + lates.joinToString { "${it.first.dayOfWeek.name.take(3)} ${it.second} min" })
if (lates.isNotEmpty()) out.appendLine(" median ${lates.map { it.second }.sorted()[lates.size / 2]} min, worst ${lates.maxOf { it.second }} min, within 10 minutes ${lates.count { it.second <= 10 }} of ${lates.size}")
val gaps = es.zipWithNext().count { (a, b) -> a.endMs != b.startMs }
out.appendLine(" gaps $gaps; daytime programmes chosen to finish in time: ${es.count { "finish before the appointment" in it.why }}")
}
out.appendLine()
}
// 4. Listed titles the library didn't match, per channel.
out.appendLine("== 4. Titles on a channel's list with no match in its pool (exact name, no substitution)")
for (p in channels.sortedBy { it.number }) {
val keys = pools.getValue(p.number).map { seriesKey(it.title) }.toSet() + pools.getValue(p.number).map { seriesKey(FilmIdentity.of(it.title).title) }
val missing = p.searches.filter { seriesKey(it) !in keys && seriesKey(FilmIdentity.of(it).title) !in keys }
if (missing.isNotEmpty()) out.appendLine(" ${p.number} ${p.name}: ${missing.size} of ${p.searches.size} unmatched: ${missing.joinToString("; ")}")
}
out.appendLine()
// 5. Film rest: how each film channel keeps its 7 days.
out.appendLine("== 5. Film channels: pool, how long the pool lasts, and how the 7-day rest is kept (four weeks of new bookings)")
for (p in filmPools.sortedBy { it.number }) {
val es = run.getValue(p.number).filter { it.startMs >= plans.getValue(p.number).endMs && it.media.item.type == "Movie" }
if (es.isEmpty()) continue
val films = pools.getValue(p.number).filter { it.isFilm }
val hoursOfFilm = films.sumOf { it.episodes.first().durationMs } / hour.toDouble()
val gaps = es.groupBy { it.media.item.id }.values.flatMap { x -> x.zipWithNext().map { (a, b) -> (b.startMs - a.startMs) / day.toDouble() } }.sorted()
val fallbacks = es.count { "no film past its rest" in it.why }
out.appendLine(" ${p.number} ${p.name}: ${films.size} films, ${"%.0f".format(hoursOfFilm)} h of film (${"%.1f".format(hoursOfFilm / 24)} days back to back); " +
"${es.size} screenings, ${es.map { it.media.item.id }.distinct().size} different; early returns (rest not kept) $fallbacks; " +
(if (gaps.isNotEmpty()) "repeat gap median ${"%.1f".format(gaps[gaps.size / 2])} d, shortest ${"%.1f".format(gaps.first())} d" else "no repeats"))
}
File(dir, "editorial-corrections.txt").writeText(out.toString())
println(out)
}
}