diff --git a/Docs/Sprints/2026-11-03-phase2-export-coverage.csv b/Docs/Sprints/2026-11-03-phase2-export-coverage.csv new file mode 100644 index 00000000..9babb9ef --- /dev/null +++ b/Docs/Sprints/2026-11-03-phase2-export-coverage.csv @@ -0,0 +1,43 @@ +Workflow,Format,HTTP,ContentAndMetadata,Ownership,IntendedScope +StoryBible,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +StoryBible,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +StoryBible,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +StoryBible,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +StoryBible,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +NarrativeTimeline,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +NarrativeTimeline,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +NarrativeTimeline,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +NarrativeTimeline,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +NarrativeTimeline,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Character,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Character,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Character,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Character,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Character,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +SceneBrief,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +SceneBrief,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +SceneBrief,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +SceneBrief,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +SceneBrief,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ChapterBrief,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ChapterBrief,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ChapterBrief,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ChapterBrief,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ChapterBrief,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +WritingSession,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +WritingSession,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +WritingSession,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +WritingSession,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +WritingSession,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ResearchPack,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ResearchPack,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ResearchPack,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ResearchPack,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ResearchPack,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Search,html,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Search,markdown,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Search,text,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Search,md,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +Search,txt,200,Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim +ProjectBackup,json,200,Twelve files and gallery metadata,Other author rejected,Portable project data with explicitly recorded remaining SI scope limits +RestorePointDownload,json,200,Twelve embedded files retained,Other author and anonymous rejected,Stored project restore point; same backup format diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 9fed2015..f38563f4 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -181,3 +181,13 @@ The asset checkpoint's full regression harness passed: 405 checks, exit 0 (`/tmp A real isolated MVC host reproduced HTTP 400 for 5 MiB JSON carried as a form value on Preview, Import and ValidationReport. Small values and a 5 MiB multipart file succeeded; the default per-value form parser limit was the blocker after upload/preview. ImportsController now allows 32 MiB per form value, leaving existing request-body/upstream limits unchanged. This is not a claim that arbitrary-size backups can pass the deployed reverse proxy. After repair, all three production POST actions bind the complete 5 MiB payload and Unicode suffix with matching SHA-256; multipart bytes also match. Missing antiforgery tokens return 400 and anonymous requests return 401. The fixture exercises production controller metadata/model binding with an action filter that reports bound data; service/SQL behavior is covered separately, and no live authenticated acceptance is implied. Evidence: `/tmp/plotdirector-phase2-import-transport-before.log` (three failures), `/tmp/plotdirector-phase2-import-transport-after.log` (pass). Build zero warnings/errors; preceding asset checkpoint's 405-check harness passed. No Development changes. + +### Reference/brief export HTTP and SQL matrix + +All eight document workflows passed HTML, Markdown, text and the `md`/`txt` aliases (40 combinations): Story Bible, Narrative Timeline, Character Reference, Scene Brief, Chapter Brief, Writing Session Brief, Research Pack and Search Results. The fixture uses real repositories/stored procedures, rendering service, controllers, CurrentUserService and ProjectAccessFilter against the isolated database. Only activity logging and the loopback synthetic identity boundary are fixtures; no application workers run. Another author and anonymous caller are rejected, missing positive IDs return 404, and foreign-project search content is excluded. + +Verified supported content, Unicode/punctuation, book subtitles, scene ordering/empty scene presence, 5,000 retained research lines, HTML encoding of literal script markup, content types/download names and exact alias equivalence. Full project and saved restore-point HTTP downloads retain all twelve uploaded files and gallery metadata. These are reference/brief exports; they are not manuscript prose or full-project round-trip formats. `2026-11-03-phase2-export-coverage.csv` records the workflow/format matrix. + +Confirmed defect: all eight actions returned a successful empty document when an ID was missing/zero. Controllers now reject invalid context with a clear 400 response; normal ownership checks remain intact. The initial Search test also expected a notebook whose name did not match the query; corrected that test expectation, not product search behavior. + +Evidence: `/tmp/plotdirector-phase2-exports-before.log` (invalid-context failures), `/tmp/plotdirector-phase2-exports-after.log` (pass); build zero warnings/errors. Next: legacy JSON import structural validation/content/rollback and Word manuscript/core-import workflows. No Development writes/deployment. diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index b7ff389f..3895b818 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -73,7 +73,7 @@ if (args.Contains("--maps-story-dev-fixture")) if(args.Contains("--project-transfer-database")) { - try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only")); } + try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only")); } catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; } return; } diff --git a/PlotLine.Tests/ProjectExportDatabaseTests.cs b/PlotLine.Tests/ProjectExportDatabaseTests.cs new file mode 100644 index 00000000..086083b1 --- /dev/null +++ b/PlotLine.Tests/ProjectExportDatabaseTests.cs @@ -0,0 +1,137 @@ +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("