using System.Collections.Concurrent; using System.Net; using System.Security.Claims; using System.Text; using System.Text.Json; using Dapper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; // Called only after the parent harness verifies the literal synthetic-only database and creates its own actors/data. internal static class ProjectExportDatabaseTests { private sealed record Packet(string Action,string Parameter,int ID,string[] Expected,bool Ordered=false,bool BookMetadata=false); public static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,int owner,int other,int project,int book,int chapter,int scene,int character) { using(var db=factory.CreateConnection()) { if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Phase2_20261103_2305" || await db.ExecuteScalarAsync("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")!=1) throw new InvalidOperationException("Export fixtures require the verified synthetic-only database."); await db.ExecuteAsync("IF NOT EXISTS(SELECT 1 FROM dbo.SceneNoteTypes WHERE TypeName=N'Research Note') INSERT dbo.SceneNoteTypes(TypeName,SortOrder) VALUES(N'Research Note',20);INSERT dbo.SceneNotes(SceneID,SceneNoteTypeID,NoteTitle,NoteText,SortOrder) SELECT @scene,SceneNoteTypeID,N'Research Ω',@longNote,2 FROM dbo.SceneNoteTypes WHERE TypeName=N'Research Note';",new{scene,longNote="\n"+string.Concat(Enumerable.Repeat("Long research — 雪 café 🖋\n",5000))}); var foreign=await db.ExecuteScalarAsync("SELECT TOP(1) ProjectID FROM dbo.ProjectUserAccess WHERE UserID=@other AND AccessRole=N'Owner' ORDER BY ProjectID",new{other}); await db.ExecuteAsync("INSERT dbo.Characters(ProjectID,CharacterName) VALUES(@foreign,N'Foreign-only marker Ω')",new{foreign}); } var sourceBackup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,owner))!; await files.CaptureAsync(sourceBackup); var point=await new ProjectRestorePointRepository(factory).CreateAsync(project,"Synthetic downloadable restore point","Manual",JsonSerializer.Serialize(sourceBackup),"HTTP transfer fixture"); var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"}); builder.WebHost.UseUrls("http://127.0.0.1:0");builder.Logging.ClearProviders(); builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider(); builder.Services.AddAuthentication("ExportFixture").AddCookie("ExportFixture",options=>options.Events.OnRedirectToLogin=context=>{context.Response.StatusCode=401;return Task.CompletedTask;}); builder.Services.AddAuthorization();builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(factory);builder.Services.AddSingleton(files); builder.Services.AddScoped(); builder.Services.AddScoped();builder.Services.AddScoped(); builder.Services.AddScoped();builder.Services.AddScoped(); builder.Services.AddScoped();builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped();builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(new NoActivity()); builder.Services.AddScoped(); builder.Services.AddControllersWithViews(options=>options.Filters.Add()).AddApplicationPart(typeof(ExportsController).Assembly); await using var app=builder.Build();var errors=new ConcurrentQueue(); app.Use(async(context,next)=>{ if(int.TryParse(context.Request.Headers["X-Synthetic-Actor"],out var actor) && (actor==owner||actor==other))context.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,actor.ToString())],"ExportFixture")); try {await next();} catch(Exception ex){errors.Enqueue(ex.Message);context.Response.StatusCode=500;await context.Response.WriteAsync("Synthetic export failed.");} }); app.UseAuthorization();app.MapControllerRoute("default","{controller=Exports}/{action=StoryBible}/{id?}"); await app.StartAsync();var address=app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); using var client=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){BaseAddress=new Uri(address)}; var packets=new[]{ new Packet("StoryBible","projectId",project,["Narrator Ω","Notebook 雨","Room Ω","Scene café"]), new Packet("NarrativeTimeline","projectId",project,["Scene café","Second empty scene"],true,true), new Packet("Character","id",character,["Narrator Ω","Knows the secret 雨","Observer 雪"]), new Packet("SceneBrief","id",scene,["Scene café","“Hello”—雪 🖋"],false,true), new Packet("ChapterBrief","id",chapter,["Chapter 雨","Goal Ω","Question café","Second empty scene"],true,true), new Packet("WritingSession","sceneId",scene,["Scene café","Check continuity 雨"],false,true), new Packet("ResearchPack","projectId",project,["Research Ω","Empty text attachment","Long research — 雪 café 🖋"],false,true), new Packet("Search","projectId",project,["Narrator Ω","Envelope Ω"]) }; var failures=new List();var coverage=new List{"Workflow,Format,HTTP,ContentAndMetadata,Ownership,IntendedScope"}; async Task Get(string route,int? actor) { using var request=new HttpRequestMessage(HttpMethod.Get,route);if(actor.HasValue)request.Headers.Add("X-Synthetic-Actor",actor.Value.ToString());return await client.SendAsync(request); } foreach(var packet in packets) { var canonical=new Dictionary(); foreach(var format in new[]{"html","markdown","text","md","txt"}) { var route=$"/Exports/{packet.Action}?{packet.Parameter}={packet.ID}&format={format}&q=%CE%A9"; using var response=await Get(route,owner);var content=await response.Content.ReadAsStringAsync(); if(response.StatusCode!=HttpStatusCode.OK){failures.Add($"{packet.Action}/{format}: HTTP {(int)response.StatusCode}; {errors.LastOrDefault()}");continue;} var decoded=format=="html"?WebUtility.HtmlDecode(content):content; foreach(var expected in packet.Expected)if(!decoded.Contains(expected,StringComparison.Ordinal))failures.Add($"{packet.Action}/{format}: missing expected fixture content {expected}"); if(decoded.Contains("Foreign-only marker",StringComparison.Ordinal))failures.Add(packet.Action+": foreign project content escaped scope"); if(packet.Ordered && !(decoded.IndexOf("Scene café",StringComparison.Ordinal)"text/html","markdown" or "md"=>"text/markdown",_=>"text/plain"}; if(response.Content.Headers.ContentType?.MediaType!=expectedType)failures.Add(packet.Action+": wrong content type"); if(format!="html" && response.Content.Headers.ContentDisposition?.FileName is null && response.Content.Headers.ContentDisposition?.FileNameStar is null)failures.Add(packet.Action+": missing download filename"); if(format=="html" && content.Contains("