PlotDirector/PlotLine/Services/NameVerification.cs

104 lines
10 KiB
C#

using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services;
public interface INameVerification
{
Task<NameVerificationView?> Read(int user,int project,string name);
Task<NameVerificationEstimate> Estimate(int user,int project,string name,bool retryInterrupted=false);
Task<NameVerificationExecution> Execute(int user,NameVerificationRequest request,CancellationToken cancellationToken);
}
public sealed class NameVerification(IProjectRepository projects,INameManuscriptRepository manuscripts,INameVerificationRepository results,IDiscretionaryAi allowance,IDiscretionaryAiRepository usage,IStoryIntelligenceClient client,IDataProtectionProvider protection,ContextWorkspaceNotifications notifications,ILogger<NameVerification> logger):INameVerification
{
private static readonly JsonSerializerOptions JsonOptions=new(JsonSerializerDefaults.Web);
private readonly IDataProtector protector=protection.CreateProtector("PlotDirector.NameVerification.Plan.v1");
private sealed record Confirmation(int UserID,int ProjectID,string Name,string Fingerprint,string ScopeKey,string Hash,int Credits,DateTime ExpiresUtc,bool RetryInterrupted=false);
private async Task<Project> Authorise(int user,int project)=>await projects.GetForUserAsync(project,user)??throw new UnauthorizedAccessException("Series access is unavailable.");
private static string ValidateName(string name){var normalised=NameIntelligenceService.NormaliseName(name);if(normalised.Length is 0 or >120)throw new ArgumentException("Choose a name of at most 120 characters.");return normalised;}
private static void RequireEdit(Project project){if(project.IsArchived||project.AccessRole is not("Owner" or "Collaborator"))throw new UnauthorizedAccessException("Name verification requires project editing access.");}
private string Model(){var configuration=client.GetConfigurationStatus();return string.IsNullOrWhiteSpace(configuration.SceneIntelligenceModel)?configuration.Model:configuration.SceneIntelligenceModel;}
private async Task<NameVerificationView?> ReadScope(int user,int project,string normalised,NameManuscriptScope scope)
{
var row=await results.Read(user,project,normalised,scope.Fingerprint,NameVerificationPlanner.AlgorithmVersion);if(row?.ResultJson is null)return null;
var result=JsonSerializer.Deserialize<NameVerificationResult>(row.ResultJson,JsonOptions)??throw new InvalidOperationException("Saved name verification could not be read.");
return new(row.NameVerificationID,result,row.Fingerprint!=scope.Fingerprint||row.AlgorithmVersion!=NameVerificationPlanner.AlgorithmVersion);
}
public async Task<NameVerificationView?> Read(int user,int project,string name)
{
await Authorise(user,project);var normalised=ValidateName(name);var scope=await manuscripts.Scope(user,project);return await ReadScope(user,project,normalised,scope);
}
private static bool Reusable(NameVerificationView? cached,AiOperationQuote quote)
{
if(cached is null||cached.Outdated)return false;
if(cached.Result.Complete||!quote.Entitled||quote.Operation is null)return true;
var empty=new NameTextSearch(cached.Result.Scope,0,true,0,0,true,[],[]);
return cached.Result.ScopeKey==NameVerificationPlanner.Build(cached.Result.Name,empty,quote.Operation,"").ScopeKey;
}
public async Task<NameVerificationEstimate> Estimate(int user,int project,string name,bool retryInterrupted=false)
{
var authorisation=await Authorise(user,project);var normalised=ValidateName(name);var scope=await manuscripts.Scope(user,project);var cached=await ReadScope(user,project,normalised,scope);var quote=await allowance.Quote(user,AiOperations.NameVerification);
if(Reusable(cached,quote)&&!(retryInterrupted&&cached!.Result.Interrupted&&quote.Entitled))return new(quote,null,true,false,cached!.Result.TextualMatches,cached.Result.MatchesExact,0,0,cached.Result.Complete,"Saved verification matches this manuscript revision. Reuse costs no credits.");
RequireEdit(authorisation);
if(!quote.Entitled||quote.Operation is not {Enabled:true,RequiredEntitlement:"discretionary-ai"})return new(quote,null,false,false,0,false,0,0,false,quote.Message);
var search=await manuscripts.Search(user,project,name);var plan=NameVerificationPlanner.Build(name,search,quote.Operation,Model());var cost=plan.Contexts>0?quote.Operation.CreditCost:0;
var summary=$"{(search.MatchesExact?"":"At least ")}{search.TextualMatches:N0} textual matches in saved manuscript content across {search.Scope.BookCount} active book(s). {plan.Matches:N0} matches in {plan.Contexts:N0} distinct contexts can be examined. "+(plan.Complete?"The saved-source search is complete. ":"Verification will be incomplete. ")+(cost==0?"No AI request or credits are required.":$"This bounded operation costs {cost} AI {(cost==1?"credit":"credits")}, including any usable partial result.");
var token=protector.Protect(JsonSerializer.Serialize(new Confirmation(user,project,name.Trim(),search.Scope.Fingerprint,plan.ScopeKey,plan.Hash,cost,DateTime.UtcNow.AddMinutes(10),retryInterrupted&&cached?.Result.Interrupted==true),JsonOptions));
return new(quote,token,false,cost>0,search.TextualMatches,search.MatchesExact,plan.Contexts,plan.Matches,plan.Complete,summary);
}
public async Task<NameVerificationExecution> Execute(int user,NameVerificationRequest request,CancellationToken cancellationToken)
{
if(request.RequestID==Guid.Empty||string.IsNullOrEmpty(request.PlanToken)||request.PlanToken.Length>8192)throw new ArgumentException("Review the verification scope and cost first.");
Confirmation confirmation;
try{confirmation=JsonSerializer.Deserialize<Confirmation>(protector.Unprotect(request.PlanToken),JsonOptions)??throw new CryptographicException();}catch(Exception error)when(error is CryptographicException or JsonException){throw new ArgumentException("The verification preview is unavailable. Review the scope and cost again.");}
if(confirmation.UserID!=user||confirmation.ExpiresUtc<=DateTime.UtcNow||request.ExpectedCredits!=confirmation.Credits)throw new ArgumentException("The verification confirmation expired or changed. Review its scope and cost again.");
var authorisation=await Authorise(user,confirmation.ProjectID);var normalised=ValidateName(confirmation.Name);var scope=await manuscripts.Scope(user,confirmation.ProjectID);var cached=await ReadScope(user,confirmation.ProjectID,normalised,scope);var quote=await allowance.Quote(user,AiOperations.NameVerification);
if(Reusable(cached,quote)&&!(confirmation.RetryInterrupted&&cached!.Result.Interrupted&&quote.Entitled))return new(cached!.NameVerificationID,false,true,cached.Result.Complete);
RequireEdit(authorisation);
if(!quote.Entitled||quote.Operation is not {Enabled:true,RequiredEntitlement:"discretionary-ai"})throw new InvalidOperationException(quote.Message);
var search=await manuscripts.Search(user,confirmation.ProjectID,confirmation.Name);var model=Model();var plan=NameVerificationPlanner.Build(confirmation.Name,search,quote.Operation,model);
if(plan.Hash!=confirmation.Hash||plan.ScopeKey!=confirmation.ScopeKey||search.Scope.Fingerprint!=confirmation.Fingerprint||(plan.Contexts>0?quote.Operation.CreditCost:0)!=confirmation.Credits)throw new InvalidOperationException("The manuscript, AI model, processing policy or cost changed. Review the scope and cost again.");
if(plan.Contexts>0&&!quote.CanExecute)throw new InvalidOperationException(quote.Message);
var job=await results.Prepare(user,confirmation.ProjectID,normalised,search.Scope.Fingerprint,NameVerificationPlanner.AlgorithmVersion,plan.ScopeKey,request.RequestID,quote.Operation.MaxDurationSeconds,confirmation.RetryInterrupted);
if(!job.IsNew)return new(job.NameVerificationID,job.Status!="Completed",job.Status=="Completed",job.ResultJson is not null&&JsonSerializer.Deserialize<NameVerificationResult>(job.ResultJson,JsonOptions)?.Complete==true);
AiUsageReservation? reservation=null;
var result=new NameVerificationResult{Name=confirmation.Name,NormalisedName=normalised,Fingerprint=search.Scope.Fingerprint,AlgorithmVersion=NameVerificationPlanner.AlgorithmVersion,ScopeKey=plan.ScopeKey,CreatedUtc=DateTime.UtcNow,Scope=search.Scope,TextualMatches=search.TextualMatches,MatchesExact=search.MatchesExact,ScannedParagraphs=search.ScannedParagraphs,CandidateParagraphs=search.CandidateParagraphs,Complete=plan.Complete,Limitations=search.Limitations.ToList()};
if(plan.Limitation is not null)result.Limitations.Add(plan.Limitation);
try
{
if(plan.Contexts>0)
{
reservation=await allowance.Reserve(user,AiOperations.NameVerification,request.RequestID,plan.Contexts,request.ExpectedCredits);
if(!reservation.IsNew)throw new InvalidOperationException("This AI request identifier has already been used. Confirm a new request.");
await results.Bind(user,job.NameVerificationID,request.RequestID,reservation.ReservationID);
reservation=await allowance.Claim(reservation.ReservationID);
using var execution=AiExecutionScope.Enter(reservation,usage,cancellationToken);
try
{
foreach(var batch in plan.Batches)
{
execution.Timeout.Token.ThrowIfCancellationRequested();
var response=await client.ExecutePromptAsync(NameVerificationPlanner.Prompt(confirmation.Name,batch),NameVerificationPlanner.AlgorithmVersion,execution.Timeout.Token,model,quote.Operation.MaxOutputTokens,NameVerificationPlanner.Contract);
result.Findings.AddRange(NameVerificationPlanner.Parse(response.RawResponseText,batch));
}
}
catch(Exception error)when(error is not OutOfMemoryException && result.Findings.Count>0)
{
logger.LogWarning(error,"Name verification {VerificationID} retained a bounded partial result.",job.NameVerificationID);
result.Complete=false;result.Interrupted=true;result.Limitations.Add("Processing stopped before every planned context was examined. Saved assessments are incomplete.");
}
}
await results.Save(user,job.NameVerificationID,request.RequestID,JsonSerializer.Serialize(result,JsonOptions),reservation?.ReservationID,reservation?.LeaseToken);
}
catch
{
if(reservation is not null)await allowance.Release(reservation.ReservationID,reservation.LeaseToken);
await results.Fail(user,job.NameVerificationID,request.RequestID);throw;
}
// This is reference data only: no character/alias writes and no manuscript-focus commands.
await notifications.Invalidate(user,projectId:confirmation.ProjectID,kind:"names");
return new(job.NameVerificationID,false,false,result.Complete);
}
}