diff --git a/ErsatzTV.Core.Tests/Scheduling/ContentEnumeratorBuilderTests.cs b/ErsatzTV.Core.Tests/Scheduling/ContentEnumeratorBuilderTests.cs
index 780bfde41..7f336b8d8 100644
--- a/ErsatzTV.Core.Tests/Scheduling/ContentEnumeratorBuilderTests.cs
+++ b/ErsatzTV.Core.Tests/Scheduling/ContentEnumeratorBuilderTests.cs
@@ -14,8 +14,10 @@ namespace ErsatzTV.Core.Tests.Scheduling;
// different algorithm keyed on the same PlaybackOrder), and
// - every order the two engines don't support returns None, so each caller logs its own #70 warning
// instead of silently scheduling nothing.
-// The Scripted engine has no golden (its external-process/HTTP transport is integration-only, #563), so
-// this direct helper test is the in-process regression net for the shared construction it drives.
+// The Scripted engine has no golden: its external-process/HTTP transport is permanently outside the
+// automated suite, and the engine behind it is covered in-process instead (decision
+// testing.scripted-engine-in-process-net, docs/testing.md -> "Scripted playout coverage"). This direct
+// helper test is the regression net for the shared construction that engine drives.
[TestFixture]
public class ContentEnumeratorBuilderTests
{
diff --git a/ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs b/ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs
index 071a215a0..6a892aa40 100644
--- a/ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs
+++ b/ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs
@@ -1,23 +1,50 @@
using ErsatzTV.Core.Domain;
+using ErsatzTV.Core.Domain.Filler;
+using ErsatzTV.Core.Domain.Scheduling;
using ErsatzTV.Core.Interfaces.Repositories;
+using ErsatzTV.Core.Scheduling;
using ErsatzTV.Core.Scheduling.Engine;
using Microsoft.Extensions.Logging;
using NSubstitute;
using NUnit.Framework;
+using Shouldly;
namespace ErsatzTV.Core.Tests.Scheduling.Engine;
+///
+/// Characterization of the build API — the surface a scripted schedule
+/// drives, one method per ScriptedScheduleController action. Covers content registration
+/// (AddCollection), the scheduling instructions (AddCount, AddAll,
+/// AddDuration, PadUntilExact), EPG grouping, per-item history, the no-progress halt, and
+/// the anchor round-trip that a Continue build restores from.
+///
+/// Deliberately out of scope here: the Cli.Wrap launch of the user-authored script process
+/// (exit code, timeout, stdout capture) and the Kestrel/HTTP/auth transport it calls back over. Those
+/// are permanently outside the automated suite; the controller adapter that sits between them and this
+/// engine is pinned by ErsatzTV.Tests/Controllers/ScriptedScheduleControllerTests. Decision:
+/// testing.scripted-engine-in-process-net.
+///
+///
+/// Every fixture here is timezone-independent by construction: it uses only Chronological order plus
+/// AddCount/AddAll/AddDuration/PadUntilExact, all of which preserve the
+/// instant. WaitUntil(TimeOnly) and PadUntil(string) read the LOCAL day and time-of-day
+/// and are therefore excluded. See docs/testing.md → Timezone independence.
+///
+///
[TestFixture]
public class SchedulingEngineTests
{
+ private const string ContentKey = "content";
+ private const string CollectionName = "Test Collection";
+
+ // Pinned build window, offset zero: the engine writes PlayoutItem.Start/Finish as UtcDateTime, so every
+ // assertion below is on an instant rather than a wall-clock reading.
+ private static readonly DateTimeOffset Start = new(2026, 1, 15, 6, 0, 0, TimeSpan.Zero);
+
[Test]
public void Continue_Across_Time_Change()
{
- var engine = new SchedulingEngine(
- Substitute.For(),
- Substitute.For(),
- Substitute.For(),
- Substitute.For>());
+ SchedulingEngine engine = NewEngine(Substitute.For());
var anchor = new PlayoutAnchor
{
@@ -25,11 +52,468 @@ public class SchedulingEngineTests
};
var start = new DateTimeOffset(new DateTime(2025, 11, 20), TimeSpan.FromHours(-6));
- var finish = start.AddDays(1);
+ DateTimeOffset finish = start.AddDays(1);
engine.BuildBetween(start, finish);
// should not throw
engine.RestoreOrReset(anchor);
}
+
+ [Test]
+ public async Task AddCollection_Then_AddCount_Lays_Items_Back_To_Back()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddCount(ContentKey, 4, Option.None, null, false).ShouldBeTrue();
+
+ List items = engine.GetState().AddedItems;
+ items.Count.ShouldBe(4);
+
+ // chronological order is the collection's release-date order, which is item id order here
+ items.Select(i => i.MediaItemId).ShouldBe([1, 2, 3, 4]);
+
+ items[0].Start.ShouldBe(Start.UtcDateTime);
+ for (var i = 1; i < items.Count; i++)
+ {
+ items[i].Start.ShouldBe(items[i - 1].Finish);
+ }
+
+ foreach (PlayoutItem item in items)
+ {
+ item.FillerKind.ShouldBe(FillerKind.None);
+ item.InPoint.ShouldBe(TimeSpan.Zero);
+ item.OutPoint.ShouldBe(item.Finish - item.Start);
+ item.PlayoutId.ShouldBe(1);
+ }
+
+ // outside an EPG group every item opens its own guide group
+ items.Select(i => i.GuideGroup).ShouldBe([1, 2, 3, 4]);
+
+ // 30 + 45 + 60 + 20 minutes of content
+ TimeSpan scheduled = TimeSpan.FromMinutes(155);
+ items[^1].Finish.ShouldBe(Start.UtcDateTime + scheduled);
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(Start + scheduled);
+ }
+
+ [Test]
+ public async Task AddAll_Schedules_Every_Item_Once()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddAll(ContentKey, Option.None, null, false).ShouldBeTrue();
+
+ List items = engine.GetState().AddedItems;
+ items.Select(i => i.MediaItemId).ShouldBe([1, 2, 3, 4, 5, 6]);
+
+ // 30 + 45 + 60 + 20 + 90 + 15 minutes
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(Start + TimeSpan.FromMinutes(260));
+ }
+
+ [Test]
+ public async Task AddDuration_Stops_Before_Overrunning_The_Target()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddDuration(
+ ContentKey,
+ "2:00:00",
+ fallback: null,
+ trim: false,
+ discardAttempts: 0,
+ stopBeforeEnd: true,
+ offlineTail: false,
+ Option.None,
+ customTitle: null,
+ disableWatermarks: false)
+ .ShouldBeTrue();
+
+ DateTimeOffset target = Start.AddHours(2);
+ List items = engine.GetState().AddedItems;
+
+ // 30 + 45 fits; the third item (60) does not, and nothing is trimmed
+ items.Select(i => i.MediaItemId).ShouldBe([1, 2]);
+ items[^1].Finish.ShouldBe(Start.UtcDateTime + TimeSpan.FromMinutes(75));
+ items[^1].Finish.ShouldBeLessThan(target.UtcDateTime);
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(Start + TimeSpan.FromMinutes(75));
+ }
+
+ [Test]
+ public async Task AddDuration_Trims_The_Last_Item_When_Trim_Is_Set()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddDuration(
+ ContentKey,
+ "2:00:00",
+ fallback: null,
+ trim: true,
+ discardAttempts: 0,
+ stopBeforeEnd: true,
+ offlineTail: false,
+ Option.None,
+ customTitle: null,
+ disableWatermarks: false)
+ .ShouldBeTrue();
+
+ DateTimeOffset target = Start.AddHours(2);
+ List items = engine.GetState().AddedItems;
+
+ items.Select(i => i.MediaItemId).ShouldBe([1, 2, 3]);
+ items[^1].Finish.ShouldBe(target.UtcDateTime);
+ items[^1].OutPoint.ShouldBe(items[^1].Finish - items[^1].Start);
+ items[^1].OutPoint.ShouldBe(TimeSpan.FromMinutes(45));
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(target);
+ }
+
+ [Test]
+ public async Task PadUntilExact_Fills_To_The_Target_Instant()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ DateTimeOffset target = Start.AddHours(2);
+
+ engine.PadUntilExact(
+ ContentKey,
+ target,
+ fallback: null,
+ trim: true,
+ discardAttempts: 0,
+ stopBeforeEnd: true,
+ offlineTail: false,
+ Option.None,
+ customTitle: null,
+ disableWatermarks: false)
+ .ShouldBeTrue();
+
+ List items = engine.GetState().AddedItems;
+ items.Count.ShouldBeGreaterThan(0);
+ items[0].Start.ShouldBe(Start.UtcDateTime);
+ items[^1].Finish.ShouldBe(target.UtcDateTime);
+
+ // the target is an instant, so a machine-local offset must not move it
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(target);
+ }
+
+ [Test]
+ public async Task AddDuration_Rejects_An_Unparseable_Duration()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddDuration(
+ ContentKey,
+ "not-a-duration",
+ fallback: null,
+ trim: false,
+ discardAttempts: 0,
+ stopBeforeEnd: true,
+ offlineTail: false,
+ Option.None,
+ customTitle: null,
+ disableWatermarks: false)
+ .ShouldBeFalse();
+
+ engine.GetState().AddedItems.ShouldBeEmpty();
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(Start);
+ }
+
+ [Test]
+ public async Task AddDuration_Rejects_Offline_Tail_Without_Stop_Before_End()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddDuration(
+ ContentKey,
+ "2:00:00",
+ fallback: null,
+ trim: false,
+ discardAttempts: 0,
+ stopBeforeEnd: false,
+ offlineTail: true,
+ Option.None,
+ customTitle: null,
+ disableWatermarks: false)
+ .ShouldBeFalse();
+
+ engine.GetState().AddedItems.ShouldBeEmpty();
+ }
+
+ [TestCase("add_all")]
+ [TestCase("add_count")]
+ [TestCase("add_duration")]
+ [TestCase("pad_to_next")]
+ [TestCase("pad_until")]
+ [TestCase("pad_until_exact")]
+ public async Task Unknown_Content_Key_Returns_False_And_Schedules_Nothing(string instruction)
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ const string Unknown = "no-such-key";
+
+ bool result = instruction switch
+ {
+ "add_all" => engine.AddAll(Unknown, Option.None, null, false),
+ "add_count" => engine.AddCount(Unknown, 1, Option.None, null, false),
+ "add_duration" => engine.AddDuration(
+ Unknown,
+ "1:00:00",
+ null,
+ false,
+ 0,
+ true,
+ false,
+ Option.None,
+ null,
+ false),
+ "pad_to_next" => engine.PadToNext(
+ Unknown,
+ 15,
+ null,
+ false,
+ 0,
+ true,
+ false,
+ Option.None,
+ null,
+ false),
+ "pad_until" => engine.PadUntil(
+ Unknown,
+ "07:00",
+ false,
+ null,
+ false,
+ 0,
+ true,
+ false,
+ Option.None,
+ null,
+ false),
+ "pad_until_exact" => engine.PadUntilExact(
+ Unknown,
+ Start.AddHours(1),
+ null,
+ false,
+ 0,
+ true,
+ false,
+ Option.None,
+ null,
+ false),
+ _ => throw new ArgumentOutOfRangeException(nameof(instruction))
+ };
+
+ result.ShouldBeFalse();
+
+ // the false is only meaningful if nothing was scheduled behind it
+ engine.GetState().AddedItems.ShouldBeEmpty();
+ engine.GetState().CurrentTime.ToUniversalTime().ShouldBe(Start);
+ }
+
+ [Test]
+ public async Task Empty_Collection_Is_Skipped()
+ {
+ var repository = Substitute.For();
+ repository.GetCollectionItemsByName(CollectionName, Arg.Any())
+ .Returns(new List());
+
+ SchedulingEngine engine = ResetEngine(repository);
+ await engine.AddCollection(ContentKey, CollectionName, PlaybackOrder.Chronological, CancellationToken.None);
+
+ engine.AddCount(ContentKey, 1, Option.None, null, false).ShouldBeFalse();
+ engine.GetState().AddedItems.ShouldBeEmpty();
+ }
+
+ [Test]
+ public async Task Filler_Kind_And_Custom_Title_Reach_The_Item()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddCount(ContentKey, 1, FillerKind.PreRoll, "Bumper", true).ShouldBeTrue();
+
+ PlayoutItem item = engine.GetState().AddedItems.Single();
+ item.FillerKind.ShouldBe(FillerKind.PreRoll);
+ item.CustomTitle.ShouldBe("Bumper");
+ item.DisableWatermarks.ShouldBeTrue();
+ }
+
+ [Test]
+ public async Task Guide_Group_Is_Locked_Across_An_Epg_Group()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.LockGuideGroup(advance: true, customTitle: "Block");
+ engine.AddCount(ContentKey, 3, Option.None, null, false).ShouldBeTrue();
+ engine.UnlockGuideGroup();
+ engine.AddCount(ContentKey, 1, Option.None, null, false).ShouldBeTrue();
+
+ List items = engine.GetState().AddedItems;
+ items.Count.ShouldBe(4);
+
+ List grouped = items.Take(3).ToList();
+ grouped.Select(i => i.GuideGroup).Distinct().Count().ShouldBe(1);
+ grouped.ShouldAllBe(i => i.CustomTitle == "Block");
+
+ // unlocking resumes per-item advancement from the group's number
+ items[3].GuideGroup.ShouldBe(grouped[0].GuideGroup + 1);
+ items[3].CustomTitle.ShouldBeNull();
+ }
+
+ [Test]
+ public async Task History_Is_Recorded_Per_Item()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+
+ engine.AddCount(ContentKey, 3, Option.None, null, false).ShouldBeTrue();
+
+ List items = engine.GetState().AddedItems;
+ List history = engine.GetState().AddedHistory;
+
+ history.Count.ShouldBe(items.Count);
+
+ string expectedKey = HistoryDetails.KeyForSchedulingContent(ContentKey, PlaybackOrder.Chronological);
+ for (var i = 0; i < history.Count; i++)
+ {
+ history[i].Key.ShouldBe(expectedKey);
+ history[i].PlayoutId.ShouldBe(1);
+ history[i].PlaybackOrder.ShouldBe(PlaybackOrder.Chronological);
+ history[i].Index.ShouldBe(i);
+ history[i].When.ShouldBe(items[i].Start);
+ history[i].Finish.ShouldBe(items[i].Finish);
+ }
+ }
+
+ [Test]
+ public void Is_Done_Throws_After_Twenty_Consecutive_Calls_Without_Progress()
+ {
+ SchedulingEngine engine = ResetEngine(Substitute.For());
+ ISchedulingEngineState state = engine.GetState();
+
+ // the first read establishes the baseline; each of the next 19 increments the no-progress counter
+ for (var i = 0; i < 20; i++)
+ {
+ state.IsDone.ShouldBeFalse();
+ }
+
+ Should.Throw(() => _ = state.IsDone);
+ }
+
+ [Test]
+ public async Task Is_Done_Counter_Resets_When_Time_Advances()
+ {
+ SchedulingEngine engine = await ResetEngineWithCollection();
+ ISchedulingEngineState state = engine.GetState();
+
+ for (var i = 0; i < 20; i++)
+ {
+ state.IsDone.ShouldBeFalse();
+ }
+
+ // one instruction that advances CurrentTime clears the counter, so the budget starts over
+ engine.AddCount(ContentKey, 1, Option.None, null, false).ShouldBeTrue();
+
+ for (var i = 0; i < 20; i++)
+ {
+ state.IsDone.ShouldBeFalse();
+ }
+ }
+
+ [Test]
+ public async Task Anchor_Round_Trips_Through_Restore()
+ {
+ SchedulingEngine first = await ResetEngineWithCollection();
+ first.AddCount(ContentKey, 2, Option.None, null, false).ShouldBeTrue();
+
+ List firstItems = first.GetState().AddedItems;
+ int lastGuideGroup = firstItems[^1].GuideGroup;
+
+ PlayoutAnchor anchor = first.GetAnchor();
+ anchor.NextStart.ShouldBe(firstItems[^1].Finish);
+
+ SchedulingEngine second = NewEngine(CollectionRepository());
+ second.WithPlayoutId(1)
+ .WithMode(PlayoutBuildMode.Continue)
+ .WithSeed(0)
+ .BuildBetween(Start, Start.AddDays(1))
+ .WithReferenceData(EmptyReferenceData())
+ .RestoreOrReset(anchor);
+
+ // the anchor carries an instant, not a wall-clock reading
+ second.GetState().CurrentTime.ToUniversalTime().ShouldBe(new DateTimeOffset(anchor.NextStart, TimeSpan.Zero));
+
+ await second.AddCollection(ContentKey, CollectionName, PlaybackOrder.Chronological, CancellationToken.None);
+ second.AddCount(ContentKey, 1, Option.None, null, false).ShouldBeTrue();
+
+ PlayoutItem resumed = second.GetState().AddedItems.Single();
+ resumed.Start.ShouldBe(anchor.NextStart);
+
+ // the guide group continues from the serialized context instead of restarting at 1
+ resumed.GuideGroup.ShouldBe(lastGuideGroup + 1);
+ }
+
+ private static SchedulingEngine NewEngine(IMediaCollectionRepository repository) =>
+ new(
+ repository,
+ Substitute.For(),
+ Substitute.For(),
+ Substitute.For>());
+
+ // WithReferenceData must precede RestoreOrReset and AddCollection: both dereference
+ // PlayoutReferenceData.PlayoutHistory, so a different order fails with a null reference that reads
+ // like an engine bug. This is the same order ScriptedPlayoutBuilder uses.
+ private static SchedulingEngine ResetEngine(IMediaCollectionRepository repository)
+ {
+ SchedulingEngine engine = NewEngine(repository);
+ engine.WithPlayoutId(1)
+ .WithMode(PlayoutBuildMode.Reset)
+ .WithSeed(0)
+ .BuildBetween(Start, Start.AddDays(1))
+ .WithReferenceData(EmptyReferenceData())
+ .RestoreOrReset(Option.None);
+ return engine;
+ }
+
+ private static async Task ResetEngineWithCollection()
+ {
+ SchedulingEngine engine = ResetEngine(CollectionRepository());
+ await engine.AddCollection(ContentKey, CollectionName, PlaybackOrder.Chronological, CancellationToken.None);
+ return engine;
+ }
+
+ private static IMediaCollectionRepository CollectionRepository()
+ {
+ var repository = Substitute.For();
+ repository.GetCollectionItemsByName(CollectionName, Arg.Any())
+ .Returns(_ => TestCollection());
+ return repository;
+ }
+
+ // Distinct release dates make chronological order deterministic (id order); distinct durations make
+ // every boundary in an assertion unambiguous.
+ private static List TestCollection() =>
+ [
+ FakeMovie(1, 30),
+ FakeMovie(2, 45),
+ FakeMovie(3, 60),
+ FakeMovie(4, 20),
+ FakeMovie(5, 90),
+ FakeMovie(6, 15)
+ ];
+
+ private static Movie FakeMovie(int id, int minutes) =>
+ new()
+ {
+ Id = id,
+ MediaVersions = [new MediaVersion { Duration = TimeSpan.FromMinutes(minutes) }],
+ MovieMetadata =
+ [
+ new MovieMetadata
+ {
+ Title = $"Movie {id:D2}",
+ ReleaseDate = new DateTime(2005, 1, 1).AddDays(id)
+ }
+ ]
+ };
+
+ private static PlayoutReferenceData EmptyReferenceData() =>
+ new(null, Option.None, [], [], null, [], [], TimeSpan.Zero);
}
diff --git a/ErsatzTV.Tests/Controllers/Fixtures/scripted-build.json b/ErsatzTV.Tests/Controllers/Fixtures/scripted-build.json
new file mode 100644
index 000000000..c5be103cb
--- /dev/null
+++ b/ErsatzTV.Tests/Controllers/Fixtures/scripted-build.json
@@ -0,0 +1,52 @@
+{
+ "description": "Committed stand-in for a user-authored scripted schedule: the ordered sequence of calls such a script makes against /api/v1/scripted/playout/build/{buildId}, replayed through the real ScriptedScheduleController by ScriptedScheduleControllerTests. Field names and casing match what the HTTP body binder accepts \u2014 the replay deserializes each body with ApiJsonSettings, the configuration Startup applies to AddNewtonsoftJson. Deliberately avoids wait_until / pad_until / pad_to_next (local day and time-of-day) and shuffle order, which would make the pinned snapshot machine-timezone- or seed-dependent. add_duration and pad_until_exact both end BETWEEN two content boundaries on purpose: an instruction that happens to end on one never reaches the engine's trim branch, and its trim flag is then witnessed by nothing.",
+ "script": [
+ {
+ "action": "add_collection",
+ "body": {
+ "key": "content",
+ "collection": "Test Collection",
+ "order": "chronological"
+ }
+ },
+ {
+ "action": "start_epg_group",
+ "body": {
+ "advance": true,
+ "customTitle": "Morning Block"
+ }
+ },
+ {
+ "action": "add_count",
+ "body": {
+ "content": "content",
+ "count": 2
+ }
+ },
+ {
+ "action": "stop_epg_group"
+ },
+ {
+ "action": "add_duration",
+ "body": {
+ "content": "content",
+ "duration": "2:00:00",
+ "trim": true
+ }
+ },
+ {
+ "action": "pad_until_exact",
+ "body": {
+ "content": "content",
+ "when": "2026-01-15T09:55:00+00:00",
+ "trim": true
+ }
+ },
+ {
+ "action": "add_all",
+ "body": {
+ "content": "content"
+ }
+ }
+ ]
+}
diff --git a/ErsatzTV.Tests/Controllers/OpenApiSerializerContractTests.cs b/ErsatzTV.Tests/Controllers/OpenApiSerializerContractTests.cs
index 366391b9e..684c3b48b 100644
--- a/ErsatzTV.Tests/Controllers/OpenApiSerializerContractTests.cs
+++ b/ErsatzTV.Tests/Controllers/OpenApiSerializerContractTests.cs
@@ -24,14 +24,13 @@ namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class OpenApiSerializerContractTests
{
- // Mirrors Startup.ConfigureServices -> AddNewtonsoftJson exactly.
- private static readonly JsonSerializerSettings RuntimeSettings = new()
- {
- NullValueHandling = NullValueHandling.Ignore,
- ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
- ContractResolver = new CustomContractResolver(),
- Converters = { new StringEnumConverter() }
- };
+ // The configuration Startup.ConfigureServices -> AddNewtonsoftJson applies, from the same function
+ // rather than a hand-copy of it. This fixture is the WRITE-side witness for the naming strategy: the
+ // four cases below assert camelCase keys, which CustomContractResolver produces and a bare
+ // JsonSerializerSettings does not. It says nothing about NullValueHandling (every DTO member below is
+ // populated, so nothing is dropped either way) or the StringEnumConverter (it compares key NAMES, not
+ // values). docs/testing.md -> "Scripted playout coverage" tabulates which suite witnesses which half.
+ private static readonly JsonSerializerSettings RuntimeSettings = ApiJsonSettings.Create();
private static IEnumerable Cases()
{
diff --git a/ErsatzTV.Tests/Controllers/ScriptedScheduleControllerTests.cs b/ErsatzTV.Tests/Controllers/ScriptedScheduleControllerTests.cs
new file mode 100644
index 000000000..802f2505b
--- /dev/null
+++ b/ErsatzTV.Tests/Controllers/ScriptedScheduleControllerTests.cs
@@ -0,0 +1,464 @@
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Text.Json;
+using ErsatzTV.Controllers.Api;
+using ErsatzTV.Core.Api.ScriptedPlayout;
+using ErsatzTV.Core.Domain;
+using ErsatzTV.Core.Domain.Filler;
+using ErsatzTV.Core.Domain.Scheduling;
+using ErsatzTV.Core.Interfaces.Repositories;
+using ErsatzTV.Core.Scheduling;
+using ErsatzTV.Core.Scheduling.Engine;
+using ErsatzTV.Core.Scheduling.ScriptedScheduling;
+using ErsatzTV.Serialization;
+using LanguageExt;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json;
+using NSubstitute;
+using NUnit.Framework;
+using Shouldly;
+
+namespace ErsatzTV.Tests.Controllers;
+
+///
+/// In-process stand-in for a scripted playout build (ersatztv#563). A committed script fixture
+/// (Fixtures/scripted-build.json) is replayed through the REAL
+/// , the REAL and the
+/// REAL , and the resulting PlayoutItems are compared to a pinned
+/// snapshot in the same line format the playout goldens use. The engine is registered under a fixed build
+/// id via , the seam that exists for exactly this.
+///
+/// The hops this cannot host, named rather than implied: the Cli.Wrap launch of the user's
+/// own program (exit code, timeout, stdout capture); the Kestrel/middleware/auth transport the
+/// program calls back over; and MVC's binding wrapper — the input formatter's content-type
+/// selection and malformed-body handling, model validation (a non-nullable reference type picks
+/// up an implicit required check there), and the [ApiController] automatic 400 either
+/// produces before an action runs, since every test here hands an action an already-bound object.
+/// The serializer inside that wrapper is not residue: request bodies are deserialized with
+/// , the same function Startup hands to AddNewtonsoftJson.
+/// It is the production configuration, not the production object — MVC applies it to
+/// settings it has already configured, and ApiJsonSettings.Create() starts from a bare one, so
+/// MVC's stricter MaxDepth and its two ProblemDetails converters are missing here
+/// (enumerated and pinned by ApiJsonSettingsTests; both inert for these DTOs, which nest two
+/// levels and are never a ProblemDetails). Two tests hold the two ways that binder can be
+/// replaced, since the fixture's own bodies parse identically under all of them:
+/// against a System.Text.Json swap, and
+/// against a
+/// plain Newtonsoft settings object. What no test here observes is Startup's own
+/// registration — removes the duplicate rather than detecting
+/// drift in one. The reasoning for the scope-out is in docs/testing.md → "Scripted playout
+/// coverage" and the decision record testing.scripted-engine-in-process-net.
+///
+///
+/// Deviation from the three golden-file nets (docs/contributing.md §10): the expected output is a
+/// string constant in this file rather than a committed golden. The golden harness lives in
+/// ErsatzTV.Core.Tests, which cannot reference a controller, and duplicating it here would
+/// create a second action-to-engine mapping — the thing this design exists to avoid.
+///
+///
+[TestFixture]
+public class ScriptedScheduleControllerTests
+{
+ private const string ContentKey = "content";
+ private const string CollectionName = "Test Collection";
+
+ private static readonly Guid BuildId = Guid.Parse("00000000-0000-0000-0000-000000000563");
+ private static readonly DateTimeOffset Start = new(2026, 1, 15, 6, 0, 0, TimeSpan.Zero);
+
+ // What Startup hands to AddNewtonsoftJson, from the same function rather than a hand-copy of it.
+ // The two Production_Body_Binder_* tests below are what hold this to the production configuration.
+ private static readonly JsonSerializerSettings BodyBinderSettings = ApiJsonSettings.Create();
+
+ // A body that omits the `required` member "collection"; Newtonsoft and System.Text.Json disagree.
+ private const string BodyMissingRequiredMember = """{"key":"content","order":"chronological"}""";
+
+ // A body sending "order" as an explicit null. NullValueHandling.Ignore keeps the DTO's declared
+ // default; Newtonsoft's own default (Include) overwrites it with null.
+ private const string BodyWithExplicitNullOrder =
+ """{"key":"content","collection":"Test Collection","order":null}""";
+
+ // Every action the fixture is expected to exercise. A fixture edit that drops one must fail loudly
+ // rather than quietly shrinking what the snapshot covers.
+ private static readonly string[] ExpectedActions =
+ [
+ "add_collection",
+ "start_epg_group",
+ "add_count",
+ "stop_epg_group",
+ "add_duration",
+ "pad_until_exact",
+ "add_all"
+ ];
+
+ // Raw UTC Start/Finish (never the *Offset properties, which localize), FillerKind, and the item's
+ // MediaItemId rendered as "Movie NN" — a label built from the id, not a lookup of the seeded title.
+ //
+ // 004 and 006 are the two trimmed items, and they are the reason the fixture's numbers look arbitrary.
+ // Movie 05 (90m) starts at 08:35 inside a two-hour add_duration ending 09:15, and pad_until_exact
+ // targets 09:55, which Movie 01 (30m) would overshoot from 09:30. Land either target on a content
+ // boundary instead and the trim branch never runs, leaving that action's `trim` argument unwitnessed.
+ private const string ExpectedSnapshot =
+ """
+ 000 | 2026-01-15 06:00:00 - 2026-01-15 06:30:00 | None | Movie 01
+ 001 | 2026-01-15 06:30:00 - 2026-01-15 07:15:00 | None | Movie 02
+ 002 | 2026-01-15 07:15:00 - 2026-01-15 08:15:00 | None | Movie 03
+ 003 | 2026-01-15 08:15:00 - 2026-01-15 08:35:00 | None | Movie 04
+ 004 | 2026-01-15 08:35:00 - 2026-01-15 09:15:00 | None | Movie 05
+ 005 | 2026-01-15 09:15:00 - 2026-01-15 09:30:00 | None | Movie 06
+ 006 | 2026-01-15 09:30:00 - 2026-01-15 09:55:00 | None | Movie 01
+ 007 | 2026-01-15 09:55:00 - 2026-01-15 10:40:00 | None | Movie 02
+ 008 | 2026-01-15 10:40:00 - 2026-01-15 11:40:00 | None | Movie 03
+ 009 | 2026-01-15 11:40:00 - 2026-01-15 12:00:00 | None | Movie 04
+ 010 | 2026-01-15 12:00:00 - 2026-01-15 13:30:00 | None | Movie 05
+ 011 | 2026-01-15 13:30:00 - 2026-01-15 13:45:00 | None | Movie 06
+ 012 | 2026-01-15 13:45:00 - 2026-01-15 14:15:00 | None | Movie 01
+ """;
+
+ [Test]
+ public async Task Committed_Script_Fixture_Produces_The_Pinned_Snapshot()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine engine) = NewSession();
+
+ List replayed = await ReplayFixture(controller);
+ replayed.ShouldBe(ExpectedActions);
+
+ List items = engine.GetState().AddedItems;
+ Snapshot(items).ShouldBe(Canonicalize(ExpectedSnapshot));
+
+ // invariants the snapshot alone does not state, so a regenerated snapshot cannot silently absorb them
+ items.Count.ShouldBe(13);
+ for (var i = 1; i < items.Count; i++)
+ {
+ items[i].Start.ShouldBe(items[i - 1].Finish);
+ }
+
+ // start_epg_group ... stop_epg_group holds one guide group across its items and titles them
+ items[0].GuideGroup.ShouldBe(items[1].GuideGroup);
+ items[2].GuideGroup.ShouldNotBe(items[0].GuideGroup);
+ items[0].CustomTitle.ShouldBe("Morning Block");
+ items[1].CustomTitle.ShouldBe("Morning Block");
+ items[2].CustomTitle.ShouldBeNull();
+
+ // after stop_epg_group every item opens its own guide group again
+ items.Skip(2).Select(i => i.GuideGroup).ShouldBe(Enumerable.Range(2, 11));
+
+ // pad_until_exact lands on the requested instant, whatever the machine offset is, and gets there by
+ // TRIMMING: Movie 01 is 30 minutes and starts at 09:30, so the 25-minute item below is the fixture's
+ // `"trim": true` reaching the engine. Passing `false` for that argument drops the item entirely.
+ items[6].Finish.ShouldBe(new DateTime(2026, 1, 15, 9, 55, 0, DateTimeKind.Utc));
+ (items[6].Finish - items[6].Start).ShouldBe(TimeSpan.FromMinutes(25));
+ items[6].OutPoint.ShouldBe(TimeSpan.FromMinutes(25));
+ }
+
+ [Test]
+ public void Production_Body_Binder_Ignores_Required_Members()
+ {
+ // The replay above is only faithful while Bind uses MVC's own serializer, and "the two agree" is
+ // not a safe assumption to leave unstated: Newtonsoft has no notion of the C# `required` keyword,
+ // so a body omitting one deserializes to a default, where System.Text.Json rejects it outright.
+ // The claim is about the SERIALIZER only — what MVC's validation layer then does with such a
+ // body (non-nullable reference types pick up an implicit required check) is the uncovered
+ // wrapper, not this. Binding through Bind itself is what gives this teeth: the fixture's own
+ // bodies parse identically under either serializer, so only a body like this one separates them.
+ // It separates THAT pair only — a Newtonsoft settings object that has merely lost the production
+ // configuration reads this body exactly as production does, which is the sibling test's subject.
+ using JsonDocument document = JsonDocument.Parse(BodyMissingRequiredMember);
+
+ ContentCollection bound = Bind(document.RootElement).ShouldNotBeNull();
+ bound.Key.ShouldBe(ContentKey);
+ bound.Collection.ShouldBeNull();
+
+ // the negative control: the same body under the serializer a swap would reach for
+ Should.Throw(
+ () => System.Text.Json.JsonSerializer.Deserialize(
+ BodyMissingRequiredMember,
+ new JsonSerializerOptions(JsonSerializerDefaults.Web)));
+ }
+
+ [Test]
+ public async Task Production_Body_Binder_Keeps_Declared_Defaults_Over_An_Explicit_Null()
+ {
+ // The other half of the binder-fidelity claim, and the half that a NEWTONSOFT lookalike witnesses:
+ // production sets NullValueHandling.Ignore, so an explicit `"order": null` leaves ContentCollection
+ // at its declared "shuffle" rather than overwriting it. Newtonsoft's own default is Include, which
+ // writes the null through — and AddCollection's Enum.TryParse then rejects it as a 400. So this is
+ // a behaviour difference a script would see, not a settings-shape assertion — which is what makes
+ // the "shuffle" and the OkResult below assertions about the production configuration itself.
+ (ScriptedScheduleController controller, SchedulingEngine engine) = NewSession();
+
+ using JsonDocument document = JsonDocument.Parse(BodyWithExplicitNullOrder);
+ ContentCollection bound = Bind(document.RootElement).ShouldNotBeNull();
+ bound.Order.ShouldBe("shuffle");
+
+ IActionResult result = await controller.AddCollection(BuildId, bound, CancellationToken.None);
+ result.ShouldBeOfType();
+
+ // and the content is usable, i.e. the surviving default really was a valid playback order
+ engine.AddCount(ContentKey, 1, Option.None, null, false).ShouldBeTrue();
+ }
+
+ [Test]
+ public async Task Unknown_Build_Id_Returns_404()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine _) = NewSession();
+
+ var other = Guid.Parse("00000000-0000-0000-0000-000000000999");
+
+ controller.GetContext(other).Result.ShouldBeOfType();
+
+ IActionResult collection = await controller.AddCollection(
+ other,
+ new ContentCollection { Key = ContentKey, Collection = CollectionName, Order = "chronological" },
+ CancellationToken.None);
+ collection.ShouldBeOfType();
+
+ ActionResult count = controller.AddCount(
+ other,
+ new PlayoutCount { Content = ContentKey, Count = 1 });
+ count.Result.ShouldBeOfType();
+ }
+
+ [Test]
+ public async Task Invalid_Playback_Order_Returns_400()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine engine) = NewSession();
+
+ IActionResult result = await controller.AddCollection(
+ BuildId,
+ new ContentCollection { Key = ContentKey, Collection = CollectionName, Order = "nonsense" },
+ CancellationToken.None);
+
+ result.ShouldBeOfType();
+
+ // the 400 short-circuits before the engine sees the content
+ engine.AddCount(ContentKey, 1, Option.None, null, false).ShouldBeFalse();
+ engine.GetState().AddedItems.ShouldBeEmpty();
+ }
+
+ [Test]
+ public async Task Unknown_Filler_Kind_Falls_Back_To_None()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine engine) = NewSession();
+
+ (await controller.AddCollection(
+ BuildId,
+ new ContentCollection { Key = ContentKey, Collection = CollectionName, Order = "chronological" },
+ CancellationToken.None)).ShouldBeOfType();
+
+ // an unparseable filler_kind is NOT rejected the way an unparseable order is; it degrades to None
+ ActionResult result = controller.AddCount(
+ BuildId,
+ new PlayoutCount { Content = ContentKey, Count = 1, FillerKind = "not-a-filler-kind" });
+
+ result.Result.ShouldBeOfType();
+ engine.GetState().AddedItems.Single().FillerKind.ShouldBe(FillerKind.None);
+ }
+
+ [Test]
+ public async Task Known_Filler_Kind_Reaches_The_Item()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine engine) = NewSession();
+
+ (await controller.AddCollection(
+ BuildId,
+ new ContentCollection { Key = ContentKey, Collection = CollectionName, Order = "chronological" },
+ CancellationToken.None)).ShouldBeOfType();
+
+ controller.AddCount(
+ BuildId,
+ new PlayoutCount { Content = ContentKey, Count = 1, FillerKind = "PreRoll" })
+ .Result.ShouldBeOfType();
+
+ engine.GetState().AddedItems.Single().FillerKind.ShouldBe(FillerKind.PreRoll);
+ }
+
+ [Test]
+ public void No_Progress_Throw_Is_Mapped_To_400()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine _) = NewSession();
+
+ // GetContext reads IsDone, which halts a script that stops advancing time. The engine throws;
+ // the controller must translate that into a 400 rather than letting it escape as a 500.
+ for (var i = 0; i < 20; i++)
+ {
+ controller.GetContext(BuildId).Result.ShouldBeOfType();
+ }
+
+ controller.GetContext(BuildId).Result.ShouldBeOfType();
+ }
+
+ [Test]
+ public void Context_Reports_Start_Finish_And_Current_Time()
+ {
+ (ScriptedScheduleController controller, SchedulingEngine _) = NewSession();
+
+ var ok = controller.GetContext(BuildId).Result.ShouldBeOfType();
+ var context = ok.Value.ShouldBeOfType();
+
+ context.StartTime.ToUniversalTime().ShouldBe(Start);
+ context.FinishTime.ToUniversalTime().ShouldBe(Start.AddHours(12));
+ context.CurrentTime.ToUniversalTime().ShouldBe(Start);
+ context.IsDone.ShouldBeFalse();
+ }
+
+ private static (ScriptedScheduleController Controller, SchedulingEngine Engine) NewSession()
+ {
+ var repository = Substitute.For();
+ repository.GetCollectionItemsByName(CollectionName, Arg.Any())
+ .Returns(_ => TestCollection());
+
+ var engine = new SchedulingEngine(
+ repository,
+ Substitute.For(),
+ Substitute.For(),
+ Substitute.For>());
+
+ // same setup order ScriptedPlayoutBuilder uses; WithReferenceData must precede RestoreOrReset
+ engine.WithPlayoutId(1)
+ .WithMode(PlayoutBuildMode.Reset)
+ .WithSeed(0)
+ .BuildBetween(Start, Start.AddHours(12))
+ .WithReferenceData(new PlayoutReferenceData(null, Option.None, [], [], null, [], [], TimeSpan.Zero))
+ .RestoreOrReset(Option.None);
+
+ // a fresh service per test, so no session leaks between fixtures
+ var service = new ScriptedPlayoutBuilderService();
+ service.MockSession(engine, BuildId).ShouldBeTrue();
+
+ return (new ScriptedScheduleController(service), engine);
+ }
+
+ // Deserializes each fixture entry into the controller's own request DTO and invokes the matching action,
+ // asserting a 200 each time. Returns the actions actually replayed, so the caller can assert coverage.
+ private static async Task> ReplayFixture(ScriptedScheduleController controller)
+ {
+ string json = await File.ReadAllTextAsync(Path.Combine(FixtureDir(), "scripted-build.json"));
+
+ using JsonDocument document = JsonDocument.Parse(json);
+ var replayed = new List();
+
+ foreach (JsonElement entry in document.RootElement.GetProperty("script").EnumerateArray())
+ {
+ string action = entry.GetProperty("action").GetString().ShouldNotBeNull();
+ JsonElement body = entry.TryGetProperty("body", out JsonElement maybeBody) ? maybeBody : default;
+
+ switch (action)
+ {
+ case "add_collection":
+ ShouldBeOk(
+ await controller.AddCollection(
+ BuildId,
+ Bind(body),
+ CancellationToken.None));
+ break;
+ case "start_epg_group":
+ ShouldBeOk(controller.StartEpgGroup(BuildId, Bind(body)));
+ break;
+ case "stop_epg_group":
+ ShouldBeOk(controller.StopEpgGroup(BuildId));
+ break;
+ case "add_count":
+ ShouldBeOkContext(controller.AddCount(BuildId, Bind(body)));
+ break;
+ case "add_all":
+ ShouldBeOkContext(controller.AddAll(BuildId, Bind(body)));
+ break;
+ case "add_duration":
+ ShouldBeOkContext(controller.AddDuration(BuildId, Bind(body)));
+ break;
+ case "pad_until_exact":
+ ShouldBeOkContext(controller.PadUntilExact(BuildId, Bind(body)));
+ break;
+ default:
+ Assert.Fail($"Fixture uses action '{action}', which the replayer does not implement.");
+ break;
+ }
+
+ replayed.Add(action);
+ }
+
+ return replayed;
+ }
+
+ // Deserializes a fixture body with the configuration the production body binder runs
+ // (Startup -> AddNewtonsoftJson -> ApiJsonSettings), so the fixture's field names and casing are
+ // asserted against that serializer rather than a convenient one. Not the identical settings OBJECT:
+ // MVC applies the configuration to its own pre-configured settings, so its stricter MaxDepth and its
+ // two ProblemDetails converters are absent from Create() — ApiJsonSettingsTests enumerates the gap and
+ // shows why neither reaches a request body. The two Production_Body_Binder_* tests, not this helper,
+ // are what make a replacement of the configuration visible.
+ private static T Bind(JsonElement body) where T : class
+ {
+ body.ValueKind.ShouldBe(JsonValueKind.Object);
+ return JsonConvert.DeserializeObject(body.GetRawText(), BodyBinderSettings).ShouldNotBeNull();
+ }
+
+ private static void ShouldBeOk(IActionResult result) => result.ShouldBeOfType();
+
+ private static void ShouldBeOkContext(ActionResult result)
+ {
+ var ok = result.Result.ShouldBeOfType();
+ ok.Value.ShouldBeOfType();
+ }
+
+ // Same line format as PlayoutBuildGoldenTests.Snapshot: ordered by Start then MediaItemId, raw UTC.
+ private static string Snapshot(List items)
+ {
+ List ordered = items
+ .OrderBy(i => i.Start)
+ .ThenBy(i => i.MediaItemId)
+ .ToList();
+
+ var sb = new StringBuilder();
+ for (var index = 0; index < ordered.Count; index++)
+ {
+ PlayoutItem item = ordered[index];
+ sb.Append(index.ToString("D3", CultureInfo.InvariantCulture));
+ sb.Append(" | ");
+ sb.Append(item.Start.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
+ sb.Append(" - ");
+ sb.Append(item.Finish.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
+ sb.Append(" | ");
+ sb.Append(item.FillerKind.ToString());
+ sb.Append(" | ");
+ sb.Append($"Movie {item.MediaItemId:D2}");
+ sb.Append('\n');
+ }
+
+ return sb.ToString();
+ }
+
+ private static string Canonicalize(string text) => text.ReplaceLineEndings("\n").TrimEnd('\n') + "\n";
+
+ private static string FixtureDir([CallerFilePath] string thisFile = "") =>
+ Path.Combine(Path.GetDirectoryName(thisFile) ?? ".", "Fixtures");
+
+ // Distinct release dates make chronological order deterministic (id order); distinct durations make
+ // every boundary in the snapshot unambiguous.
+ private static List TestCollection() =>
+ [
+ FakeMovie(1, 30),
+ FakeMovie(2, 45),
+ FakeMovie(3, 60),
+ FakeMovie(4, 20),
+ FakeMovie(5, 90),
+ FakeMovie(6, 15)
+ ];
+
+ private static Movie FakeMovie(int id, int minutes) =>
+ new()
+ {
+ Id = id,
+ MediaVersions = [new MediaVersion { Duration = TimeSpan.FromMinutes(minutes) }],
+ MovieMetadata =
+ [
+ new MovieMetadata
+ {
+ Title = $"Movie {id:D2}",
+ ReleaseDate = new DateTime(2005, 1, 1).AddDays(id)
+ }
+ ]
+ };
+}
diff --git a/ErsatzTV.Tests/Serialization/ApiJsonSettingsTests.cs b/ErsatzTV.Tests/Serialization/ApiJsonSettingsTests.cs
new file mode 100644
index 000000000..618eb89db
--- /dev/null
+++ b/ErsatzTV.Tests/Serialization/ApiJsonSettingsTests.cs
@@ -0,0 +1,84 @@
+using ErsatzTV.Serialization;
+using Microsoft.AspNetCore.Mvc;
+using Newtonsoft.Json;
+using NUnit.Framework;
+using Shouldly;
+
+namespace ErsatzTV.Tests.Serialization;
+
+///
+/// Pins the gap between the two objects produces:
+/// onto MVC's own settings, which is what the production body binder
+/// runs, and , which tests outside the MVC pipeline
+/// (ScriptedScheduleControllerTests, OpenApiSerializerContractTests) bind and serialize with.
+/// They are not the same object, and the difference belongs in a test rather than in a comment: a prose
+/// claim of parity cannot notice the day it stops being true, and every doc describing the scripted
+/// coverage rests on knowing which parts carry over and which do not.
+///
+[TestFixture]
+public class ApiJsonSettingsTests
+{
+ // The object MVC's options pipeline constructs before Startup's configure delegate runs. Building it
+ // directly rather than hosting the app is the point of the caveat below: this measures the settings
+ // MvcNewtonsoftJsonOptions itself defines, not a fully composed host.
+ private static JsonSerializerSettings Production() =>
+ ApiJsonSettings.Apply(new MvcNewtonsoftJsonOptions().SerializerSettings);
+
+ [Test]
+ public void Apply_Sets_The_Same_Four_Things_On_Either_Object()
+ {
+ JsonSerializerSettings production = Production();
+ JsonSerializerSettings standalone = ApiJsonSettings.Create();
+
+ production.NullValueHandling.ShouldBe(NullValueHandling.Ignore);
+ standalone.NullValueHandling.ShouldBe(NullValueHandling.Ignore);
+
+ production.ReferenceLoopHandling.ShouldBe(ReferenceLoopHandling.Ignore);
+ standalone.ReferenceLoopHandling.ShouldBe(ReferenceLoopHandling.Ignore);
+
+ production.ContractResolver.ShouldBeOfType();
+ standalone.ContractResolver.ShouldBeOfType();
+
+ production.Converters.ShouldContain(c => c is Newtonsoft.Json.Converters.StringEnumConverter);
+ standalone.Converters.ShouldContain(c => c is Newtonsoft.Json.Converters.StringEnumConverter);
+ }
+
+ [Test]
+ public void Standalone_Matches_On_The_Mvc_Defaults_That_Change_How_A_Body_Parses()
+ {
+ JsonSerializerSettings production = Production();
+ JsonSerializerSettings standalone = ApiJsonSettings.Create();
+
+ standalone.MissingMemberHandling.ShouldBe(production.MissingMemberHandling);
+ standalone.TypeNameHandling.ShouldBe(production.TypeNameHandling);
+ standalone.DateParseHandling.ShouldBe(production.DateParseHandling);
+ }
+
+ [Test]
+ public void Standalone_Does_Not_Carry_Mvcs_Depth_Limit_Or_Its_Error_Converters()
+ {
+ JsonSerializerSettings production = Production();
+ JsonSerializerSettings standalone = ApiJsonSettings.Create();
+
+ // MVC clamps the object graph it will consume; a bare settings object keeps Newtonsoft's own limit.
+ // A body deeper than 32 therefore binds here and 400s in production — inert for the scripted request
+ // DTOs, which nest two levels, and the reason no test may generalize from Create() to "production".
+ production.MaxDepth.ShouldBe(32);
+ standalone.MaxDepth.ShouldBe(64);
+
+ // The rest of the delta is MVC's error-response shaping, which no request body reaches.
+ string[] missing = production.Converters
+ .Select(c => c.GetType().Name)
+ .Except(standalone.Converters.Select(c => c.GetType().Name))
+ .Order()
+ .ToArray();
+
+ missing.ShouldBe(["ProblemDetailsConverter", "ValidationProblemDetailsConverter"]);
+
+ // and nothing goes the other way: the standalone object adds nothing production lacks
+ standalone.Converters
+ .Select(c => c.GetType().Name)
+ .Except(production.Converters.Select(c => c.GetType().Name))
+ .ShouldBeEmpty();
+ }
+}
diff --git a/ErsatzTV/Serialization/ApiJsonSettings.cs b/ErsatzTV/Serialization/ApiJsonSettings.cs
new file mode 100644
index 000000000..6406a1499
--- /dev/null
+++ b/ErsatzTV/Serialization/ApiJsonSettings.cs
@@ -0,0 +1,43 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Converters;
+
+namespace ErsatzTV.Serialization;
+
+///
+/// The Newtonsoft settings the MVC JSON formatters read and write `/api/*` bodies with. Defined once,
+/// here, so a test can deserialize a request body exactly the way the production body binder does
+/// instead of mirroring 's registration. This REMOVES the duplicate rather than
+/// detecting drift in one: no test observes Startup.ConfigureServices, and a byte-equal hand-copy
+/// of is behaviourally indistinguishable from calling it. What the tests do
+/// separate is a caller that binds with something else — a body omitting a C#
+/// required member deserializes to a default here where System.Text.Json throws, and
+/// .Ignore keeps a DTO's declared default over an explicit
+/// null where plain Newtonsoft writes the null through. Both are pinned by
+/// ScriptedScheduleControllerTests; the naming strategy is pinned on the write side by
+/// OpenApiSerializerContractTests. See docs/testing.md → "Scripted playout coverage".
+///
+public static class ApiJsonSettings
+{
+ /// Applies the production configuration to an existing settings object (the MVC path).
+ public static JsonSerializerSettings Apply(JsonSerializerSettings settings)
+ {
+ settings.NullValueHandling = NullValueHandling.Ignore;
+ settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
+ settings.ContractResolver = new CustomContractResolver();
+ settings.Converters.Add(new StringEnumConverter());
+ return settings;
+ }
+
+ ///
+ /// onto a bare settings object, for a caller outside the MVC pipeline. It carries
+ /// everything sets and nothing MVC supplies around it, so it is NOT the object the
+ /// body binder runs. Measured 2026-09-05 against new MvcNewtonsoftJsonOptions().SerializerSettings:
+ /// MaxDepth is Newtonsoft's 64 rather than MVC's stricter 32, and MVC's two error-shaping
+ /// converters — ProblemDetailsConverter and ValidationProblemDetailsConverter — are absent.
+ /// MissingMemberHandling, TypeNameHandling and DateParseHandling match. Both gaps are
+ /// inert for the request DTOs the tests bind (two levels deep, never a ProblemDetails), which is why
+ /// this is usable there at all; the delta is pinned by ApiJsonSettingsTests so it cannot decay into
+ /// a parity claim.
+ ///
+ public static JsonSerializerSettings Create() => Apply(new JsonSerializerSettings());
+}
diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs
index 4aa2845c8..be25df792 100644
--- a/ErsatzTV/Startup.cs
+++ b/ErsatzTV/Startup.cs
@@ -104,7 +104,6 @@ using Microsoft.IdentityModel.Tokens;
using Microsoft.IO;
using Microsoft.OpenApi;
using Newtonsoft.Json;
-using Newtonsoft.Json.Converters;
using Refit;
using Scalar.AspNetCore;
using Serilog;
@@ -503,13 +502,9 @@ public class Startup
options.OutputFormatters.Insert(0, new HdhrJsonOutputFormatter());
options.Filters.AddService();
})
- .AddNewtonsoftJson(opt =>
- {
- opt.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
- opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- opt.SerializerSettings.ContractResolver = new CustomContractResolver();
- opt.SerializerSettings.Converters.Add(new StringEnumConverter());
- });
+ // ApiJsonSettings rather than an inline lambda: the request-body binder's semantics are asserted
+ // by ScriptedScheduleControllerTests, which has to configure the SAME object, not a mirror of it.
+ .AddNewtonsoftJson(opt => ApiJsonSettings.Apply(opt.SerializerSettings));
services.AddScoped(_ => new ConditionalIptvAuthorizeFilter("JwtOnlyScheme"));
diff --git a/docs/api-conventions.md b/docs/api-conventions.md
index 03ef5a896..8c2c61100 100644
--- a/docs/api-conventions.md
+++ b/docs/api-conventions.md
@@ -641,7 +641,11 @@ Runtime `/api/*` JSON is serialized by **Newtonsoft** (`AddNewtonsoftJson` in `S
`ErsatzTV/Serialization/CustomContractResolver.cs` → `CustomNamingStrategy` (camelCase **plus** a
special case mapping any `FFmpegProfileId` member to `"ffmpegProfileId"`, and honoring any
`[JsonProperty("...")]` attribute, e.g. `ChannelResponseModel.FFmpegProfile` →
-`[JsonProperty("ffmpegProfile")]`). The OpenAPI document, however, is generated from
+`[JsonProperty("ffmpegProfile")]`). The settings themselves live in
+`ErsatzTV/Serialization/ApiJsonSettings.cs`, which `Startup` applies — call it from a test that needs to
+serialize or bind the way the runtime does rather than restating the settings, which drifts silently
+(`OpenApiSerializerContractTests`, `ScriptedScheduleControllerTests`). The OpenAPI document, however, is
+generated from
**System.Text.Json** metadata, whose camelCase can differ (it emitted `fFmpegProfileId` /
`fFmpegProfile`). That drift silently gave the SPA the wrong key to read (issue #198).
diff --git a/docs/decisions.md b/docs/decisions.md
index 9364af441..af48db9eb 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -99,7 +99,6 @@ leaving the shared tree dirty is the one outcome that would make this script a n
**Negative control (inherited from #231/#250).** A dedicated test hammers unbalanced releases on an empty pool while reader threads sample the count; none may ever observe a value below zero. Reinstating the pre-#539 decrement-first body makes it fail (`sawNegative > 0` — the readers catch the transient `−1`); verified. As with the #536 tests, break the primitive by reverting the real body, **not** `if (true)` (CS0219 under warnings-as-errors leaves `--no-build` running a stale, still-fixed dll).
**SPA is id-fields-first; the API is complete ahead of the UI.** The Channel Builder + Auto-Tune DetailPanel re-add a real "None" option to the five id selects (watermark + fillers) — the pickers #89 had degraded to "Inherit"-only — routed through a `CLEAR` overrides sentinel folded into `advanced.clear` at request-build time (`applyOverridesToRequest`, so the sentinel never leaks as a field value). The three string clear-fields are covered by the backend enum for machine clients (MCP) but the SPA text inputs keep "empty = inherit"; adding a tri-state to those inputs is deferred, not blocked. This is the deliberate "REST API is a real audience" posture (`rest-api-purpose-mcp-and-new-ui`).
`security.iptv-browser-token`.
-external-process pipeline remains #563's.
picker; TZ-independence holds only for divisors of 60. See #77 (prior art) and #392.
@@ -202,7 +201,7 @@ another doc or an old issue comment should land here and then follow the link.
- 2026-07-21 — `WorkAheadSlots.Release()` clamps before decrementing and reports unbalance in-band (#539) — [`ffmpeg.work-ahead-slot-release-never-negative`](decisions/records/ffmpeg/work-ahead-slot-release-never-negative.md)
- 2026-07-21 — `from-lineup` advanced overrides express "clear to none" via a typed `clear` enum list (#135) — [`api.from-lineup-clear-to-none`](decisions/records/api/from-lineup-clear-to-none.md)
- 2026-07-22 — Channel-level graphics-element attachment + seeded On Now/Next text element (#74) — [`graphics.channel-level-attachment`](decisions/records/graphics/channel-level-attachment.md)
-- 2026-07-22 — Sequential (YAML) playout gets a golden; Scripted is excluded from the golden net by construction (#381) — [`testing.scripted-playout-golden-deferred`](decisions/records/testing/scripted-playout-golden-deferred.md)
+- 2026-07-22 — Sequential (YAML) playout gets a golden; Scripted is excluded from the golden net by construction (#381) — [`testing.scripted-playout-golden-deferred`](decisions/archive/testing/scripted-playout-golden-deferred.md) (superseded by `testing.scripted-engine-in-process-net`)
- 2026-07-22 — per-schedule clock-boundary padding is a synthetic content-less Pad over the existing per-episode machinery (#392) — [`sched.clock-padding-schedule-toggle`](decisions/records/sched/clock-padding-schedule-toggle.md)
- 2026-07-23 — Channel health = a server-derived `health` object on the channel DTOs, built-timeline detection (#415) — [`api.channel-health-object`](decisions/records/api/channel-health-object.md)
- 2026-07-23 — Channel origin is immutable creation-provenance, stamped at insert, not a health signal (#414) — [`channel.origin-marker`](decisions/records/channel/origin-marker.md)
@@ -216,3 +215,4 @@ another doc or an old issue comment should land here and then follow the link.
- 2026-07-25 — The rationale-edit marker is a git trailer, not a substring anywhere in the commit range (#609) — [`ci.decisions-edit-trailer`](decisions/records/ci/decisions-edit-trailer.md)
- 2026-07-25 — UI-E2E: headless Playwright flows in the existing `functional-e2e` job, browser baked into the CI image (#445) — [`ci.ui-e2e-harness`](decisions/records/ci/ui-e2e-harness.md)
- 2026-07-26 — Facet-value typeahead restated: every artist source covered; the JSON-column source is paged by row position with no residual SQL predicate (#578) — [`api.search-field-values-sources`](decisions/records/api/search-field-values-sources.md)
+- 2026-09-05 — Scripted playout is covered in-process, engine plus controller adapter; the Cli.Wrap process and the HTTP transport are permanently out of the automated suite (#563) — [`testing.scripted-engine-in-process-net`](decisions/records/testing/scripted-engine-in-process-net.md)
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index c165a701c..e24a8ef87 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -224,7 +224,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `testing.live-e2e-prepush-timing` | Run live-E2E via `scripts/e2e-local.sh` before pushing a write-path or UI change, and exercise download endpoints with curl, never a browser tab. | 2026-07-21 | [link](records/testing/live-e2e-prepush-timing.md) |
| `testing.mutation-claims-are-executed` | A `MUTATION` row in `docs/guard-inventory.md` is not a statement that someone once witnessed a red. It carries a DECLARED clause mutation in `scripts/tests/mutation_manifest.py`, and `scripts/tests/test_mutation_harness.py` applies that mutation to an isolated copy of the repository on every run and requires the row's OWN named test to go red. The manifest and the MUTATION rows are compared for SET EQUALITY in both directions, so a row cannot claim the grade without a mutation and a mutation cannot outlive the grade it justifies. EXIT STATUS IS NOT THE VERDICT: each entry also declares the DIAGNOSTIC its red must carry, matched against pytest's exception output alone, because pytest reports a crashing test exactly as it reports a detecting one and a red for an unrelated reason is evidence about nothing. WHERE THE GUARD IS ITSELF A TEST, `target` may differ from `guard` and the exact-once check applies to the declared TARGET. Two shapes are admissible and the choice is not free. Where the guard's assertion IS the check — a completeness comparison against a Markdown inventory — the mutation goes into the guarded ARTIFACT, per `testing.guard-ships-with-mutation-proof`'s checker-guard exception, because mutating such a checker's own POPULATION demonstrates a false POSITIVE while proving nothing about the detection the row claims. Where the guard is a test module wrapping a separately mutable DETECTOR or helper, the clause may be in that detector, since disarming it is a real clause disarm and the module's own assertion is what notices. THE MUTATION IS DECLARED, NEVER INFERRED: a harness that guessed which clause of a 90-line hook is the guard would manufacture the confident-but-empty coverage this exists to prevent, which is why `testing.guard-ships-with-mutation-proof` rejected a generic runner. Where a proof test already names its clause in source, the manifest reuses THAT string, so a retarget in either place is caught by the other. COARSENESS IS RECORDED, NOT HIDDEN: each entry is graded `CLAUSE` or `DETECTOR`, and a `DETECTOR` entry — one whose detector accumulates faults from independent arms, so disarming any single arm leaves its proof test green — must CARRY the finer mutation that survived, which is re-run every time and required to keep surviving. Guards that are not graded `MUTATION` each carry a STATED reason in that same manifest, keyed on the guard and compared for SET EQUALITY against the inventory's `GUARD` rows in both directions — so a new guard cannot arrive without someone writing what a proof would need, and a reason cannot outlive the row it is about. Keying the reason on the row's GRADE instead is tautological (a new guard inherits one and nobody looks at it) and a pinned COUNT moves only on net change; both were tried and are rejected. The sandbox is a real git repository built from `git ls-files` with working-tree content, never a filesystem walk. THE POPULATION IS EVERY DECLARED MUTATION-OUTCOME CLAIM, NOT ONLY THE INVENTORY'S ROWS (ersatztv#881): a sentence asserting that a specific mutation reddens, or does not redden, a named test is the same kind of claim wherever it is written — a code comment, a test docstring, a decision record — and is either a `CLAIMS` entry in `scripts/tests/mutation_manifest.py` that executes every run, or it is not written. A claim entry is keyed on the PROSE rather than on a guard: it carries the tracked `site` and the verbatim `quote`, both checked every run, so a reworded sentence reports as a RETARGET instead of drifting away from the entry that justifies it. THE QUOTE SPANS THE MUTATION AND THE OUTCOME IT ASSERTS: the outcome half is the checkable part, so a quote stopping at the mutation binds the uncontroversial words and leaves the assertion, and the test it names, outside the binding entirely. It declares `RED` or `GREEN`, and GREEN is the half no `MUTATION` row can express — a claim that a mutation is NOT noticed is read by THREE separate clauses, because each alone certifies a run that proves nothing: the run exited 0, something actually PASSED, and the named proof was shown to REACH the mutated clause. THE TWO DIRECTIONS ARE NOT SYMMETRIC, WHICH IS WHY THE THIRD CLAUSE EXISTS ON ONLY ONE OF THEM. A RED claim checks its own relevance for free — a proof that never executes the mutated file stays green and is refused in the same words as a clause that has stopped being load-bearing — while a GREEN claim gets precisely the green it asserts from a proof that reads a different file entirely, so exit status and a passing test TOGETHER still certify a run that never executed the clause. A GREEN entry therefore also declares a SECOND mutation of the SAME clause, required to REDDEN the same proof and carrying its own declared diagnostic, executed through the same red-reading path the inventory rows use; only once that passes is the green evidence about this clause at all. It is worth what the `DETECTOR` survivor was worth: re-run, and required to KEEP surviving. THE REFERENT IS DECLARED, NEVER INFERRED, exactly as the clause is: a checker hunting for sentences that merely SOUND like mutation claims would be a string predicate over prose, which this repo refuses to make load-bearing, so what is enforced is a claim that named its own referent, and the direction that cannot be mechanised — prose that declares nothing — is stated rather than papered over. TWO NEIGHBOURING PROPOSALS ARE SETTLED HERE. A QUOTATION of another file is a claim about that file: adopted, and the `quote` field IS the check, wherever the referent is declared; a general quotation-checker is rejected for the same reason inference is, since a quotation whose referent is unnamed has nothing to resolve. ANCHORING PROSE TO A STATE THE COMMIT ITSELF MOVES ('the last edit to that path', 'the only X that'): rejected as a detector and kept as a phrasing rule. The rejection is measured, and the scan is PINNED IN THE BODY rather than summarised as a figure here, for the same reason the population scan is — a count quoted without the predicate that produced it is the defect this record is about. What it shows is that the shape is indistinguishable BY PATTERN from ordinary rationale ('X is the only thing that can Y'), which this rule carves out, so a detector would fire mostly on prose it must not flag, and an advisory check that does that stops being read. Anchor to a date or a sha under `docs.no-session-narrative`'s dated-measurement clause; inside this rule's own population the anchor is the manifest entry, which is re-executed and therefore cannot go stale. | 2026-08-22 | [link](records/testing/mutation-claims-are-executed.md) |
| `testing.playwright-mcp-download-and-recovery` | In Playwright-MCP E2E, fetch file-download endpoints with curl — never a browser tab or `window.open` — and if browser tools stall repeatedly, `pkill -f ms-playwright-mcp` and drive a fresh session. | 2026-07-21 | [link](records/testing/playwright-mcp-download-and-recovery.md) |
-| `testing.scripted-playout-golden-deferred` | The `PlayoutBuildGoldenTests` in-memory golden net covers Sequential (YAML) as of #381. Scripted's *end-to-end pipeline* is excluded — `ScriptedPlayoutBuilder` runs a user-authored external program that drives the engine over HTTP loopback, which the in-memory harness can't pin — so that full-pipeline (integration) harness is deferred to #563. But the scheduling *behavior* those scripts drive lives entirely in the in-process `SchedulingEngine` (the `ScriptedScheduleController` is a 1:1 pass-through to it), which IS directly unit/golden-testable; the earlier "Scripted is un-golden-able by construction" framing overstated the constraint by conflating transport with engine. #395 extracts that shared switch to `ContentEnumeratorBuilder` and adds a direct regression net (`ContentEnumeratorBuilderTests`) over it. | 2026-07-22 | [link](records/testing/scripted-playout-golden-deferred.md) |
+| `testing.scripted-engine-in-process-net` | Scripted playout is characterized at two in-process levels and no further. (1) `SchedulingEngineTests` drives the engine build API directly with substituted repositories — the same setup order `ScriptedPlayoutBuilder` uses (`WithPlayoutId`/`WithMode`/`WithSeed`/`BuildBetween`/`WithReferenceData`/`RestoreOrReset`, and `WithReferenceData` MUST precede the last two or `PlayoutReferenceData.PlayoutHistory` NREs). (2) `ScriptedScheduleControllerTests` replays a committed script fixture (`ErsatzTV.Tests/Controllers/Fixtures/scripted-build.json`) through the REAL `ScriptedScheduleController` + `ScriptedPlayoutBuilderService.MockSession` + `SchedulingEngine` and pins the resulting `PlayoutItem`s as a snapshot in the golden line format — so exactly ONE action-to-engine mapping exists in the repo, the production one. Fixture bodies in that replay are deserialized with `ApiJsonSettings`, the configuration `Startup` applies to `AddNewtonsoftJson`, invoked from the same function rather than mirrored — and two tests WITNESS that choice instead of asserting it, each binding a body that separates the production binder from one plausible replacement: `Production_Body_Binder_Ignores_Required_Members` omits a C# `required` member, which Newtonsoft defaults and System.Text.Json rejects; `Production_Body_Binder_Keeps_Declared_Defaults_Over_An_Explicit_Null` sends an explicit `"order": null`, which `NullValueHandling.Ignore` drops and a bare `JsonSerializerSettings` writes through into a 400. What is shared is the CONFIGURATION, never MVC's settings OBJECT: `ApiJsonSettings.Create()` applies it to a bare settings object, so MVC's `MaxDepth` of 32 and its `ProblemDetails`/`ValidationProblemDetails` converters are absent (measured 2026-09-05, pinned by `ApiJsonSettingsTests`); neither is reachable from a scripted request body, and no test may generalize from `Create()` to production past that. What no test observes is the `Startup` registration itself, so the extraction REMOVES the duplicate rather than detecting its drift. The `Cli.Wrap` launch of the user-authored program (exit code, timeout, stdout capture), the Kestrel/middleware/`ApiAuthorizationFilter` transport it calls back over, and MVC model binding as a WRAPPER (the input formatter, model validation and the `[ApiController]` automatic 400 either produces before an action runs — the serializer inside that wrapper is covered, the wrapper around it is not) are NOT tested and are not scheduled to be; that residue is named below rather than argued away. Both fixtures must aim every trimming instruction at an instant BETWEEN two content boundaries: a pad or duration that happens to land on one never enters the engine's trim branch, so that action's `trim` argument reaches nothing the snapshot can show. The controller is a thin adapter, NOT a 1:1 pass-through: an unparseable playback order is a 400, an unparseable filler kind SILENTLY degrades to `FillerKind.None`, an unknown build id is a 404, and the engine no-progress `InvalidOperationException` is translated to a 400 — each pinned by a test, because a prose claim of equivalence decays. | 2026-09-05 | [link](records/testing/scripted-engine-in-process-net.md) |
| `testing.suite-isolated-from-production-hook-fire-log` | THE SUITE MUST NOT WRITE TO `$HOME/.cache/ersatztv/hook-fire/`, AND THAT PROPERTY IS ESTABLISHED STRUCTURALLY RATHER THAN OBSERVED. Two layers in `scripts/tests/conftest.py`, which close different routes and must both stay. FIRST, `pytest_configure` sets `ETV_HOOK_FIRE_LOG_DIR` BEFORE COLLECTION. An autouse fixture alone runs at test setup — after every module has been imported — so it cannot reach a module that snapshots `{**os.environ}` at import time (the ersatztv#785 defect, 58 leaked records per run) and cannot reach a MODULE- or SESSION-SCOPED FIXTURE at all; measured on the pre-change tree by instrumenting `subprocess.Popen` for a full run and asking which launches resolve to `$HOME/.cache/ersatztv/hook-fire`, 83 did — 37 during collection, 44 inside module- or session-scoped fixtures, and 2 from an environment built from scratch. INSTRUMENT `Popen` ALONE: `subprocess.run`, `call` and `check_output` all reach it, so a census wrapping `run` as well counts every launch twice and every figure doubles. STATE THE PREDICATE WITH THE COUNT: this one also UNDERCOUNTS the from-scratch route, because such an environment usually carries no `HOME` either and lands in the sink's OTHER default, which this predicate cannot see. The launches that carry no `ETV_HOOK_FIRE_LOG_DIR` and are built from scratch number 83 as well, and 81 of those carry no `HOME` — two different sets of the same size, which is precisely the shape a later reader reconciles wrongly. The per-test fixture stays, because a test that inspects its own log dir must not see another test's records. SECOND, a `Popen` wrapper fails EVERY launch that does not CARRY the isolated directory — the route left open when an environment is built FROM SCRATCH rather than derived from `os.environ`, where no snapshot is involved and import ordering cannot help. THE RULE IS "CARRIES AN ISOLATED DIR", NOT "IS NOT THE PRODUCTION ONE", and that is the difference between a guard and a guard-shaped hole: `etv_hook_fire_log_dir` has TWO default branches — `$HOME/.cache/...` and, when `HOME` is unset or empty, `/tmp/.cache/...` — so a check comparing against one resolved production path models one branch and waves the other through, and `/tmp/.cache/ersatztv/hook-fire` is just as shared, just as persistent and just as readable with `hook-fire-log.sh report --dir`. Measured: of the 83 from-scratch launches, 81 carry no `HOME` either. Requiring the variable covers both branches and any a future sink adds, and is independent of what `HOME` happens to be on the machine running the suite — which is also what keeps it from firing on legitimate launches where `HOME` is unset or is itself `/tmp`. The corollary is that every from-scratch environment in the suite must carry the variable, one line each. NO COUNT OF THOSE SITES IS KEPT HERE: it is a hand-written population literal that nothing derives, and the commit introducing this rule already falsified its own, by adding further construction sites in the tests that prove the rule. The guard itself is the enumerator; a missing site is a red, not a stale sentence. Its population is every launch that actually happens, derived at runtime, so a new suite is covered by existing rather than by remembering. NEVER OBSERVE THE PRODUCTION DIRECTORY TO PROVE THIS. The withdrawn guard snapshotted `st_mtime_ns` across it and required no change, which makes the oracle state every concurrent session on the machine writes: an unrelated session firing a hook inside the window failed the suite with `a test run modified the production hook-fire log`, an accusation about the suite when the writer was another process. Seen on three separate branches, green on every immediate re-run. The misattribution is the expensive part — it aims the next reader at the suite, and a guard that cries wolf gets waved through. THE RESOLVER IS A REIMPLEMENTATION AND FAILS OPEN, so it is differential-tested against `etv_hook_fire_log_dir` every run: a resolver that disagrees clears a launch the sink then points at the real log. Shell's `:-` treats an EMPTY value as absent, which `dict.get(k, default)` does not — that case is in the matrix because it is where a Python transliteration goes wrong. AND BIND A VIOLATION BEFORE ASSERTING ON IT: pytest rewrites an assert expression and prints the repr of every sub-expression, so `assert isolation_violation(os.environ) is None` dumps the environment — API keys included — into the failure output and from there into a CI log. | 2026-08-28 | [link](records/testing/suite-isolated-from-production-hook-fire-log.md) |
| `testing.troubleshoot-path-cannot-test-branding` | Verify logo/watermark/bug changes through a real channel playout — a green troubleshoot run proves nothing about branding. | 2026-07-21 | [link](records/testing/troubleshoot-path-cannot-test-branding.md) |
| `testing.verification-code-needs-its-own-proof` | VERIFICATION CODE IS CODE UNDER TEST. The obligation in `testing.guard-ships-with-mutation-proof` attaches to whatever emits a PASS/FAIL somebody acts on — a smoke test, a timeout wrapper, an operator-run checker, the harness that applies the mutations — and NOT only to files sitting in the guard population or named like guards; every one of the five defects measured below was in code nobody had counted as a guard. THE DISCRIMINATOR IS WHETHER A PROOF TEST CAN DRIVE THE CONSTRUCT HERMETICALLY, NOT WHETHER CI RUNS IT, and the difference is load-bearing rather than pedantic: `.claude/hooks/*.sh` and `.husky/pre-push` are operator-run and CI never fires them AS HOOKS, yet several of them carry `MUTATION` rows — among them `pretooluse-bom-guard.sh`, `pretooluse-worktree-guard.sh` and `.husky/pre-push` — because a pytest proof drives them in a sandbox. A does-CI-run-it test would sort those already-proven guards into the exempt branch. (Most of the remaining hooks are graded `NONE`; that is unproven debt, not evidence for the other discriminator.) "IT NEEDS A REAL SERVER" IS AN EXEMPTION CLAIM AND IT IS USUALLY FALSE: `scripts/mcp_smoke.py` takes its config path and server name as POSITIONAL ARGUMENTS, so a test hands it a synthetic config in a tmpdir pointing at a stub responder and drives it with no gitignored `.mcp.json` and no language server, which is how it is proven in `scripts/tests/test_mcp_smoke.py`. That coverage is a SUBSET and no count of it is kept here: the file's own docstring enumerates the cases it drives and names what it does not, so there is a list rather than a number to keep in step with it. A checker is never excused because its CALLER cannot run in CI. WHERE THE PROOF LIVES: the checker itself needs NO `docs/guard-inventory.md` row, because that population is derived from workflow and hook call sites and a transitively-reached script is rejected as a phantom; the proof goes in an ordinary `scripts/tests/test_*.py`, which joins the population automatically and carries the row, while the manifest entry names THAT test as `guard` and the checker as `target`. That shape already exists for `mutation_harness_lib.py` and needs no change to any population. ONLY WHAT NO PROOF TEST CAN DRIVE HERMETICALLY falls back to a WITNESSED NEGATIVE CONTROL — the failure path executed once, the false-green form reproduced, both recorded in the PR, and its decay stated because nothing re-runs it. `scripts/check-local-lsp.sh` is the genuine case: it asserts developer-machine installs (a global `csharp-ls`, a `host/fxr` under `DOTNET_ROOT`, a root `node_modules`) that no runner has. STOP-AND-SUBTRACT, adopted here as this record's own threshold: when a review round's finding was CREATED by the previous round's fix and that happens TWICE CONSECUTIVELY, delete the layer generating them rather than guarding it. READING THE CONSTRUCT IS NOT EXECUTING IT: ShellCheck 0.11.0 flagged NEITHER of the two shell defects below, and each is indistinguishable from correct by reading. | 2026-08-28 | [link](records/testing/verification-code-needs-its-own-proof.md) |
diff --git a/docs/decisions/records/testing/scripted-playout-golden-deferred.md b/docs/decisions/archive/testing/scripted-playout-golden-deferred.md
similarity index 77%
rename from docs/decisions/records/testing/scripted-playout-golden-deferred.md
rename to docs/decisions/archive/testing/scripted-playout-golden-deferred.md
index 3111ebc59..ae21f0bc2 100644
--- a/docs/decisions/records/testing/scripted-playout-golden-deferred.md
+++ b/docs/decisions/archive/testing/scripted-playout-golden-deferred.md
@@ -1,13 +1,13 @@
---
key: testing.scripted-playout-golden-deferred
title: 2026-07-22 — Sequential (YAML) playout gets a golden; Scripted is excluded from the golden net by construction (#381)
-status: active
+status: superseded
since: '2026-07-22'
supersedes: none
-superseded-by: none
-rule: 'The `PlayoutBuildGoldenTests` in-memory golden net covers Sequential (YAML) as of #381. Scripted''s *end-to-end pipeline* is excluded — `ScriptedPlayoutBuilder` runs a user-authored external program that drives the engine over HTTP loopback, which the in-memory harness can''t pin — so that full-pipeline (integration) harness is deferred to #563. But the scheduling *behavior* those scripts drive lives entirely in the in-process `SchedulingEngine` (the `ScriptedScheduleController` is a 1:1 pass-through to it), which IS directly unit/golden-testable; the earlier "Scripted is un-golden-able by construction" framing overstated the constraint by conflating transport with engine. #395 extracts that shared switch to `ContentEnumeratorBuilder` and adds a direct regression net (`ContentEnumeratorBuilderTests`) over it.'
+superseded-by: testing.scripted-engine-in-process-net@2026-09-05
+rule: '(superseded) The `PlayoutBuildGoldenTests` in-memory golden net covers Sequential (YAML) as of #381. Scripted''s *end-to-end pipeline* is excluded — `ScriptedPlayoutBuilder` runs a user-authored external program that drives the engine over HTTP loopback, which the in-memory harness can''t pin — so that full-pipeline (integration) harness is deferred to #563. But the scheduling *behavior* those scripts drive lives entirely in the in-process `SchedulingEngine` (the `ScriptedScheduleController` is a 1:1 pass-through to it), which IS directly unit/golden-testable; the earlier "Scripted is un-golden-able by construction" framing overstated the constraint by conflating transport with engine. #395 extracts that shared switch to `ContentEnumeratorBuilder` and adds a direct regression net (`ContentEnumeratorBuilderTests`) over it.'
signals: 'why is there no scripted golden; scripted transport vs engine; SchedulingEngine is in-process testable; Cli.Wrap external process is transport only; ScriptedScheduleController 1:1 pass-through; engine-level scripted regression net; EnumeratorForContent · paths: `ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs`, `ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs`, `ErsatzTV.Core/Scheduling/Engine/SchedulingEngine.cs`, `ErsatzTV/Controllers/Api/ScriptedScheduleController.cs`, `ErsatzTV.Core/Scheduling/ScriptedScheduling/ScriptedPlayoutBuilder.cs` · issues: #381, #163, #395, #563'
-mechanics: docs/testing.md → Golden-file nets
+mechanics: superseded by `testing.scripted-engine-in-process-net` (ersatztv#563), which stands up the deferred coverage in-process and corrects the "1:1 pass-through" description of `ScriptedScheduleController`
---
**Sequential (YAML) is golden-able and TZ-independent.** `SequentialPlayoutBuilder` reads a YAML schedule
diff --git a/docs/decisions/records/testing/scripted-engine-in-process-net.md b/docs/decisions/records/testing/scripted-engine-in-process-net.md
new file mode 100644
index 000000000..ee9b61bc5
--- /dev/null
+++ b/docs/decisions/records/testing/scripted-engine-in-process-net.md
@@ -0,0 +1,77 @@
+---
+key: testing.scripted-engine-in-process-net
+title: '2026-09-05 — Scripted playout is covered in-process, engine plus controller adapter; the Cli.Wrap process and the HTTP transport are permanently out of the automated suite (#563)'
+status: active
+since: '2026-09-05'
+supersedes: testing.scripted-playout-golden-deferred@2026-07-22
+superseded-by: none
+rule: 'Scripted playout is characterized at two in-process levels and no further. (1) `SchedulingEngineTests` drives the engine build API directly with substituted repositories — the same setup order `ScriptedPlayoutBuilder` uses (`WithPlayoutId`/`WithMode`/`WithSeed`/`BuildBetween`/`WithReferenceData`/`RestoreOrReset`, and `WithReferenceData` MUST precede the last two or `PlayoutReferenceData.PlayoutHistory` NREs). (2) `ScriptedScheduleControllerTests` replays a committed script fixture (`ErsatzTV.Tests/Controllers/Fixtures/scripted-build.json`) through the REAL `ScriptedScheduleController` + `ScriptedPlayoutBuilderService.MockSession` + `SchedulingEngine` and pins the resulting `PlayoutItem`s as a snapshot in the golden line format — so exactly ONE action-to-engine mapping exists in the repo, the production one. Fixture bodies in that replay are deserialized with `ApiJsonSettings`, the configuration `Startup` applies to `AddNewtonsoftJson`, invoked from the same function rather than mirrored — and two tests WITNESS that choice instead of asserting it, each binding a body that separates the production binder from one plausible replacement: `Production_Body_Binder_Ignores_Required_Members` omits a C# `required` member, which Newtonsoft defaults and System.Text.Json rejects; `Production_Body_Binder_Keeps_Declared_Defaults_Over_An_Explicit_Null` sends an explicit `"order": null`, which `NullValueHandling.Ignore` drops and a bare `JsonSerializerSettings` writes through into a 400. What is shared is the CONFIGURATION, never MVC''s settings OBJECT: `ApiJsonSettings.Create()` applies it to a bare settings object, so MVC''s `MaxDepth` of 32 and its `ProblemDetails`/`ValidationProblemDetails` converters are absent (measured 2026-09-05, pinned by `ApiJsonSettingsTests`); neither is reachable from a scripted request body, and no test may generalize from `Create()` to production past that. What no test observes is the `Startup` registration itself, so the extraction REMOVES the duplicate rather than detecting its drift. The `Cli.Wrap` launch of the user-authored program (exit code, timeout, stdout capture), the Kestrel/middleware/`ApiAuthorizationFilter` transport it calls back over, and MVC model binding as a WRAPPER (the input formatter, model validation and the `[ApiController]` automatic 400 either produces before an action runs — the serializer inside that wrapper is covered, the wrapper around it is not) are NOT tested and are not scheduled to be; that residue is named below rather than argued away. Both fixtures must aim every trimming instruction at an instant BETWEEN two content boundaries: a pad or duration that happens to land on one never enters the engine''s trim branch, so that action''s `trim` argument reaches nothing the snapshot can show. The controller is a thin adapter, NOT a 1:1 pass-through: an unparseable playback order is a 400, an unparseable filler kind SILENTLY degrades to `FillerKind.None`, an unknown build id is a 404, and the engine no-progress `InvalidOperationException` is translated to a 400 — each pinned by a test, because a prose claim of equivalence decays.'
+signals: 'why is there no scripted golden; scripted integration harness; scripted transport vs engine; SchedulingEngine is in-process testable; Cli.Wrap external process is transport only; shell-out scoped out; MockSession seam; in-process stand-in for a scripted script; engine build API characterization; committed script fixture replay; ScriptedScheduleController is an adapter not a pass-through; scripted filler kind silently falls back to None; scripted playout no-progress halt maps to 400; scripted build 401 blind spot; EnumeratorForContent · paths: `ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs`, `ErsatzTV.Tests/Controllers/ScriptedScheduleControllerTests.cs`, `ErsatzTV.Tests/Controllers/Fixtures/scripted-build.json`, `ErsatzTV.Tests/Serialization/ApiJsonSettingsTests.cs`, `ErsatzTV/Serialization/ApiJsonSettings.cs`, `ErsatzTV.Core/Scheduling/Engine/SchedulingEngine.cs`, `ErsatzTV/Controllers/Api/ScriptedScheduleController.cs`, `ErsatzTV.Core/Scheduling/ScriptedScheduling/ScriptedPlayoutBuilder.cs`, `ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs` · issues: #563, #381, #395, #163'
+mechanics: docs/testing.md → "Scripted playout coverage" and "Golden-file nets"
+---
+
+**What carries over from the predecessor.** Sequential (YAML) is golden-able and TZ-independent, and
+`PlayoutBuildGoldenTests` covers Classic / Block / Sequential. Scripted's *end-to-end pipeline* stays out
+of that net: `ScriptedPlayoutBuilder` builds nothing itself, it `Cli.Wrap`-executes a user-authored
+program, hands it `http://localhost:{Settings.UiPort}` plus a build id, and reads the result straight off
+the in-process engine afterwards. #395's `ContentEnumeratorBuilderTests` remains the direct net over the
+enumerator-construction switch Scripted and Sequential share.
+
+**What changed.** The predecessor deferred the whole harness to #563 and described the controller as a
+"1:1 pass-through". Both are now settled: the coverage exists in-process, and the pass-through wording was
+wrong — the four adapter mappings above are real behaviour that only a test can hold.
+
+**Why not the full Kestrel + `Cli.Wrap` harness.** Four measured obstacles, not a preference:
+
+1. *The production transport is not "a controller behind Kestrel".* `Startup` 404s any request whose Host
+ is not `localhost` and whose `Connection.LocalPort != Settings.UiPort` (a mutable process-wide static),
+ and `ApiAuthorizationFilter` fail-closes every mutating verb. A hand-rolled minimal host would test a
+ transport the product does not have; the real `Startup` drags in the whole DI graph (TvContext, ffmpeg
+ workers, search index, background services), which is what #381 deferred in the first place.
+2. *The external program is user-authored by definition.* `Playout.ScheduleFile` is an arbitrary command
+ line, so any script we commit is a stand-in we wrote either way. The fork's own driver,
+ `scripts/scripted-schedules/entrypoint.py`, imports `etv_client`, a generated package that exists only
+ in the deploy environment, so it cannot run in the .NET test job without adding a client-generation step.
+3. *It would put an interpreter and process spawning inside the pure in-memory .NET suite*, with the 30s
+ `Cli.Wrap` timeout nested inside CI's `--blame-hang-timeout 2m` — a new flake class on a shared runner.
+4. *The stand-in loses nothing the harness would have added at the engine level.* Replaying the fixture
+ through the real controller and the real service keeps a single action-to-engine mapping under test;
+ what is absent is the two transport hops plus MVC binding as a wrapper, and the wrapper is the shallow
+ half — the serializer inside it is configured by `ApiJsonSettings`, the production configuration (not
+ MVC's settings *object*, whose remaining defaults the rule enumerates).
+
+**The residue, named.** Uncovered: process launch, exit code and timeout handling; Kestrel plus the
+forwarded-headers / compression / SPA-hosting middleware; MVC model binding as a *wrapper* — the input
+formatter (content-type selection, malformed-body handling), model validation (a non-nullable reference
+type picks up an implicit required check there) and the `[ApiController]` automatic 400 either produces
+before an action runs, since every test hands an action an already-bound object; and
+`ApiAuthorizationFilter`. The *serializer* inside that wrapper is deliberately not on this list — it is
+`ApiJsonSettings` itself, and two tests hold the two ways it can be replaced. `ApiJsonSettings` exists so
+that binder is *defined* once; it is not a drift **detector**, and the branch may not claim one, because
+nothing observes `Startup.ConfigureServices` and a byte-equal hand-copy of `Apply` is indistinguishable
+by construction. What the suites do separate is a mirror that has *lost* something. The mechanics doc
+tabulates which suite separates which half of the configuration, and what neither reaches.
+
+**Where the calibrating measurements are, and why not here.** `testing.mutation-claims-are-executed`
+admits a sentence asserting that a specific mutation reddens — or does not redden — a named test only as
+a `CLAIMS` entry in `scripts/tests/mutation_manifest.py`, executed every run; otherwise it is not
+written. That harness resolves a proof to `scripts/tests/` and runs pytest, so an NUnit proof
+cannot be declared in it and this coverage is entirely NUnit. The binder and `trim` mutants run while
+building these tests therefore stay in ersatztv#563 — its pull request and the commit messages that
+ran them — dated. Durable prose carries
+the mechanism each test is built on instead — which serializer difference, which engine branch — because
+that is re-checkable by reading the code rather than by trusting a remembered outcome.
+
+`ApiAuthorizationFilter` on that list is not hypothetical — `ScriptedScheduleController` carries no
+`[SkipApiAuthorization]` while
+`ScriptedPlayoutBuilder` passes the script only host, build id and mode, with no `X-Api-Key`, and
+`entrypoint.py` builds its client with no credential. Whether a scripted build therefore 401s on its first
+POST in this fork is unverified against a live instance and is tracked in ersatztv#913; it is recorded here
+as the concrete shape of what an engine-level net cannot see, so the scope-out is not read as a claim of
+equivalence.
+
+**Determinism constraints on the fixtures.** Both use Chronological order and only instant-preserving
+instructions (`AddCount`, `AddAll`, `AddDuration`, `PadUntilExact`). `WaitUntil(TimeOnly)` and
+`PadUntil(string)` read the LOCAL day and time-of-day, and `PadToNext` becomes offset-sensitive once a
+call has localized `CurrentTime`, so introducing any of them — or a `shuffle` order — reopens the
+timezone and seed question the fixtures were built to close.
diff --git a/docs/testing.md b/docs/testing.md
index dbc04b5d5..09ebf0827 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -35,14 +35,10 @@ Three golden-file suites guard the highest-value, most-subtle output:
produces over a pinned build window. Covers the **Classic** (`PlaybackOrder.Chronological`),
**Block**, and **Sequential (YAML)** builders. The **Scripted** *end-to-end pipeline* is excluded from this
net — `ScriptedPlayoutBuilder` runs a user-authored external process that drives the engine over HTTP, which
- the in-memory harness can't pin; that integration harness is tracked in ersatztv#563. The scheduling
- *behavior* those scripts drive, though, lives in the in-process `SchedulingEngine` (the HTTP controller is a
- 1:1 pass-through) and IS directly testable — `SchedulingEngineTests` news it up with substitutes, and
- `ContentEnumeratorBuilderTests` (ersatztv#395) is the direct regression net over the enumerator-construction
- helper the Scripted and Sequential/YAML engines now share (decision:
- `testing.scripted-playout-golden-deferred`). The **Sequential** case
- (`Sequential_yaml`, ersatztv#381)
- builds from a committed YAML fixture (`Goldens/Fixtures/sequential-schedule.yml`) instead of a
+ the in-memory harness can't pin. Scripted is instead covered in-process at two levels, described under
+ "Scripted playout coverage" below (decision: `testing.scripted-engine-in-process-net`, ersatztv#563).
+ The **Sequential** case (`Sequential_yaml`, ersatztv#381) builds from a committed YAML fixture
+ (`Goldens/Fixtures/sequential-schedule.yml`) instead of a
`ProgramSchedule`; it is TZ-independent (the `count`/`all`/`duration` handlers do UTC-only arithmetic —
it passes, not skips, under a non-UTC `TZ`) so needs no `Assume` guard. A third case,
`Classic_clock_padded` (ersatztv#77), locks clock-boundary padding: a `FillerMode.Pad` +
@@ -67,6 +63,71 @@ diff during normal test runs means the code changed the output — regenerating
away hides the change instead of surfacing it. Only a human who has confirmed the change is
intentional should regenerate.
+## Scripted playout coverage
+
+Scripted playout is characterized in-process at two levels, and the transport is deliberately not covered
+at all (ersatztv#563, decision `testing.scripted-engine-in-process-net`).
+
+| Where | Covers |
+| --- | --- |
+| `ErsatzTV.Core.Tests/Scheduling/Engine/SchedulingEngineTests.cs` | The engine build API a script drives: `AddCollection`, `AddCount`, `AddAll`, `AddDuration` (stop-before-end and trim), `PadUntilExact`, EPG guide-group locking, per-item `PlayoutHistory`, the `IsDone` no-progress halt and its reset, and the `GetAnchor`/`RestoreOrReset` round-trip a Continue build resumes from. Substituted repositories, no database. |
+| `ErsatzTV.Tests/Controllers/ScriptedScheduleControllerTests.cs` | A committed script fixture (`Controllers/Fixtures/scripted-build.json`), bound with the production body-binder configuration (`ApiJsonSettings`) and replayed through the real `ScriptedScheduleController` + `ScriptedPlayoutBuilderService.MockSession` + `SchedulingEngine`, with a pinned 13-item snapshot in the same line format the playout goldens use (both trimming actions target an instant *between* two content boundaries, so each one's `trim` argument reaches the engine's trim branch rather than sitting inert), plus the four adapter mappings: 404 on an unknown build id, 400 on an unparseable playback order, a silent fall back to `FillerKind.None` on an unparseable filler kind, and the engine's no-progress `InvalidOperationException` translated to a 400. |
+| `ErsatzTV.Core.Tests/Scheduling/ContentEnumeratorBuilderTests.cs` | The enumerator-construction helper the Scripted and Sequential/YAML engines share (ersatztv#395). |
+| `ErsatzTV.Tests/Serialization/ApiJsonSettingsTests.cs` | What the replay's standalone binder does and does not share with the one MVC runs, so the paragraph below stays a measurement rather than a claim. |
+
+The expected snapshot is a string constant in the test rather than a fourth golden file: the golden
+harness lives in `ErsatzTV.Core.Tests`, which cannot reference a controller, and duplicating it would
+create a second action-to-engine mapping — the thing the single-mapping design exists to avoid.
+
+**Not covered, and not scheduled to be** (measured 2026-09-05): the `Cli.Wrap` launch of the user's own
+program — exit code, the `PlayoutScriptedScheduleTimeoutSeconds` timeout, stdout capture; Kestrel and the
+`Startup` middleware, including the host/`Settings.UiPort` check that 404s a foreign request;
+`ApiAuthorizationFilter`, which fail-closes every mutating verb for an endpoint without
+`[SkipApiAuthorization]`; and MVC model binding as a *wrapper* — the input formatter, model validation
+(a non-nullable reference type picks up an implicit required check there) and the `[ApiController]`
+automatic 400 either produces before the action runs, since the replay hands each action an
+already-bound object. Hosting the real `Startup` would drag in the whole DI graph, a
+hand-rolled minimal host would test a transport the product does not have, and the script is
+user-authored by definition — so any committed script is a stand-in either way. The decision record
+names the concrete blind spot this leaves, and it is tracked as ersatztv#913.
+
+The *serializer* inside that binding wrapper is covered rather than scoped out. The replay deserializes
+fixture bodies through `ErsatzTV.Serialization.ApiJsonSettings`, the same function `Startup` hands to
+`AddNewtonsoftJson`, and two tests witness that choice through the replay's own bind helper. The
+fixture's own bodies parse the same way under every plausible replacement, so each test carries a body
+built to separate one of them:
+
+| Replacement the test separates the production binder from | The body that separates them |
+| --- | --- |
+| `System.Text.Json` with web defaults | A body omitting the C# `required` member `collection`. Newtonsoft has no notion of `required` and deserializes it to a default; System.Text.Json rejects the body outright. `Production_Body_Binder_Ignores_Required_Members` asserts both halves. |
+| a bare `new JsonSerializerSettings()` — still Newtonsoft, but without the production configuration | An explicit `"order": null`. `NullValueHandling.Ignore` keeps `ContentCollection.Order` at its declared `"shuffle"`; Newtonsoft's own `Include` default writes the null through, and `AddCollection`'s `Enum.TryParse` then returns a 400. `Production_Body_Binder_Keeps_Declared_Defaults_Over_An_Explicit_Null` asserts the production side end to end. |
+
+Both are statements about the serializer and stop there — what MVC validation does with such a body
+belongs to the wrapper named above. What each test does to a suite when the binder is actually swapped
+was measured while building it and is recorded in ersatztv#563, not here: under
+`testing.mutation-claims-are-executed` such a sentence is a `CLAIMS` entry in
+`scripts/tests/mutation_manifest.py` that executes every run or it is not written, and that harness runs
+pytest, so an NUnit proof cannot be declared in it.
+
+What is shared with production is the *configuration*, not the settings **object**. MVC applies it to
+settings it has already configured; `ApiJsonSettings.Create()`, which every test outside the pipeline
+uses, applies it to a bare one. Measured 2026-09-05, the standalone object therefore keeps Newtonsoft's
+`MaxDepth` of 64 instead of MVC's stricter 32 and lacks MVC's `ProblemDetailsConverter` and
+`ValidationProblemDetailsConverter`; `MissingMemberHandling`, `TypeNameHandling` and `DateParseHandling`
+match. Neither gap can reach a scripted request body — the DTOs nest two levels and are never a
+`ProblemDetails` — which is what makes `Create()` usable in a test at all, and no test may generalize
+from it to "production" beyond that. `ErsatzTV.Tests/Serialization/ApiJsonSettingsTests.cs` pins the
+whole delta in both directions, so it fails rather than rots if either object moves.
+
+`ApiJsonSettings` exists so that binder is *defined* once; it is not a drift detector, and the difference
+is worth stating because it bounds what the suite can promise. Nothing here observes
+`Startup.ConfigureServices`, and a byte-equal hand-copy of `Apply` is behaviourally indistinguishable
+from calling it — so the extraction removes the duplicate rather than detecting drift in one. A mirror
+that has *lost* something is what the suites separate: the table above on the read path, and
+`OpenApiSerializerContractTests` on the write path, whose four cases assert the camelCase keys
+`CustomContractResolver` produces and nothing else in the configuration supplies. Drift confined to
+`ReferenceLoopHandling` or the `StringEnumConverter` is separated by neither.
+
## Timezone independence
The suite is timezone-independent (ersatztv#24). When constructing test `PlayoutItem`s, always
@@ -74,6 +135,17 @@ set a real `Start` (e.g. `startState.CurrentTime.UtcDateTime`) — never rely on
`DateTime.MinValue`, which underflows `DateTimeOffset.MinValue` once a non-UTC local offset is
applied (`StartOffset` calls `ToLocalTime()`). CI runs in UTC; local runs may not.
+**Which `SchedulingEngine` calls are safe to put in a fixture** (audited 2026-09-05). `AddCount`,
+`AddAll`, `AddDuration` and `PadUntilExact` preserve the instant — items are always written as
+`_state.CurrentTime.UtcDateTime`, and `PadUntilExact`'s `ToLocalTime()` changes the offset the state
+carries, not the moment. `WaitUntil(TimeOnly)` and `PadUntil(string)` are **not** safe: both read the
+LOCAL day and time-of-day off `CurrentTime` and rebuild a target from them. `PadToNext` is safe only
+until something localizes `CurrentTime` — it reads `.Year`/`.Month`/`.Day`/`.Hour`/`.Minute` in whatever
+offset that value happens to carry, so a fixture that calls it after `PadUntilExact`, `WaitUntilExact` or
+a Continue anchor becomes TZ-sensitive by ordering rather than by call. The scripted fixtures therefore
+use Chronological order and only the instant-preserving instructions; they pass, rather than skip, under
+`TZ=UTC`, `America/New_York`, `Australia/Lord_Howe` and `Asia/Kathmandu`.
+
## Running tests
Full .NET gate: