158 lines
12 KiB
C#
158 lines
12 KiB
C#
using System.Reflection;
|
|
using System.Text.Json;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
using PlotLine.ViewModels;
|
|
|
|
internal static class ExceptionReviewTests
|
|
{
|
|
private static void Check(bool value, string message) { if (!value) throw new InvalidOperationException(message); }
|
|
private static StoryIntelligenceObservationEvidence Evidence(int scene = 1, decimal confidence = .95m, string signal = "Learns", string text = "The character reads the registration document.")
|
|
=> new() { SceneID = scene, ChapterNumber = 1, SceneNumber = scene, Confidence = confidence, Signal = signal, Evidence = text };
|
|
private static StoryIntelligenceKnowledgeReviewCandidateViewModel Knowledge(string key = "k", string statement = "The vehicle belongs to another character", string state = "Knows", decimal confidence = .95m, bool ambiguous = false, string signal = "Learns")
|
|
=> new() { Key = key, CharacterID = 1, CharacterName = "Iris", KnowledgeStateID = 1, KnowledgeStateName = state, KnowledgeStatement = statement, RawConfidence = confidence, AmbiguousIdentity = ambiguous, Evidence = "Scene-backed evidence", Observations = [Evidence(confidence: confidence, signal: signal)] };
|
|
private static StoryIntelligenceRelationshipReviewCandidateViewModel Relationship(string key = "r", int scene = 1, string state = "Friendly", int a = 1, int b = 2, bool mutual = false, decimal confidence = .95m, bool directionUnknown = false, string detail = "They share a meal")
|
|
=> new()
|
|
{
|
|
Key = key,
|
|
CharacterAID = a,
|
|
CharacterBID = b,
|
|
CharacterAName = a == 1 ? "Iris" : "Jon",
|
|
CharacterBName = b == 1 ? "Iris" : "Jon",
|
|
RelationshipTypeID = 1,
|
|
HasExplicitState = true,
|
|
HasExplicitType = true,
|
|
RelationshipType = "Other",
|
|
RelationshipStateID = 1,
|
|
RelationshipState = state,
|
|
FirstSceneID = scene,
|
|
FirstChapterNumber = 1,
|
|
FirstSceneNumber = scene,
|
|
IsReciprocal = mutual,
|
|
NeedsDirectionReview = directionUnknown,
|
|
Development = detail,
|
|
ExampleContext = detail,
|
|
RawConfidence = confidence,
|
|
Observations = [Evidence(scene, confidence, "Friendly", detail)]
|
|
};
|
|
|
|
public static void DomainPolicy()
|
|
{
|
|
var ordinary = Knowledge();
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(ordinary, [ordinary]).Priority == "Tracked", "Supported ordinary knowledge should be tracked without an author task.");
|
|
var invalid = Knowledge(confidence: 95m);
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(invalid, [invalid]).Priority == "Optional", "Out-of-range confidence must never autoaccept.");
|
|
var trivial = Knowledge(confidence: .2m);
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(trivial, [trivial]).Priority == "Optional", "Low confidence alone must not make an urgent task.");
|
|
var ambiguous = Knowledge(ambiguous: true);
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(ambiguous, [ambiguous]).Priority == "Attention", "Canonical identity ambiguity must block automatic acceptance.");
|
|
var major = Knowledge(statement: "The commander murdered the witness", state: "Suspects", signal: "Suspects");
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(major, [major]).Priority == "Attention", "A consequential suspicion must remain distinct from knowledge.");
|
|
var hearsay = Knowledge(signal: "IsTold");
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(hearsay, [hearsay]).Priority == "Optional", "Reported knowledge must not be promoted to certainty.");
|
|
var unaware = Knowledge("u", state: "Unaware");
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(ordinary, [ordinary, unaware]).Priority == "Attention", "Same-scene opposing awareness needs attention.");
|
|
var missing = new StoryIntelligenceKnowledgeReviewCandidateViewModel { Key = "old", Confidence = "High", KnowledgeStatement = "Old extracted fact" };
|
|
Check(StoryIntelligenceReviewPolicy.Knowledge(missing, [missing]).Priority == "Optional", "Legacy confidence label is insufficient for autoacceptance.");
|
|
var unknown = Relationship(state: "unknown");
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(unknown, [unknown]).Priority == "Optional", "Unknown states cannot become automatic just because casing differs.");
|
|
var unmapped = new StoryIntelligenceRelationshipReviewCandidateViewModel
|
|
{
|
|
Key="unmapped", CharacterAID=1, CharacterBID=2, RelationshipStateID=1, RelationshipTypeID=1,
|
|
RelationshipState="Unmapped feeling", FirstSceneID=1, Development="Explicit scene evidence", Observations=[Evidence()], HasExplicitType=true
|
|
};
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(unmapped, [unmapped]).Priority == "Optional", "A lookup fallback must never masquerade as an explicit canonical state.");
|
|
var forward = Relationship(state: "Romantic");
|
|
var reverse = Relationship("reverse", state: "Distrustful", a: 2, b: 1);
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(forward, [forward, reverse]).Priority == "Tracked", "Different directions are not contradictory.");
|
|
var opposite = Relationship("opposite", state: "Hostile");
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(forward, [forward, opposite]).Priority == "Attention", "Same-track opposing states require attention.");
|
|
var before = Relationship("before", 1, "Trusting");
|
|
var middle = Relationship("middle", 2, "Hostile", confidence: .4m, detail: "Their mood seems different");
|
|
var after = Relationship("after", 3, "Trusting");
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(middle, [before, middle, after]).Priority == "Attention", "Unsupported opposing transition should be reviewable.");
|
|
var supported = Relationship("supported", 2, "Hostile", detail: "She discovers his betrayal");
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(supported, [before, supported, after]).Priority == "Tracked", "Supported changes must not be rejected just for changing.");
|
|
Check(StoryIntelligenceReviewPolicy.Relationship(Relationship(directionUnknown: true), []).Priority == "Optional", "Missing direction must not be autoaccepted or automatically urgent.");
|
|
var asset = new StoryIntelligenceAssetReviewCandidateViewModel { AssetName = "Brass key", Confidence = "Low", ExampleContext = "A key lies on the shelf" };
|
|
Check(StoryIntelligenceReviewPolicy.Asset(asset).Priority == "Optional", "A trivial asset must not create an urgent task.");
|
|
}
|
|
|
|
public static void PreserveDecisionsAndObservations() => Run().GetAwaiter().GetResult();
|
|
private static async Task Run()
|
|
{
|
|
var rows = new List<StoryIntelligenceReviewCandidateRow>();
|
|
var assessed = new List<(int ID, string Payload, StoryIntelligenceReviewAssessment Assessment)>();
|
|
var options = StoryIntelligenceExceptionReviewService.JsonOptions;
|
|
StoryIntelligenceReviewCandidateRow Row(int id, object payload, string status = "Pending") => new()
|
|
{ ReviewCandidateID = id, ReviewCandidateGenerationID = 11, BookID = 22, Module = "Relationships", StableKey = "r" + id, DecisionStatus = status, CandidatePayloadJson = JsonSerializer.Serialize(payload, options) };
|
|
rows.Add(Row(1, Relationship("r1", 1)));
|
|
rows.Add(Row(2, Relationship("r2", 2, a: 2, b: 1)));
|
|
rows.Add(Row(3, Relationship("r3", 3), "Reviewed"));
|
|
rows.Add(Row(4, Relationship("r4", 4), "AutoAccepted"));
|
|
var repo = Stub<IStoryIntelligenceReviewCandidateRepository>((method, args) => method switch
|
|
{
|
|
"ListAllAsync" => Task.FromResult<IReadOnlyList<StoryIntelligenceReviewCandidateRow>>(rows),
|
|
"AssessAsync" => Save((int)args![0]!, (string)args[2]!, (string)args[3]!),
|
|
_ => throw new Exception("Unexpected repository call: " + method)
|
|
});
|
|
Task Save(int id, string payload, string assessment) { assessed.Add((id, payload, JsonSerializer.Deserialize<StoryIntelligenceReviewAssessment>(assessment, options)!)); return Task.CompletedTask; }
|
|
var service = new StoryIntelligenceExceptionReviewService(repo,
|
|
Stub<IStoryIntelligenceKnowledgeImportService>((m, a) => throw new Exception("No analysis/reconstruction during normal assessment")),
|
|
Stub<IStoryIntelligenceRelationshipImportService>((m, a) => throw new Exception("No analysis/reconstruction during normal assessment")),
|
|
Stub<IStoryIntelligenceAssetImportService>((m, a) => throw new Exception("No analysis/reconstruction during normal assessment")));
|
|
await service.AssessPreparedAsync(22, "Relationships");
|
|
Check(assessed.Count == 2 && assessed.All(x => x.ID < 3), "Existing reviewed and tracked decisions must remain untouched.");
|
|
var accepted = assessed.Select(x => JsonSerializer.Deserialize<StoryIntelligenceRelationshipReviewCandidateViewModel>(x.Payload, options)!).ToList();
|
|
Check(accepted[0].FirstSceneID == 1 && accepted[1].FirstSceneID == 2, "Every scene observation must survive classification.");
|
|
Check(accepted[0].CharacterAID == 1 && accepted[1].CharacterAID == 2, "Direction must survive classification.");
|
|
var entries = rows.Select(StoryIntelligenceReviewEntry.From).ToList();
|
|
Check(entries.GroupBy(x => x.PairKey).Count() == 1 && entries.Sum(x => x.Observations.Count) == 4, "Pair aggregation must retain both directions and all evidence.");
|
|
Check(entries[2].Status == "Reviewed by you", "Author decisions must not be presented as automatic.");
|
|
var otherPair = StoryIntelligenceReviewEntry.From(Row(9, new StoryIntelligenceRelationshipReviewCandidateViewModel
|
|
{ Key = "other", CharacterAID = 3, CharacterBID = 4, CharacterAName = "Iris", CharacterBName = "Jon" }));
|
|
Check(otherPair.PairKey != entries[0].PairKey, "Identically named but distinct canonical pairs must not be flattened.");
|
|
rows.Clear(); assessed.Clear();
|
|
var recovered = Knowledge();
|
|
rows.Add(new()
|
|
{
|
|
ReviewCandidateID = 7,
|
|
ReviewCandidateGenerationID = 11,
|
|
BookID = 22,
|
|
Module = "Knowledge",
|
|
StableKey = "k",
|
|
DecisionStatus = "Pending",
|
|
CandidatePayloadJson = JsonSerializer.Serialize(new StoryIntelligenceKnowledgeReviewCandidateViewModel { Key = "k", Confidence = "High" }, options)
|
|
});
|
|
rows.Add(new()
|
|
{
|
|
ReviewCandidateID = 8,
|
|
ReviewCandidateGenerationID = 11,
|
|
BookID = 22,
|
|
Module = "Knowledge",
|
|
StableKey = "unmatched",
|
|
DecisionStatus = "Pending",
|
|
CandidatePayloadJson = JsonSerializer.Serialize(new StoryIntelligenceKnowledgeReviewCandidateViewModel { Key = "unmatched", Confidence = "High" }, options)
|
|
});
|
|
var reconstructed = Stub<IStoryIntelligenceKnowledgeImportService>((m, a) => m == "BuildReviewAsync"
|
|
? Task.FromResult(new StoryIntelligenceKnowledgeReviewViewModel { Candidates = [recovered] }) : throw new Exception(m));
|
|
var reclassifier = new StoryIntelligenceExceptionReviewService(repo, reconstructed,
|
|
Stub<IStoryIntelligenceRelationshipImportService>((m, a) => throw new Exception("Wrong module")),
|
|
Stub<IStoryIntelligenceAssetImportService>((m, a) => throw new Exception("Wrong module")));
|
|
await reclassifier.ReassessAsync(new OnboardingStoryIntelligenceBatch { BookID = 22 }, "Knowledge");
|
|
Check(assessed.Single(x => x.ID == 7).Assessment.Priority == "Tracked", "An old stable key can recover reliable saved evidence without new AI analysis.");
|
|
Check(assessed.Single(x => x.ID == 8).Assessment.Priority == "Optional", "Unmatched legacy keys stay visible without invented certainty.");
|
|
var progress = new StoryIntelligenceProgressViewModel { PipelineDashboard = new() { CharacterStageComplete = true }, KnowledgeReview = new() { SummaryNeedsAttentionCount = 0, PendingCandidateCount = 100 } };
|
|
Check(progress.CharacterGateSatisfied && progress.KnowledgeNeedsAttentionCount == 0, "Optional decisions must not block project access or inflate attention counts.");
|
|
}
|
|
|
|
public static T Stub<T>(Func<string, object?[]?, object?> invoke) where T : class
|
|
{ var result = DispatchProxy.Create<T, Proxy>(); ((Proxy)(object)result).Call = invoke; return result; }
|
|
public class Proxy : DispatchProxy
|
|
{
|
|
public Func<string, object?[]?, object?> Call { get; set; } = null!;
|
|
protected override object? Invoke(MethodInfo? method, object?[]? args) => Call(method!.Name, args);
|
|
}
|
|
}
|