using System.Diagnostics; using System.Security.Claims; using System.Text.Json; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.Manuscript; using PlotLine.Services.NativeCompanion; // Explicit opt-in Development integration. Creates only a new synthetic project; // never updates an existing author's book. A copy-only backup precedes provisioning. internal static class ChapterAcceptanceDevelopmentTests { public static async Task Run(string[] args) { if (!OperatingSystem.IsLinux() || args.Length != 2 || !int.TryParse(args[1], out var user) || user <= 0) throw new InvalidOperationException("Use --chapter-acceptance-dev "); var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true }; foreach (var value in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(value); using var process = Process.Start(start)!; var environment = await process.StandardOutput.ReadToEndAsync(); await process.WaitForExitAsync(); if (process.ExitCode != 0) throw new Exception("Development configuration inaccessible"); var connection = environment.Split('\n').Single(l => l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\''); if (new SqlConnectionStringBuilder(connection).InitialCatalog != "PlotDirector_Development") throw new Exception("Wrong database"); using (var db = new SqlConnection(connection)) { await db.OpenAsync(); using var verify = new SqlCommand("SELECT DB_NAME()", db); if ((string?)await verify.ExecuteScalarAsync() != "PlotDirector_Development") throw new Exception("Wrong database"); var backup = $"/var/opt/mssql/backup/chapter-acceptance-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak"; using var command = new SqlCommand("BACKUP DATABASE [PlotDirector_Development] TO DISK=@path WITH COPY_ONLY,CHECKSUM,COMPRESSION", db) { CommandTimeout = 300 }; command.Parameters.AddWithValue("@path", backup); await command.ExecuteNonQueryAsync(); var check = new ProcessStartInfo("sudo"); foreach (var value in new[] { "-n", "docker", "exec", "atlas-sql-server", "test", "-s", backup }) check.ArgumentList.Add(value); using var backupCheck = Process.Start(check)!; await backupCheck.WaitForExitAsync(); if (backupCheck.ExitCode != 0) throw new Exception("Backup missing"); } var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["ConnectionStrings:DefaultConnection"] = connection, ["Features:ParagraphManuscripts"] = "true" }).Build(); var factory = new SqlConnectionFactory(config); var projects = new ProjectRepository(factory); var project = await projects.SaveAsync(new() { ProjectName = "Synthetic chapter acceptance " + Guid.NewGuid().ToString("N"), CreatedByUserID = user }, user, null); try { var books = new BookRepository(factory); var book = await books.SaveAsync(new() { ProjectID = project, BookTitle = "Synthetic chapter scale qualification", CreatedByUserID = user }); var lookup = await new LookupRepository(factory).GetAllAsync(); var canonicalChapters = new List(); var canonicalScenes = new List(); for (var i = 0; i < 48; i++) { var chapter = await new ChapterRepository(factory).SaveAsync(new() { BookID = book, ChapterNumber = i + 1, ChapterTitle = "Synthetic chapter " + i, RevisionStatusID = lookup.RevisionStatuses.First().RevisionStatusID, SortOrder = i + 1 }); canonicalChapters.Add(chapter); canonicalScenes.Add(await new SceneRepository(factory).SaveAsync(new() { ChapterID = chapter, SceneNumber = 1, SceneTitle = "Synthetic scene " + i, RevisionStatusID = lookup.RevisionStatuses.First().RevisionStatusID, TimeModeID = lookup.TimeModes.First().TimeModeID, TimeConfidenceID = lookup.TimeConfidences.First().TimeConfidenceID, SortOrder = 1 })); } var rows = new List(); var spans = new List(); var position = 0; for (var chapter = 0; chapter < 48; chapter++) { var count = chapter == 0 ? 233 : chapter == 47 ? 128 : 176; var firstOrdinal = rows.Count; for (var n = 0; n < count; n++) { var text = n == 0 ? $"Synthetic chapter {chapter}\r" : $"Synthetic paragraph {rows.Count}: " + new string('x', 420) + "\r"; rows.Add(new() { Ordinal = rows.Count, Start = position, End = position + text.Length, Text = text, Outline = n == 0 ? 1 : 10 }); position += text.Length; } spans.Add(new() { ChapterId = canonicalChapters[chapter], SceneId = canonicalScenes[chapter], Start = firstOrdinal + 2, End = rows.Count, Title = "Synthetic scene " + chapter }); } var repository = new ParagraphManuscriptRepository(factory); var checkpoints = new ChapterSyncRepository(factory); var original = ParagraphManuscriptEngine.Bootstrap(book, project, Guid.NewGuid(), rows.ToArray(), spans); original.Mode = "Manual"; original.SnapshotHash = ParagraphManuscriptEngine.Hash(original.Paragraphs.Select(p => p.Occurrence).ToArray()); original = await repository.Save(user, original, -1, Guid.NewGuid()); Check(original.Paragraphs.Count == 8457, "Representative 8,457-paragraph, 48-chapter fixture"); var session = Guid.NewGuid(); var instance = Guid.NewGuid(); const string grant = "synthetic-chapter-test"; var presence = new NativePresenceStore(TimeProvider.System); void Observe(long revision = 0) => Check(presence.Put(user, grant, DateTimeOffset.UtcNow.AddHours(1), instance, session, new() { BookId = book, ManuscriptId = original.ManuscriptId, Revision = revision, Sequence = DateTime.UtcNow.Ticks, WordAvailable = true, WordRunning = true, WordSaved = true, CanChapterSync = true }), "Eligible saved Word session"); var access = new WordCompanionRepository(factory); var imports = new OnboardingBuildRepository(factory); var reconciliation = new ParagraphManuscriptService(repository, access, books, imports, new ManuscriptTextStatisticsService(new ManuscriptTextStatisticsRepository(factory), imports), config); var service = new ChapterSyncService(repository, checkpoints, access, reconciliation, presence, TimeProvider.System); var controller = new NativeChapterSyncController(service) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } }; controller.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier, user.ToString()), new("NativeCompanion.Grant", grant)], "SyntheticAuthenticatedFixture")); async Task Accept(ChapterObservation proof) { Observe(proof.WordRevision); var elapsed = Stopwatch.StartNew(); var action = await controller.Validate(book, proof); var reply = (action as OkObjectResult)?.Value as ChapterSyncReply; if(reply?.Accepted != true) throw new Exception($"Chapter acceptance refused after {elapsed.ElapsedMilliseconds} ms: {((action as ObjectResult)?.Value as ChapterSyncReply)?.Message ?? action.GetType().Name}"); Check(true, "Controller returned accepted after durable commit"); Check(elapsed.Elapsed < TimeSpan.FromSeconds(15), $"Acceptance fits the client deadline ({elapsed.ElapsedMilliseconds} ms)"); return reply!; } ChapterObservation Proof(ParagraphManuscript state, int chapter) { var part = ChapterCheckpointEngine.Parts(state)[chapter]; var evidence = part.Rows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId.Length > 0 ? p.Occurrence.NativeId : (p.Occurrence.Ordinal + 1).ToString("X8"), Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToArray(); return new() { InstanceId = instance, SessionId = session, ManuscriptId = original.ManuscriptId, BaseRevision = state.Revision, ChapterId = part.Chapter.CanonicalId, Start = part.Rows[0].Occurrence.Start, End = part.Rows[^1].Occurrence.End, NextHeadingId = part.End < state.Paragraphs.Count ? (state.Paragraphs[part.End].Occurrence.NativeId.Length > 0 ? state.Paragraphs[part.End].Occurrence.NativeId : (part.End + 1).ToString("X8")) : "", ContentHash = ChapterFingerprint.Content(part.Rows.Select(p => p.Occurrence.Text)), IdentityHash = ChapterFingerprint.Identity(evidence), Paragraphs = evidence }; } Observe(); var repair = await service.Repair(user, book, instance, session); var first = Proof(original, 0); first.OperationId = repair; await Accept(first); var saved = (await repository.Get(user, book))!; Check(saved.ChapterCheckpoints.Count == 1 && (await checkpoints.List(user, book, session, 0)).Count == 1, "Fresh database read confirms durable checkpoint"); Check(saved.Paragraphs.Select(p => (p.Occurrence.Id, p.Occurrence.Text, p.SceneId, p.ChapterId)).SequenceEqual(original.Paragraphs.Select(p => (p.Occurrence.Id, p.Occurrence.Text, p.SceneId, p.ChapterId))), "Adoption preserves every GUID, exact paragraph and scene assignment"); var scenePosition = ChapterCheckpointEngine.Validate(saved, first, DateTime.UtcNow).Positions.First(p => p.SceneId.HasValue); Check((await checkpoints.Position(user, book, original.ManuscriptId, session, 0, scenePosition.Start))?.SceneID == canonicalScenes[0], "Writing Context resolves the current chapter before unrelated chapters finish"); presence = new NativePresenceStore(TimeProvider.System); // Simulate process loss: trust is recovered through repository, not an in-memory cache. // A fresh service reads the committed manifest even though no other chapter has been processed. service = new ChapterSyncService(repository, checkpoints, access, reconciliation, presence, TimeProvider.System); Observe(); var manifest = await service.Manifest(user, book, session, 0); Check(manifest.Chapters.Count(c => c.State == "Synchronised") == 1, "Interrupted work resumes from the persisted first checkpoint"); controller = new NativeChapterSyncController(service) { ControllerContext = controller.ControllerContext }; await Accept(first); // Same request is idempotent after restart. repair = await service.Repair(user, book, instance, session); var second = Proof(saved, 1); second.OperationId = repair; await Accept(second); saved = (await repository.Get(user, book))!; Check(saved.ChapterCheckpoints.Count == 2 && saved.SnapshotHash == ParagraphManuscriptEngine.Hash(saved.Paragraphs.Select(p => p.Occurrence).ToArray()), "Multiple durable adoptions retain the coherent full-snapshot hash"); Check(presence.ChapterProgress(user, book, instance, session, 0)?.Matching == 2, "Live progress counts persisted acceptances immediately"); var partial = await service.Finish(user, grant, book, new() { InstanceId = instance, SessionId = session, WordRevision = 0 }); Check(partial.State == "Needs review" && partial.Matching == 2 && partial.Total == 48, "Two accepted chapters cannot imply whole-manuscript completion"); var unknownIssue=await service.Finish(user,grant,book,new(){InstanceId=instance,SessionId=session,WordRevision=0,HasIssues=true}); Check(unknownIssue.State=="Needs review"&&unknownIssue.Matching==2&&(await checkpoints.List(user,book,session,0)).Count==2,"An unidentified structural failure does not revoke an unrelated accepted chapter"); var unchanged = Proof(saved, 0); await Accept(unchanged); var changed = Proof(saved, 0); changed.WordRevision = 1; var partRows = ChapterCheckpointEngine.Parts(saved)[0].Rows; changed.Paragraphs = partRows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId, Text = p.Occurrence.Text, Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToArray(); changed.Paragraphs[1].Text = "Changed synthetic paragraph.\r"; changed.Paragraphs[1].Length = changed.Paragraphs[1].Text!.Length; changed.End = changed.Start + changed.Paragraphs.Sum(p => p.Length); changed.ContentHash = ChapterFingerprint.Content(changed.Paragraphs.Select(p => p.Text!)); changed.IdentityHash = ChapterFingerprint.Identity(changed.Paragraphs); Observe(1); var detection = (await controller.Validate(book, changed) as OkObjectResult)?.Value as ChapterSyncReply; Check(detection?.State == "Changed" && !detection.AllowText, "Manual mode detects edits without silently authorising reconciliation"); // Consume the old repair command before requesting a new revision-scoped operation. presence.TakeNavigation(user, grant, instance, session); changed.OperationId = await service.Repair(user, book, instance, session, 1); changed.Reconcile = true; await Accept(changed); var reconciled = (await repository.Get(user, book))!; Check(reconciled.Paragraphs.Skip(partRows.Length).Select(p => (p.Occurrence.Id, p.Occurrence.NativeId, p.Occurrence.Text, p.ChapterId, p.SceneId, p.PositionVerified, p.Story)).SequenceEqual(saved.Paragraphs.Skip(partRows.Length).Select(p => (p.Occurrence.Id, p.Occurrence.NativeId, p.Occurrence.Text, p.ChapterId, p.SceneId, p.PositionVerified, p.Story))) && reconciled.Scenes.Select(s => s.Id).SequenceEqual(saved.Scenes.Select(s => s.Id)), "Selective reconciliation preserves unaffected mappings and scene identities"); var sourceBefore = (await imports.ListSceneManuscriptSourcesByBookAsync(book)).Single(s => s.SceneID == canonicalScenes[1]); foreach(var insert in new[]{true,false}) { var current = (await repository.Get(user, book))!; var edit = Proof(current, 0); edit.WordRevision = insert ? 2 : 3; var evidence = ChapterCheckpointEngine.Parts(current)[0].Rows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId, Text = p.Occurrence.Text, Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToList(); if(insert) evidence.Insert(2,new() { NativeId="10000001", Text="Inserted synthetic paragraph.\r", Length="Inserted synthetic paragraph.\r".Length, Outline=10 }); else evidence.RemoveAll(p=>p.NativeId=="10000001"); edit.Paragraphs=evidence.ToArray();edit.End=edit.Start+evidence.Sum(p=>p.Length); edit.ContentHash=ChapterFingerprint.Content(evidence.Select(p=>p.Text!));edit.IdentityHash=ChapterFingerprint.Identity(evidence); Observe(edit.WordRevision);presence.TakeNavigation(user,grant,instance,session); edit.OperationId=await service.Repair(user,book,instance,session,edit.WordRevision);edit.Reconcile=true; await Accept(edit); var sourceAfter=(await imports.ListSceneManuscriptSourcesByBookAsync(book)).Single(s=>s.SceneID==canonicalScenes[1]); var shift=insert?1:0; Check(sourceAfter.SourceText==sourceBefore.SourceText&&sourceAfter.SourceKind==sourceBefore.SourceKind&&sourceAfter.SourceStartParagraph==sourceBefore.SourceStartParagraph+shift&&sourceAfter.SourceEndParagraph==sourceBefore.SourceEndParagraph+shift&&sourceAfter.WordStartParagraphIndex==sourceBefore.WordStartParagraphIndex+shift&&sourceAfter.WordEndParagraphIndex==sourceBefore.WordEndParagraphIndex+shift, "Chapter "+(insert?"insertion":"deletion")+" shifts later source bounds without replacing unrelated prose"); } reconciled=(await repository.Get(user,book))!; var stale = Proof(reconciled, 0); stale.BaseRevision = 0; stale.WordRevision = 3; var rejected = (await controller.Validate(book, stale) as ConflictObjectResult)?.Value as ChapterSyncReply; Check(rejected?.Accepted == false && rejected.Message.Contains("Stale"), "Rejected chapter returns a specific validation reason"); var freshSession = Guid.NewGuid(); Check((await checkpoints.List(user, book, freshSession, 1)).Count == 0 && (await repository.Get(user, book))!.ChapterCheckpoints.Count >= 2, "New sessions preserve durable evidence and require fresh absolute position verification"); } finally { await projects.ArchiveForUserAsync(project, user); Console.WriteLine($"Synthetic project {project} archived for evidence; existing author books were not modified."); } } private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); Console.WriteLine("PASS " + message); } }