diff --git a/PlotLine.Tests/NativeImportCorrectionTests.cs b/PlotLine.Tests/NativeImportCorrectionTests.cs index 11aee33f..0bb68d13 100644 --- a/PlotLine.Tests/NativeImportCorrectionTests.cs +++ b/PlotLine.Tests/NativeImportCorrectionTests.cs @@ -16,6 +16,7 @@ internal static class NativeImportCorrectionTests public static async Task Run() { await CheckpointRetry(); + await Boundary97Versus99(); 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"); @@ -58,14 +59,29 @@ internal static class NativeImportCorrectionTests 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}]}).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 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"); + 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) diff --git a/PlotLine/Models/ManuscriptScanModels.cs b/PlotLine/Models/ManuscriptScanModels.cs index 219a37e9..6a90d0d9 100644 --- a/PlotLine/Models/ManuscriptScanModels.cs +++ b/PlotLine/Models/ManuscriptScanModels.cs @@ -334,6 +334,8 @@ public sealed class OnboardingSceneStructureSummary public sealed class OnboardingSceneStructureDetail { + public bool RequiresRefinement {get;init;} + public string? BoundaryWarning {get;init;} public int SceneNumberWithinChapter { get; init; } public string Title { get; init; } = string.Empty; public string DisplayTitle => SceneTitleDisplay.Format(SceneNumberWithinChapter, Title); diff --git a/PlotLine/Services/ManuscriptStructureAnalysisService.cs b/PlotLine/Services/ManuscriptStructureAnalysisService.cs index 8e8c768d..6b116e18 100644 --- a/PlotLine/Services/ManuscriptStructureAnalysisService.cs +++ b/PlotLine/Services/ManuscriptStructureAnalysisService.cs @@ -49,7 +49,7 @@ public sealed partial class ManuscriptStructureAnalysisService( var promptVersion = versions.GetPromptVersion(ChapterPromptFile); var clientStatus = client.GetConfigurationStatus(); var template = await prompts.LoadPromptAsync(ChapterPromptFile, cancellationToken); - var prompt = BuildChapterPrompt(template, BuildChapterContextJson(request), StoryIntelligenceParagraphs.Number(paragraphs)); + var prompt = BuildChapterPrompt(template, BuildChapterContextJson(request,paragraphs.Count), StoryIntelligenceParagraphs.Number(paragraphs)); var result = await client.ExecutePromptAsync(prompt, promptVersion, cancellationToken, clientStatus.ChapterStructureModel); var chapterJson = ExtractOutputText(result.RawResponseText); var parseResult = StoryIntelligenceAiJsonParser.Parse(chapterJson, JsonOptions); @@ -252,12 +252,15 @@ public sealed partial class ManuscriptStructureAnalysisService( retryAttempted); } - private static string BuildChapterContextJson(ManuscriptStructureAnalysisRequest request) + private static string BuildChapterContextJson(ManuscriptStructureAnalysisRequest request,int paragraphCount) => JsonSerializer.Serialize(new { projectId = request.ProjectID, bookId = request.BookID, chapterId = (int?)null, + structuralParagraphCount=paragraphCount, + firstParagraph=1,lastParagraph=paragraphCount, + numbering="Use only the explicit [n] labels in CHAPTER_TEXT, not blank lines or Word document paragraph numbers.", chapterNumber = request.ChapterNumber, sourceLabel = request.SourceLabel, storyEra = request.StoryEra, @@ -407,6 +410,23 @@ public sealed partial class ManuscriptStructureAnalysisService( return first; } + // Import policy, not an AI repair: preserve a readable chapter as an explicitly unrefined grouping. + public static ManuscriptStructureAnalysisResult RetainChapter(ManuscriptStructureAnalysisRequest request,ManuscriptStructureAnalysisResult rejected) + { + var built=BuildStructuralParagraphs(request,request.ChapterText); + if(!built.Success||built.Paragraphs.Count==0||request.ParagraphMap.Count!=built.Paragraphs.Count||request.SourceParagraphs.Count==0) + throw new InvalidOperationException("The accepted chapter's source mapping is incomplete. Its capture is preserved; scene grouping cannot safely continue."); + var ordered=request.ParagraphMap.OrderBy(p=>p.StructuralParagraphOrdinal).ToArray(); + var text=BuildSourceText(request.SourceParagraphs,ordered[0].WordParagraphIndex,ordered[^1].WordParagraphIndex); + if(string.IsNullOrWhiteSpace(text))throw new InvalidOperationException("The accepted chapter has no mapped source prose. The capture is preserved."); + var warning="Scene boundaries need refinement. The chapter has been retained as one scene; the AI proposal was not accepted."; + var metadata=JsonSerializer.Serialize(new{analysisState="Fallback",requiresRefinement=true,diagnostic=rejected.ErrorMessage,invalidProposal=rejected.ParsedJson}); + return new(){TemporaryChapterKey=request.TemporaryChapterKey,Success=true,RequiresRefinement=true,BoundaryWarning=warning,RejectedProposalJson=rejected.ParsedJson,ErrorMessage=rejected.ErrorMessage, + ParsedJson=metadata,Scenes=[new(){TemporaryChapterKey=request.TemporaryChapterKey,TemporarySceneKey=request.TemporaryChapterKey+"-fallback-scene-1",SceneNumberWithinChapter=1, + Title="Unrefined scene",StartParagraph=1,EndParagraph=built.Paragraphs.Count,WordStartPosition=ordered[0].WordParagraphIndex,WordEndPosition=ordered[^1].WordParagraphIndex, + SourceText=text,WordCount=built.Paragraphs.Sum(CountWords),RequiresRefinement=true,BoundaryWarning=warning,ChapterParsedJson=metadata}]}; + } + private static string BuildUserJsonParseFailureMessage(ManuscriptStructureAnalysisRequest request) { var label = ExtractChapterLabel(request.SourceLabel); @@ -701,6 +721,9 @@ public sealed class ManuscriptStructureAnalysisRequest public sealed class ManuscriptStructureAnalysisResult { + public bool RequiresRefinement {get;init;} + public string? BoundaryWarning {get;init;} + public string? RejectedProposalJson {get;init;} public string TemporaryChapterKey { get; init; } = string.Empty; public bool Success { get; init; } public string? ErrorMessage { get; init; } @@ -750,6 +773,8 @@ internal sealed class StructuralParagraphBuildResult public sealed class ManuscriptStructureSceneBoundary { + public bool RequiresRefinement {get;init;} + public string? BoundaryWarning {get;init;} public string TemporarySceneKey { get; init; } = string.Empty; public string TemporaryChapterKey { get; init; } = string.Empty; public int SceneNumberWithinChapter { get; init; } diff --git a/PlotLine/Services/OnboardingService.cs b/PlotLine/Services/OnboardingService.cs index 0aeff253..85e03bc7 100644 --- a/PlotLine/Services/OnboardingService.cs +++ b/PlotLine/Services/OnboardingService.cs @@ -519,7 +519,9 @@ public sealed class OnboardingService( var checkpoint=preview.Source=="NativeWordCompanion"&&captureRepository!=null?await captureRepository.GetAnalysis(userId,preview.PreviewID,fingerprint):null; var analysis=checkpoint==null?null:JsonSerializer.Deserialize(checkpoint); if(analysis?.Success!=true){ - analysis=await structureAnalysis.AnalyseChapterAsync(request); + // A previously rejected proposal can be safely grouped without repeating successful chapters. + analysis=analysis??await structureAnalysis.AnalyseChapterAsync(request); + if(!analysis.Success)analysis=ManuscriptStructureAnalysisService.RetainChapter(request,analysis); if(preview.Source=="NativeWordCompanion"&&captureRepository!=null)await captureRepository.SaveAnalysis(userId,preview.PreviewID,fingerprint,JsonSerializer.Serialize(analysis)); } @@ -1234,6 +1236,7 @@ public sealed class OnboardingService( SceneNumberWithinChapter = scene.SceneNumberWithinChapter, Title = generateSceneTitles ? scene.SuggestedTitle ?? string.Empty : string.Empty, WordCount = scene.WordCount, + RequiresRefinement=scene.RequiresRefinement,BoundaryWarning=scene.BoundaryWarning, StructuralSummary = scene.StructuralSummary, StartParagraph = scene.StartParagraph, EndParagraph = scene.EndParagraph @@ -1271,6 +1274,7 @@ public sealed class OnboardingService( SceneNumberWithinChapter = sceneIndex + 1, Title = scene.SceneTitle ?? string.Empty, WordCount = scene.SourceWordCount, + RequiresRefinement=scene.SourceKind=="StructuralFallback",BoundaryWarning=scene.SourceKind=="StructuralFallback"?"Scene boundaries need refinement; the chapter was preserved as one scene.":null, StructuralSummary = scene.StructuralSummary, StartParagraph = scene.SourceStartParagraph ?? 0, EndParagraph = scene.SourceEndParagraph ?? 0 @@ -1340,6 +1344,7 @@ public sealed class OnboardingService( ProjectID = preview.ProjectID, BookID = preview.BookID, ChapterID = chapterId, + SourceKind=scene.RequiresRefinement?"StructuralFallback":"StructuralImport", SourceText = scene.SourceText, SourceWordCount = CountWords(scene.SourceText), SourceCharacterCount = scene.SourceText.Length, diff --git a/PlotLine/Views/Onboarding/BuildComplete.cshtml b/PlotLine/Views/Onboarding/BuildComplete.cshtml index acbb22f9..b1c6423b 100644 --- a/PlotLine/Views/Onboarding/BuildComplete.cshtml +++ b/PlotLine/Views/Onboarding/BuildComplete.cshtml @@ -56,13 +56,14 @@ @chapter.ChapterTitle @chapter.SceneCount.ToString("N0") scene@(chapter.SceneCount == 1 ? string.Empty : "s") / @chapter.WordCount.ToString("N0") words - @if (chapter.Scenes.Any(scene => !string.IsNullOrWhiteSpace(scene.StructuralSummary))) + @if (chapter.Scenes.Any(scene => scene.RequiresRefinement || !string.IsNullOrWhiteSpace(scene.StructuralSummary))) {
    @foreach (var scene in chapter.Scenes) {
  1. @scene.DisplayTitle + @if(scene.RequiresRefinement){

    @scene.BoundaryWarning

    } @scene.WordCount.ToString("N0") words @if (!string.IsNullOrWhiteSpace(scene.StructuralSummary)) {