PlotDirector/PlotLine.Tests/NameVerificationTests.cs

55 lines
10 KiB
C#
Raw Permalink 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.AspNetCore.DataProtection;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Hubs;
using PlotLine.Models;
using PlotLine.Services;
internal static class NameVerificationTests
{
public static async Task Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Name verification: "+message);}
var scope=new NameManuscriptScope{Fingerprint=new string('A',64),BookCount=2,SnapshotBooks=1,LegacyBooks=1};
NameCandidateParagraph Paragraph(string text,int ordinal=0)=>new(){BookID=12,BookTitle="Synthetic book",ChapterID=10,SceneID=22,SceneTitle="Synthetic scene",ParagraphID=Guid.NewGuid(),ParagraphOrdinal=ordinal,SourceKind="Paragraph snapshot",Text=text,TotalCandidateParagraphs=1};
foreach(var pair in new[]{("Rose","Rose placed a rose on the table. Rosemary watched.",2),("May","May arrived. May I come? Maybe later.",2),("Will","Will you come? I spoke to Will yesterday. William left.",2),("Mark","Mark made a mark. A marker remained.",2),("Hope","Hope smiled. I hope she returns. Hopeful thoughts.",2)})Check(NameTextMatcher.Match(pair.Item1,scope,[Paragraph(pair.Item2)]).TextualMatches==pair.Item3,"whole-word matching preserves ambiguity for "+pair.Item1+" without substring matches");
Check(NameTextMatcher.Match("Mary Jane",scope,[Paragraph("I spoke to Mary Jane; not Mary Janette.")]).TextualMatches==1,"phrase matching accepts normal whitespace and punctuation boundaries");
Check(NameTextMatcher.Match("O’Neil",scope,[Paragraph("O'Neil's dog arrived.")]).TextualMatches==1,"normal apostrophe variants and possessive punctuation are handled");
var a=Paragraph("Rose walked to the door.");a.TotalCandidateParagraphs=2;var b=Paragraph(a.Text,1);b.TotalCandidateParagraphs=2;
var deduplicated=NameTextMatcher.Match("Rose",scope,[a,b]);Check(deduplicated.Contexts.Count==1&&deduplicated.Contexts[0].References.Count==2,"identical focused contexts deduplicate without losing manuscript references");
var incomplete=NameTextMatcher.Match("Rose",scope,[new(){BookID=12,Text="Rose.",TotalCandidateParagraphs=2001,Truncated=true}]);Check(!incomplete.Complete&&!incomplete.MatchesExact&&incomplete.Limitations.Count>=2,"bounded local searches never claim a complete manuscript search");
var policy=new AiOperationPolicy{OperationID=AiOperations.NameVerification,Enabled=true,CreditCost=1,MaxScope=100,MaxRequests=3,MaxTokens=100000,MaxOutputTokens=512,MaxDurationSeconds=60};
var many=NameTextMatcher.Match("Rose",scope,Enumerable.Range(0,100).Select(i=>new NameCandidateParagraph{BookID=12,Text=$"Scene {i}: Rose walked home.",TotalCandidateParagraphs=100,ParagraphOrdinal=i}).ToList());var limited=NameVerificationPlanner.Build("Rose",many,policy,"synthetic");Check(limited.Contexts<=20&&!limited.Complete&&limited.Limitation is not null,"planning reserves worst-case retries and reports scope truncation before execution");
var batch=deduplicated.Contexts;var parsed=NameVerificationPlanner.Parse("{\"items\":[{\"id\":0,\"classification\":\"likely-name\",\"reason\":\"Synthetic qualified assessment\"}]}",batch);Check(parsed.Single().Context.References.Count==2,"AI assessments retain every deduplicated source reference");
foreach(var json in new[]{"{\"items\":[]}","{\"items\":[{\"id\":7,\"classification\":\"likely-name\",\"reason\":\"x\"}]}","{\"items\":[{\"id\":0,\"classification\":\"confirmed-character\",\"reason\":\"x\"}]}"}){try{NameVerificationPlanner.Parse(json,batch);throw new Exception("Invalid provider scope accepted");}catch(JsonException){}}
Check(true,"missing, foreign and invented AI classifications are rejected");
var entitled=true;var providerFailure=false;var providerCalls=0;var reservations=0;var refunds=0;var searchCalls=0;var notices=new List<string>();var rows=new List<NameVerificationJob>();var search=NameTextMatcher.Match("NoMatch",scope,[]);var next=0;var currentCredits=10;
var projects=NativeWorkflowTests.Proxy<IProjectRepository>((_,args)=>Task.FromResult<Project?>((int)args![0]! ==7?new(){ProjectID=7,AccessRole="Owner"}:null));
var manuscripts=NativeWorkflowTests.Proxy<INameManuscriptRepository>((method,_)=>method switch{"Scope"=>Task.FromResult(scope),"Search"=>Search(),_=>throw new Exception(method)});
Task<NameTextSearch> Search(){searchCalls++;return Task.FromResult(search);}
var repository=NativeWorkflowTests.Proxy<INameVerificationRepository>((method,args)=>method switch{
"Read"=>Task.FromResult(rows.LastOrDefault(r=>r.Status=="Completed"&&r.ResultJson is not null&&JsonSerializer.Deserialize<NameVerificationResult>(r.ResultJson,new JsonSerializerOptions(JsonSerializerDefaults.Web))!.NormalisedName==(string)args![2]!)),
"Prepare"=>Prepare(args!),"Bind"=>Task.CompletedTask,"Save"=>Save(args!),"Fail"=>Task.CompletedTask,_=>throw new Exception(method)});
Task<NameVerificationJob> Prepare(object?[] args){var row=new NameVerificationJob{NameVerificationID=++next,Fingerprint=(string)args[3]!,AlgorithmVersion=(string)args[4]!,ScopeKey=(string)args[5]!,Status="Pending",IsNew=true};rows.Add(row);return Task.FromResult(row);}
Task Save(object?[] args){var row=rows.Single(x=>x.NameVerificationID==(int)args[1]!);row.ResultJson=(string)args[3]!;row.Status="Completed";return Task.CompletedTask;}
var allowance=NativeWorkflowTests.Proxy<IDiscretionaryAi>((method,args)=>method switch{
"Quote"=>Task.FromResult(new AiOperationQuote(policy,new(){Enabled=entitled,MonthlyCredits=currentCredits,PeriodEndUtc=DateTime.UtcNow.AddMonths(1)},entitled,entitled?"Insufficient credits.":"AI-enabled subscription required.")),
"Reserve"=>Reserve(),"Claim"=>Task.FromResult(new AiUsageReservation{ReservationID=Guid.NewGuid(),LeaseToken=Guid.NewGuid(),MaxDurationSeconds=60,MaxOutputTokens=512}),"Release"=>Refund(),_=>throw new Exception(method)});
Task<AiUsageReservation> Reserve(){reservations++;return Task.FromResult(new AiUsageReservation{ReservationID=Guid.NewGuid(),IsNew=true});}Task Refund(){refunds++;return Task.CompletedTask;}
var client=NativeWorkflowTests.Proxy<IStoryIntelligenceClient>((method,args)=>{if(method=="GetConfigurationStatus")return new StoryIntelligenceClientConfigurationStatus{Model="synthetic",SceneIntelligenceModel="synthetic"};providerCalls++;if(providerFailure)throw new HttpRequestException("Synthetic provider failure");using var prompt=JsonDocument.Parse(((string)args![0]!)[(((string)args[0]!).LastIndexOf('\n')+1)..]);return Task.FromResult(new StoryIntelligenceClientResult{Model="synthetic",RawResponseText=JsonSerializer.Serialize(new{items=prompt.RootElement.GetProperty("occurrences").EnumerateArray().Select(x=>new{id=x.GetProperty("id").GetInt32(),classification=char.IsUpper(x.GetProperty("match").GetString()![0])?"likely-name":"ordinary-language",reason="Synthetic assessment for regression only"})})});});
var proxy=NativeWorkflowTests.Proxy<IClientProxy>((method,args)=>{notices.Add((string)args![0]!);return Task.CompletedTask;});var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>NativeWorkflowTests.Proxy<IHubClients>((_,_)=>proxy));
var service=new NameVerification(projects,manuscripts,repository,allowance,NativeWorkflowTests.Proxy<IDiscretionaryAiRepository>((_,_)=>throw new Exception("The mocked provider cannot spend external budget")),client,new EphemeralDataProtectionProvider(),new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance),NullLogger<NameVerification>.Instance);
currentCredits=0;var estimate=await service.Estimate(4,7,"NoMatch");Check(!estimate.RequiresAi&&estimate.PlanToken is not null,"no textual matches produce a zero-credit preview despite exhausted allowance");await service.Execute(4,new(estimate.PlanToken!,Guid.NewGuid(),0),default);Check(providerCalls==0&&reservations==0,"zero matches persist accurate results without provider calls or reservations");
entitled=false;var beforeSearch=searchCalls;var denied=await service.Estimate(4,7,"AnotherNoMatch");Check(denied.PlanToken is null&&searchCalls==beforeSearch,"lowest-tier denial is enforced even when a prospective name could have no matches");Check((await service.Read(4,7,"NoMatch")) is not null,"saved verification remains readable after downgrade");
entitled=true;currentCredits=10;search=NameTextMatcher.Match("Rose",scope,[Paragraph("Rose placed a rose on the table.")]);estimate=await service.Estimate(4,7,"Rose");
try{await service.Execute(4,new(estimate.PlanToken!,Guid.NewGuid(),0),default);throw new Exception("Cost tampering accepted");}catch(ArgumentException){}Check(reservations==0,"direct invocation cannot bypass confirmed credit cost");
await service.Execute(4,new(estimate.PlanToken!,Guid.NewGuid(),1),default);var saved=await service.Read(4,7,"Rose");Check(providerCalls==1&&reservations==1&&saved!.Result.Likely==1&&saved.Result.Ordinary==1&&saved.Result.Complete,"one bounded batch persists distinct name and ordinary-language assessments");
var reused=await service.Estimate(4,7,"Rose");Check(reused.Cached&&providerCalls==1&&reservations==1,"valid result reuse makes no provider request or duplicate reservation");
scope.Fingerprint=new string('B',64);Check((await service.Read(4,7,"Rose"))!.Outdated,"manuscript revision changes mark results outdated without automatic AI");search=NameTextMatcher.Match("Rose",scope,[Paragraph("Rose returned.")]);providerFailure=true;estimate=await service.Estimate(4,7,"Rose");try{await service.Execute(4,new(estimate.PlanToken!,Guid.NewGuid(),1),default);throw new Exception("Provider failure ignored");}catch(HttpRequestException){}Check(refunds==1&&(await service.Read(4,7,"Rose"))!.Outdated,"failed processing releases reservation and preserves previous saved findings");
providerFailure=false;estimate=await service.Estimate(4,7,"Rose");scope.Fingerprint=new string('C',64);search=NameTextMatcher.Match("Rose",scope,[Paragraph("Rose returned.")]);var beforeReservations=reservations;try{await service.Execute(4,new(estimate.PlanToken!,Guid.NewGuid(),1),default);throw new Exception("Stale preview accepted");}catch(InvalidOperationException){}Check(reservations==beforeReservations,"content changes invalidate confirmation before credit reservation");
try{await service.Estimate(4,8,"Rose");throw new Exception("Foreign project accepted");}catch(UnauthorizedAccessException){}Check(notices.All(x=>x=="ContextInvalidated"),"verification uses existing data hints and sends no manuscript-focus changes");
Check(NameOccurrenceNavigation.Url(deduplicated.Contexts[0].References[0]).Contains("paragraphId="),"snapshot navigation preserves the actual paragraph identity");
}
}