PlotDirector/PlotLine.Tests/NativeImportCorrectionTests.cs

84 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
using PlotDirector.Companion.Protocol;
internal static class NativeImportCorrectionTests
{
private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
private static string Response(int count,bool malformedConfidence=true)=>JsonSerializer.Serialize(new{
schemaVersion="1.0",chapterSummary="Synthetic structural regression, not a proposed author scene plan.",
sceneBoundaries=Enumerable.Range(1,count).Select(i=>new{sceneNumber=i,startParagraph=i,endParagraph=i,suggestedTitle="Test scene",structuralSummary="A synthetic narrative event for paragraph mapping verification.",confidence=i==count?0.9m:0.8m,reason="Synthetic boundary fixture."})
}).Replace("\"confidence\":0.9",malformedConfidence?"\"confidence\":0. Nine":"\"confidence\":0.9");
private static (ManuscriptStructureAnalysisService Service,FakeStoryIntelligenceClient Client) Analysis(string json){var client=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}}));return(new(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),client,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance),client);}
public static async Task Run()
{
await CheckpointRetry();
var options=new JsonSerializerOptions(JsonSerializerDefaults.Web);
var parsed=StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(Response(4),options);
Check(parsed.Success&&parsed.Parsed!.SceneBoundaries![3].Confidence==0.9m&&parsed.Warnings.Count>0,"Observed Counting the Days confidence token 0. Nine is repaired transparently without changing paragraph coordinates");
Check(parsed.Parsed!.SceneBoundaries!.Select(s=>s.StartParagraph).SequenceEqual(new int?[]{1,2,3,4}),"Confidence repair does not invent or move any scene boundary");
var bad=Response(4,false).Replace("\"endParagraph\":4","\"endParagraph\":0. Nine");
Check(!StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(bad,options).Success,"Malformed paragraph coordinates remain an error, never inferred");
var quoted=Response(4).Replace("Synthetic boundary fixture.","The string 0. nine remains literal.");
Check(StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(quoted,options).Parsed!.SceneBoundaries![0].Reason=="The string 0. nine remains literal.","Confidence repair leaves quoted narrative strings unchanged");
var fragments=new List<ParagraphFragment>();var position=0;int ordinal=0;
foreach(var row in new[]{(1,"Title page\r"),(10,"Copyright prose.\r"),(1,"– Counting the Days\r"),(10,"Repeated paragraph.\r"),(10,"\r"),(10,"Repeated paragraph.\r"),(10,"Manual\vline break.\r"),(10,"\f\r"),(10,"Final paragraph.\r")}){
fragments.Add(new(){Start=position,End=position+row.Item2.Length,ParagraphIndex=++ordinal,OutlineLevel=row.Item1,Text=row.Item2,CompletesParagraph=true});position+=row.Item2.Length;
}
var preview=NativeManuscriptCapture.Build(new(){End=position,Paragraphs=fragments.ToArray()},7,1,2,3,"Synthetic manuscript");
Check(preview.Chapters[0].IsFrontMatter&&preview.Chapters[0].ChapterNumber==0&&preview.Chapters[1].ChapterNumber==1,"Leading title/copyright material is retained separately without shifting story chapter numbering");
using(var provider=new ServiceCollection().BuildServiceProvider()){
var scans=new ManuscriptScanPreviewStore(provider.GetRequiredService<IServiceScopeFactory>(),NullLogger<ManuscriptScanPreviewStore>.Instance);var reviewSource=new ManuscriptScanPreview{UserID=7,Chapters=preview.Chapters};
await scans.CompleteAsync(7,reviewSource);var defaults=await scans.GetReviewAsync(7,reviewSource.PreviewID);
Check(preview.ChapterCount==1&&defaults!.Chapters[0].Include==false&&defaults.Chapters[1].Include,"Canonical chapter review excludes front matter by default while preserving it for explicit author review");
}
var chapter=preview.Chapters[1];Check(chapter.ParagraphMap.Select(p=>p.WordParagraphIndex).SequenceEqual(new[]{4,6,7,9}),"Blank paragraphs and page breaks do not consume structural ordinals; repeated text keeps distinct source indices");
var (service,client)=Analysis(Response(4));var result=await service.AnalyseChapterAsync(new(){TemporaryChapterKey=chapter.TemporaryChapterKey,SourceLabel="Synthetic: – Counting the Days",ChapterText=chapter.ChapterText!,ParagraphMap=chapter.ParagraphMap,SourceParagraphs=chapter.SourceParagraphs});
Check(result.Success&&client.Prompts.Count==1&&result.Scenes.Count==4,"Native canonical paragraph map passes the established analysis service with the observed malformed confidence response");
Check(result.Scenes.Select(s=>s.WordStartPosition).SequenceEqual(new int[]{4,6,7,9})&&result.Scenes[0].SourceText==result.Scenes[1].SourceText,"Scene boundaries map by original paragraph identity, never by repeated text matching");
var (invalid,invalidClient)=Analysis(bad);var failure=await invalid.AnalyseChapterAsync(new(){TemporaryChapterKey=chapter.TemporaryChapterKey,ChapterText=chapter.ChapterText!,ParagraphMap=chapter.ParagraphMap,SourceParagraphs=chapter.SourceParagraphs});
Check(!failure.Success&&failure.Scenes.Count==0&&invalidClient.Prompts.Count==2,"Unrepairable analysis uses bounded retry then reports failure without fabricated scenes");
}
private static async Task CheckpointRetry()
{
var values=new Dictionary<(int,Guid,string),string>();var calls=new Dictionary<string,int>();var previewId=Guid.NewGuid();
var repo=NativeWorkflowTests.Proxy<PlotLine.Data.IManuscriptCaptureRepository>((name,args)=>name switch{
"GetAnalysis"=>Task.FromResult(values.GetValueOrDefault(((int)args![0]!, (Guid)args[1]!, (string)args[2]!))),
"SaveAnalysis"=>Save((int)args![0]!, (Guid)args[1]!, (string)args[2]!, (string)args[3]!),
_=>throw new Exception("Unexpected source mutation during retry: "+name)});
Task Save(int user,Guid preview,string hash,string result){values[(user,preview,hash)]=result;return Task.CompletedTask;}
var ai=NativeWorkflowTests.Proxy<IManuscriptStructureAnalysisService>((_,args)=>{
var request=(ManuscriptStructureAnalysisRequest)args![0]!;calls[request.TemporaryChapterKey]=calls.GetValueOrDefault(request.TemporaryChapterKey)+1;
return Task.FromResult(request.TemporaryChapterKey=="second"&&calls["second"]==1?ManuscriptStructureAnalysisResult.Failed("second","Synthetic provider failure"):
ManuscriptStructureAnalysisResult.Succeeded(request.TemporaryChapterKey,[new(){TemporaryChapterKey=request.TemporaryChapterKey,SceneNumberWithinChapter=1,SourceText=request.ChapterText,StartParagraph=1,EndParagraph=1,WordStartPosition=1,WordEndPosition=1}],"{}"));
});
var people=NativeWorkflowTests.Proxy<PlotLine.Data.ICharacterRepository>((_,_)=>Task.FromResult<IReadOnlyList<Character>>([]));
var scans=NativeWorkflowTests.Proxy<IManuscriptScanPreviewStore>((_,_)=>Task.FromResult(new OnboardingBuildProgress()));
OnboardingService NewService(){var constructor=typeof(OnboardingService).GetConstructors().Single();return (OnboardingService)constructor.Invoke(constructor.GetParameters().Select(p=>p.ParameterType==typeof(PlotLine.Data.IManuscriptCaptureRepository)?(object)repo:p.ParameterType==typeof(IManuscriptStructureAnalysisService)?ai:p.ParameterType==typeof(PlotLine.Data.ICharacterRepository)?people:p.ParameterType==typeof(IManuscriptScanPreviewStore)?scans:null).ToArray());}
var source=new ManuscriptScanPreview{PreviewID=previewId,UserID=7,ProjectID=1,BookID=3,Source="NativeWordCompanion",Chapters=new[]{"first","second"}.Select((key,i)=>new ManuscriptScanChapterPreview{TemporaryChapterKey=key,ChapterNumber=i+1,ChapterText="Exact source "+key,ParagraphMap=[new(){StructuralParagraphOrdinal=1,WordParagraphIndex=1,Text="Exact source "+key}]}).ToArray()};
ManuscriptScanReviewDecision Review(string title)=>new(){PreviewID=previewId,Chapters=[new(){TemporaryChapterKey="first",ChapterNumber=1,Title=title,Include=true},new(){TemporaryChapterKey="second",ChapterNumber=2,Title="Second",Include=true}]};
var method=typeof(OnboardingService).GetMethod("AnalyseApprovedChaptersAsync",System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic)!;
async Task Analyse(OnboardingService service,ManuscriptScanReviewDecision review)=>await (Task<IReadOnlyList<ManuscriptStructureSceneBoundary>>)method.Invoke(service,[7,source,review,new Book{BookID=3},null])!;
var failed=false;try{await Analyse(NewService(),Review("First"));}catch(InvalidOperationException){failed=true;}
Check(failed&&calls["first"]==1&&calls["second"]==1&&values.Count==2,"Failed second chapter retains first success and diagnostic result without mutating captured source");
await Analyse(NewService(),Review("First"));Check(calls["first"]==1&&calls["second"]==2,"New service resumes from persisted success and retries only the failed chapter without Word capture");
await Analyse(NewService(),Review("Edited intention"));Check(calls["first"]==2&&calls["second"]==2,"Changed reviewed chapter context invalidates only its analysis checkpoint");
}
// Private, non-network evidence probe. Reads an explicitly supplied protected local capture; prints no prose.
public static async Task CapturedEvidence(string file,string key)
{
var preview=JsonSerializer.Deserialize<ManuscriptScanPreview>(await File.ReadAllTextAsync(file))!;
var chapter=preview.Chapters.Single(c=>c.TemporaryChapterKey==key);
var map=chapter.ParagraphMap;
Check(map.Count>0&&map.Select(p=>p.StructuralParagraphOrdinal).SequenceEqual(Enumerable.Range(1,map.Count))&&map.Zip(map.Skip(1)).All(p=>p.First.WordParagraphIndex<p.Second.WordParagraphIndex),"Privately inspected failing chapter has contiguous structural ordinals and monotonic original paragraph identities");
// One fixture boundary only, never persisted or represented as real AI output.
var json=JsonSerializer.Serialize(new{schemaVersion="1.0",chapterSummary="Synthetic mapping probe only.",sceneBoundaries=new[]{new{sceneNumber=1,startParagraph=1,endParagraph=map.Count,suggestedTitle="Mapping probe",structuralSummary="Synthetic mapping validation only, not an analysis of the author manuscript.",confidence=0.9m,reason="Private non-network mapping regression."}}}).Replace("\"confidence\":0.9","\"confidence\":0. Nine");
var (service,_)=Analysis(json);var result=await service.AnalyseChapterAsync(new(){PrivateAnalysis=true,TemporaryChapterKey=key,ChapterText=chapter.ChapterText!,ParagraphMap=map,SourceParagraphs=chapter.SourceParagraphs});
Check(result.Success&&result.Scenes.Single().WordStartPosition==map.First().WordParagraphIndex&&result.Scenes.Single().WordEndPosition==map.Last().WordParagraphIndex,"Actual privately read captured chapter passes canonical source mapping with a synthetic response containing the observed malformed token");
Console.WriteLine($"Evidence: structural paragraphs {map.Count}; source paragraphs {chapter.SourceParagraphs.Count}; no provider call, source write, import or story mutation.");
}
}