PlotDirector/PlotLine.Tests/WriterIntelligenceDatabaseTests.cs

109 lines
15 KiB
C#

using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotDirector.Companion.Protocol;
using PlotLine.Data;
using PlotLine.Models;
internal static class WriterIntelligenceDatabaseTests
{
public static async Task Run()
{
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var part in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(part);
using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Configuration unavailable");
var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
var connection=new SqlConnectionStringBuilder(raw);if(connection.InitialCatalog!="PlotDirector_Development")throw new Exception("Unexpected configured database");connection.InitialCatalog="PlotDirector_WriterIntelligent_20261115";
using var db=new SqlConnection(connection.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=connection.InitialCatalog)throw new Exception("Wrong disposable target");
void Check(bool ok,string text){if(!ok)throw new Exception(text);Console.WriteLine("PASS Writer database "+text);}
var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connection.ConnectionString}}).Build());
var rows=await db.QuerySingleAsync<(int UserID,int Other,int ProjectID,int BookID,int ForeignBook,int ChapterID,int EmptyChapter,int SceneID)>("""
DECLARE @u int,@o int,@p int,@b int,@f int,@c int,@empty int,@s int,@l int,@revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY SortOrder);
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@work.invalid','Synthetic work author','not-a-credential');SET @u=SCOPE_IDENTITY();
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@work.invalid','Synthetic other','not-a-credential');SET @o=SCOPE_IDENTITY();
INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),'Work fixture',10,100,100,100,100,0,0,0);SET @l=SCOPE_IDENTITY();
INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@u,@l,1,1,'2030-01-01');
INSERT dbo.Projects(ProjectName) VALUES('Synthetic intelligent Writer');SET @p=SCOPE_IDENTITY();
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@p,@u,'Owner',1);
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Synthetic Writer',1,1);SET @b=SCOPE_IDENTITY();
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Foreign target',2,2);SET @f=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Synthetic chapter',1,1,@revision);SET @c=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Chapter without a scene',2,2,@revision);SET @empty=SCOPE_IDENTITY();
INSERT dbo.Scenes(ChapterID,SceneTitle,SceneNumber,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) VALUES(@c,'Synthetic scene',1,1,@revision,(SELECT TOP(1) TimeModeID FROM dbo.TimeModes ORDER BY SortOrder),(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY SortOrder));SET @s=SCOPE_IDENTITY();
SELECT @u UserID,@o Other,@p ProjectID,@b BookID,@f ForeignBook,@c ChapterID,@empty EmptyChapter,@s SceneID;
""");
var user=rows.UserID;var book=rows.BookID;
// This owned disposable database is removed after qualification; never retarget this test.
var work=new WriterWorkRepository(factory,TimeProvider.System);var id=Guid.NewGuid();
await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=id,ChapterID=rows.ChapterID,Kind="Editing"});
await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=id,ChapterID=rows.ChapterID,Kind="Editing"});
Check((await work.Read(user,book)).Count==1,"idempotent starts do not duplicate sessions");
var refused=false;try{await work.Read(rows.Other,book);}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"private work history denies another author");
refused=false;try{await work.Execute(new{Action="start",UserID=user,BookID=rows.ForeignBook,SessionID=Guid.NewGuid(),ChapterID=rows.ChapterID,Kind="Reading"});}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"a chapter cannot be attached to another book");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET BrowserReceivedUtc=DATEADD(second,-12,SYSUTCDATETIME()) WHERE SessionID=@id",new{id});
await work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=1,Engaged=true});
var engaged=(await work.Read(user,book)).Single().EngagedSeconds;
await work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=1,Engaged=true});
Check(engaged is >=11 and <=14&&(await work.Read(user,book)).Single().EngagedSeconds==engaged,"engaged time is server-bounded and duplicate heartbeat is inert");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET BrowserReceivedUtc=DATEADD(hour,-1,SYSUTCDATETIME()) WHERE SessionID=@id",new{id});
await work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=2,Engaged=true});
Check((await work.Read(user,book)).Single().EngagedSeconds==engaged,"long idle or network gap does not become active time");
await Task.WhenAll(work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=3,Engaged=true}),work.Execute(new{Action="heartbeat",UserID=user,BookID=book,SessionID=id,Sequence=4,Engaged=true}));
Check((await work.Read(user,book)).Single().BrowserSequence==4,"concurrent out-of-order heartbeats retain the highest sequence");
var audio=Guid.NewGuid();var instance=Guid.NewGuid();var document=Guid.NewGuid();
await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=audio,ChapterID=rows.ChapterID,Kind="AudioReview",NativeInstance=instance,NativeDocument=document,NativeGrant="synthetic-grant"});
Check((await work.Read(user,book)).Count(x=>x.EndedUtc==null)==1,"starting another activity closes the prior session without overlapping book timers");
var value=new AudioReviewObservation{BookID=book,ReviewID=audio,Sequence=1,State="playing",MediaKey="synthetic-media",PositionSeconds=100,DurationSeconds=1000,Operations=["play","pause","back15","forward15"]};
await work.Media(user,book,instance,document,"synthetic-grant",value);
Check((await work.Read(user,book)).First(x=>x.SessionID==audio).PlaybackSeconds==0,"initial playing position alone establishes no listening interval");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET MediaReceivedUtc=DATEADD(second,-10,SYSUTCDATETIME()) WHERE SessionID=@audio",new{audio});
value.Sequence=2;value.PositionSeconds=110;await work.Media(user,book,instance,document,"synthetic-grant",value);
var measured=(await work.Read(user,book)).First(x=>x.SessionID==audio);
Check(measured.PlaybackSeconds is >9 and <=10.1&&measured.UniqueSeconds==10,"consecutive native telemetry records playback and unique coverage");
await work.Media(user,book,instance,document,"synthetic-grant",value);
Check((await work.Read(user,book)).First(x=>x.SessionID==audio).PlaybackSeconds==measured.PlaybackSeconds,"retry after lost media acknowledgement cannot inflate time");
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET MediaReceivedUtc=DATEADD(second,-10,SYSUTCDATETIME()),PositionSeconds=100 WHERE SessionID=@audio",new{audio});
value.Sequence=3;await work.Media(user,book,instance,document,"synthetic-grant",value);measured=(await work.Read(user,book)).First(x=>x.SessionID==audio);
Check(measured.PlaybackSeconds>19&&measured.UniqueSeconds==10,"replay increments listening duration while unique coverage remains unchanged");
refused=false;try{await work.Media(user,book,Guid.NewGuid(),document,"synthetic-grant",value);}catch(UnauthorizedAccessException){refused=true;}Check(refused,"media ingestion pins exact instance, document and grant");
value.Sequence=4;value.TextModified=true;var reply=await work.Media(user,book,instance,document,"synthetic-grant",value);
Check(reply.Command=="pause"&&reply.CommandID.HasValue,"real text modification requests pause when preference is enabled");
value.Sequence=5;value.TextModified=false;value.State="paused";value.AcknowledgedCommandID=reply.CommandID;reply=await work.Media(user,book,instance,document,"synthetic-grant",value);
Check(reply.Command==null,"pause acknowledgement never causes automatic resume");
await work.Execute(new{Action="preference",UserID=user,BookID=book,SessionID=audio,PauseOnEdit=false});
Check((await work.State(user,book)).Current?.SessionID==audio&&!(await work.State(user,book)).PauseOnEdit,"lightweight state reads the active session and saved audio preference");
await work.Execute(new{Action="end",UserID=user,BookID=book,SessionID=audio,Note="Return to the scene objective"});
Check((await work.Read(user,book)).First(x=>x.SessionID==audio).Note=="Return to the scene objective","explicit return note and end are retained");
Check((await work.State(user,book)).Current==null&&!(await work.State(user,book)).PauseOnEdit,"audio preference survives the end of a review without loading history");
var days=await work.Calendar(user,book,DateTime.UtcNow.Year);Check(days.Any(x=>x.AudioReview>0&&x.PlaybackSeconds>19)&&days.Any(x=>x.Editing>0),"calendar includes editing and audio even without word growth");
var schedule=new WritingScheduleRepository(factory);var planning=new WriterPlanningRepository(factory);
var plan=await schedule.CreateWritingPlanAsync(new(){UserID=user,ProjectID=rows.ProjectID,BookID=book,PlanName="Synthetic reviewed plan",GoalType="Revision",StartDate=DateTime.Today,DeadlineDate=DateTime.Today.AddDays(30),AvailableDaysJson="[{\"day\":\"Monday\",\"minutes\":120}]",SessionLengthMinutes=120,IsActive=true});
var context=await planning.Context(user,plan);Check(context.Chapters==2&&context.Scenes==1&&context.ExistingTasks==0,"empty-schedule diagnostics report actual chapter, scene and existing-task counts");
var candidates=await planning.Read(user,plan,"candidates");Check(candidates.Any(x=>x.SceneID==rows.SceneID)&&candidates.Any(x=>x.ChapterID==rows.EmptyChapter&&x.SceneID==null),"planning includes imported statuses and chapters without manual scene tasks");
var item=new WriterPlanActivity{BookID=book,ChapterID=rows.EmptyChapter,Minutes=30,ScheduledDate=DateTime.Today,Kind="Edit"};
await planning.Save(user,plan,[item]);var saved=await planning.Read(user,plan);
Check(saved.Count==1&&(await schedule.GetWritingPlansForManagementAsync(user)).Single().PlannedTaskCount==1,"chapter activity persists in the existing plan and management totals");
await planning.Complete(user,plan,saved[0].ActivityID);
refused=false;try{await planning.Save(user,plan,[item]);}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"regeneration cannot discard completed activities");
var manuscript=new ParagraphManuscriptRepository(factory);var paragraphText=string.Join(' ',Enumerable.Repeat("word",1000))+"\r";var text=string.Concat(Enumerable.Repeat(paragraphText,250));var state=new ParagraphManuscript{BookId=book,ProjectId=rows.ProjectID,ManuscriptId=Guid.NewGuid(),SnapshotHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))),Paragraphs=Enumerable.Range(0,250).Select(i=>new StoryParagraph{ChapterId=rows.ChapterID,Occurrence=new(){Id=Guid.NewGuid(),Ordinal=i,Start=i*paragraphText.Length,End=(i+1)*paragraphText.Length,Text=paragraphText}}).ToList()};
var canonical=await manuscript.Save(user,state,-1,Guid.NewGuid());var clock=Stopwatch.StartNew();
var checkpoint=Guid.NewGuid();await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=checkpoint,ChapterID=rows.ChapterID,Kind="Reading"});await work.Execute(new{Action="end",UserID=user,BookID=book,SessionID=checkpoint});await work.Calendar(user,book,DateTime.UtcNow.Year);clock.Stop();
var recorded=(await work.Read(user,book)).First(x=>x.SessionID==checkpoint);
Check(recorded.StartRevision==canonical.Revision&&recorded.EndRevision==canonical.Revision&&recorded.StartParagraphCount==250,"250,000-word manuscript checkpoints preserve accepted revision and paragraph count");
Console.WriteLine($"Writer 250,000-word explicit checkpoint + calendar measurement: {clock.ElapsedMilliseconds} ms; dashboard never tokenises this prose.");
var after=await manuscript.Get(user,book);Check(after!.Revision==canonical.Revision&&after.SnapshotHash==state.SnapshotHash,"activity and planning leave canonical manuscript unchanged");
var reviewEdits=Guid.NewGuid();await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=reviewEdits,ChapterID=rows.ChapterID,Kind="AudioReview",NativeInstance=instance,NativeDocument=document,NativeGrant="synthetic-grant"});
value=new(){BookID=book,ReviewID=reviewEdits,Sequence=1,State="playing",MediaKey="review-edits",PositionSeconds=0,PlaybackRate=1};await work.Media(user,book,instance,document,"synthetic-grant",value);
state.Paragraphs[0].Occurrence.Text="edit"+state.Paragraphs[0].Occurrence.Text[4..];state.SnapshotHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text)))));
var acceptedEdit=await manuscript.Save(user,state,canonical.Revision,Guid.NewGuid());
await db.ExecuteAsync("UPDATE dbo.WriterWorkSessions SET MediaReceivedUtc=DATEADD(second,-10,SYSUTCDATETIME()) WHERE SessionID=@reviewEdits",new{reviewEdits});value.Sequence=2;value.PositionSeconds=10;await work.Media(user,book,instance,document,"synthetic-grant",value);await work.Execute(new{Action="end",UserID=user,BookID=book,SessionID=reviewEdits});
var evidence=(await work.History(user,book)).Single(x=>x.SessionID==reviewEdits);
Check(evidence.ChangesDuringSession==1&&evidence.AdditionsDuringSession==1&&evidence.RemovalsDuringSession==1&&evidence.ChangedParagraphs==1&&evidence.PlaybackSeconds>9,"audio review links actual zero-net accepted revision and paragraph changes without duplicate word counting");
await new WritingActivityRepository(factory).Configure(user,book,false,365);
refused=false;try{await work.Execute(new{Action="start",UserID=user,BookID=book,SessionID=Guid.NewGuid(),Kind="Planning"});}catch(SqlException e)when(e.Number==51000){refused=true;}Check(refused,"existing recording pause also prevents new work sessions");
await work.Execute(new{Action="erase",UserID=user,BookID=book});Check((await work.Read(user,book)).Count==0,"erasure removes work, notes and cascaded daily measurements");
}
}