using System.Text.Json; using Dapper; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services.Manuscript; internal static class ParagraphChapterQualificationTests { // Explicit disposable Windows fixture only; not an application migration or an adoption endpoint. public static async Task Run(bool repair) { var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")); var connection=line[(line.IndexOf('=')+1)..].Trim().Trim('"','\'');var builder=new SqlConnectionStringBuilder(connection); if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Development required"); await using var db=new SqlConnection(connection);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database"); if(!await db.ExecuteScalarAsync("SELECT CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.Books WHERE BookID=10151 AND ProjectID=8173 AND BookTitle LIKE N'%QA%') THEN 1 ELSE 0 END AS bit)"))throw new Exception("Disposable fixture identity changed"); var user=await db.QuerySingleAsync("SELECT UserID FROM dbo.ProjectUserAccess WHERE ProjectID=8173 AND AccessRole=N'Owner' AND IsActive=1"); var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"ConnectionStrings:DefaultConnection",connection}}).Build(); var repository=new ParagraphManuscriptRepository(new SqlConnectionFactory(configuration)); var current=await repository.Get(user,10151)??throw new Exception("Missing qualification manuscript"); var source=await repository.Capture(user,10151)??throw new Exception("Missing immutable accepted capture"); var raw=source.NativeParagraphs??throw new Exception("Missing original paragraph identities"); if(current.ProjectId!=8173||current.Paragraphs.Count!=9||raw.Length!=9||current.Evidence.Count!=0||current.Undo.Count!=0||current.Scenes.Count!=2||current.Scenes.Any(s=>s.Retired)||current.Chapters.Count!=2||source.PreviewID!=Guid.Parse("50e741d8-d42a-47bc-be48-2ad23f91b83d")||!Guid.TryParse(source.CompanionDocumentIdentifier,out var manuscript)||current.ManuscriptId!=manuscript)throw new Exception("Qualified source or author decisions changed; refusing automatic fixture repair"); if((await repository.Status(user,10151))?.Paused!=false)throw new Exception("Fixture analysis/import active"); var original=raw.OrderBy(p=>p.Ordinal).ToArray();var headings=current.Chapters.OrderBy(c=>Array.FindIndex(original,p=>p.Id==c.HeadingId)).ToArray(); if(headings.Any(c=>c.HeadingId==Guid.Empty)||original[0].Id!=headings[0].HeadingId||original[5].Id!=headings[1].HeadingId||original.Where((p,i)=>p.Text!=current.Paragraphs[i].Occurrence.Text).Count()>1)throw new Exception("Fixture no longer matches the qualified single-edit source"); // One original scene in each chapter makes the original import grouping exact, not inferred by name. var groups=new List(); for(int n=0;ns.ChapterId==chapter.CanonicalId);var start=Array.FindIndex(original,p=>p.Id==chapter.HeadingId)+2;var end=n+1p.Id==headings[n+1].HeadingId):original.Length;groups.Add(new(){SceneId=scene.CanonicalId,ChapterId=chapter.CanonicalId,Title=scene.Title,Start=start,End=end});} var candidate=ParagraphManuscriptEngine.Bootstrap(10151,8173,current.ManuscriptId,original,groups); foreach(var scene in candidate.Scenes){var generated=scene.Id;scene.Id=current.Scenes.Single(s=>s.CanonicalId==scene.CanonicalId).Id;foreach(var row in candidate.Paragraphs.Where(p=>p.SceneId==generated))row.SceneId=scene.Id;} candidate.DocumentName=current.DocumentName;candidate.Mode=current.Mode;candidate.Revision=current.Revision;candidate.SessionId=current.SessionId;candidate.WordRevision=current.WordRevision;candidate.EventPositions=current.EventPositions; ParagraphManuscriptEngine.Reconcile(candidate,current.Paragraphs.Select(p=>p.Occurrence).ToArray()); if(!candidate.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(original.Select(p=>p.Id))||!candidate.Paragraphs.Select(p=>p.Occurrence.Text).SequenceEqual(current.Paragraphs.Select(p=>p.Occurrence.Text))||candidate.Paragraphs.Skip(6).Any(p=>p.ChapterId!=headings[1].CanonicalId||p.SceneId!=candidate.Scenes[1].Id||!p.PositionVerified))throw new Exception("Original source continuity or chapter-local recovery could not be established"); var maps=await db.QueryAsync("SELECT m.SceneID FROM dbo.OnboardingManuscriptBuilds b JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=b.OnboardingManuscriptBuildID WHERE b.PreviewID=@preview",new{preview=source.PreviewID}); if(!maps.Order().SequenceEqual(candidate.Scenes.Select(s=>s.CanonicalId).Order()))throw new Exception("Original canonical build mapping changed"); Console.WriteLine("PASS book 10151: immutable original nine GUIDs and two canonical build maps survive; chapter-local replay preserves latest raw Word prose and chapter-two membership"); if(!repair)return; var saved=await repository.Save(user,candidate,current.Revision,Guid.NewGuid()); foreach(var ordinal in new[]{1,6}){var p=saved.Paragraphs[ordinal];var expected=saved.Scenes.Single(s=>s.Id==p.SceneId).CanonicalId;var position=await repository.Position(user,10151,saved.ManuscriptId,saved.SessionId,saved.WordRevision,p.Occurrence.Start);if(position?.SceneID!=expected||position.ChapterID!=p.ChapterId)throw new Exception("Saved cursor map verification failed");} var repeated=ParagraphManuscriptEngine.Clone(saved);ParagraphManuscriptEngine.Reconcile(repeated,saved.Paragraphs.Select(p=>p.Occurrence).ToArray()); if(!repeated.Paragraphs.Select(p=>(p.Occurrence.Id,p.SceneId,p.ChapterId,p.PositionVerified)).SequenceEqual(saved.Paragraphs.Select(p=>(p.Occurrence.Id,p.SceneId,p.ChapterId,p.PositionVerified))))throw new Exception("Subsequent unchanged save changes restored mapping"); Console.WriteLine("PASS repaired only disposable book 10151 using CAS: original opaque scene IDs retained, paragraph 2/7 positional lookups resolve their own scenes, unchanged re-sync remains stable; no grouping confirmation or Word edits"); } }