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.Instance),client);} public static async Task Run() { await CheckpointRetry(); await Boundary97Versus99(); var integer=Response(1,false).Replace("\"schemaVersion\":\"1.0\"","\"schemaVersion\":\"2.0\"").Replace("\"confidence\":0.9","\"confidence\":90"); var (integerService,_)=Analysis(integer);var integerResult=await integerService.AnalyseChapterAsync(new(){ConfidenceContractVersion=2,ChapterText="Original narrative.\r",ParagraphMap=[new(){StructuralParagraphOrdinal=1,WordParagraphIndex=1,Text="Original narrative.\r"}],SourceParagraphs=[new(){WordParagraphIndex=1,Text="Original narrative.\r",IncludeInSourceText=true}]}); Check(integerResult.Success&&integerResult.Scenes.Single().Confidence==.9m&&integerResult.ParsedJson!.Contains("\"confidence\":90"),"Integer provider confidence is persisted as schema 2.0 and normalized once for legacy domain consumers"); var options=new JsonSerializerOptions(JsonSerializerDefaults.Web); var parsed=StoryIntelligenceAiJsonParser.Parse(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(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(quoted,options).Parsed!.SceneBoundaries![0].Reason=="The string 0. nine remains literal.","Confidence repair leaves quoted narrative strings unchanged"); var fragments=new List();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(),NullLogger.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();var previewId=Guid.NewGuid(); var repo=NativeWorkflowTests.Proxy((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((_,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((_,_)=>Task.FromResult>([])); var scans=NativeWorkflowTests.Proxy((_,_)=>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}],SourceParagraphs=[new(){WordParagraphIndex=1,Text="Exact source "+key,IncludeInSourceText=true}]}).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>)method.Invoke(service,[7,source,review,new Book{BookID=3},null])!; var retained=await Analyse(NewService(),Review("First")); Check(calls["first"]==1&&calls["second"]==1&&values.Count==2&&retained[1].RequiresRefinement,"Failed chapter becomes an explicitly unrefined scene while successful chapter checkpoint is preserved"); await Analyse(NewService(),Review("First"));Check(calls["first"]==1&&calls["second"]==1,"New service resumes cached valid groupings without Word capture or repeated successful AI calls"); await Analyse(NewService(),Review("Edited intention"));Check(calls["first"]==2&&calls["second"]==1,"Changed reviewed chapter context invalidates only its analysis checkpoint"); } private static async Task Boundary97Versus99() { var map=new List();var rows=new List{new(){WordParagraphIndex=3453,Text="Synthetic heading",IsChapterHeading=true}}; for(int n=1;n<=97;n++){var word=3453+n+(n>=40?1:0);if(n==40)rows.Add(new(){WordParagraphIndex=3493,Text="",IsBlank=true,IncludeInSourceText=true});var text=$"Original occurrence {n}.";map.Add(new(){StructuralParagraphOrdinal=n,WordParagraphIndex=word,Text=text});rows.Add(new(){WordParagraphIndex=word,Text=text,IncludeInSourceText=true});} var invalid=Response(1,false).Replace("\"endParagraph\":1","\"endParagraph\":99");var (service,provider)=Analysis(invalid); var request=new ManuscriptStructureAnalysisRequest{TemporaryChapterKey="chapter-25",SourceLabel="Synthetic: Counting the Days",ChapterText=string.Join("\n\n",map.Select(p=>p.Text)),ParagraphMap=map,SourceParagraphs=rows}; var rejected=await service.AnalyseChapterAsync(request); Check(!rejected.Success&&rejected.ErrorMessage!.Contains("97")&&rejected.ErrorMessage.Contains("99"),"Exact 97-versus-99 proposal is rejected, not clamped into a supposedly valid AI result"); Check(System.Text.RegularExpressions.Regex.Matches(provider.Prompts.Single(),@"(?m)^\[\d+\]").Count==97&&provider.Prompts.Single().Contains("\"structuralParagraphCount\": 97"),"AI receives exactly 97 numbered structural paragraphs, not 99 raw source paragraphs or Word indices"); var retained=ManuscriptStructureAnalysisService.RetainChapter(request,rejected);var scene=retained.Scenes.Single(); Check(retained.RequiresRefinement&&scene.RequiresRefinement&&scene.StartParagraph==1&&scene.EndParagraph==97&&scene.WordStartPosition==3454&&scene.WordEndPosition==3551&&scene.Confidence==null,"Explicit fallback covers the actual chapter and retains no invented AI confidence"); Check(scene.SourceText==string.Join(Environment.NewLine+Environment.NewLine,rows.Skip(1).Select(p=>p.Text))&&retained.RejectedProposalJson!.Contains("99"),"Fallback preserves all original occurrences, blank paragraph and rejected proposal for later refinement"); var unsafeMap=new ManuscriptStructureAnalysisRequest{TemporaryChapterKey="bad-map",ChapterText="Body",ParagraphMap=[new(){StructuralParagraphOrdinal=2,WordParagraphIndex=1,Text="Body"}],SourceParagraphs=[new(){WordParagraphIndex=1,Text="Body",IncludeInSourceText=true}]}; var refused=false;try{ManuscriptStructureAnalysisService.RetainChapter(unsafeMap,rejected);}catch(InvalidOperationException){refused=true;}Check(refused,"Fallback refuses a corrupt source map instead of concealing manuscript integrity errors"); } // 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(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