diff --git a/Docs/StoryIntelligence_ExceptionReview.md b/Docs/StoryIntelligence_ExceptionReview.md new file mode 100644 index 00000000..530c556f --- /dev/null +++ b/Docs/StoryIntelligence_ExceptionReview.md @@ -0,0 +1,39 @@ +# Story Intelligence exception review + +## Investigation + +The reported 647 Knowledge and 526 Relationship items were pending candidate counts, not measured ambiguity or conflict counts. The extraction prompts already request broad, scene-backed intelligence. `SceneIntelligenceKnowledgeChange` and `SceneIntelligenceRelationship` retain confidence, evidence and domain-specific signals in saved scene JSON. The review builders group knowledge by character, statement and state, and relationships into scene proposals. Neither builder previously assessed whether author intervention was useful. + +Migration 177 persisted every candidate with `DecisionStatus=Pending`. Its page query and the Review Centre summary treated pending as attention. Candidate confidence was displayed as a band but the candidate table's numeric confidence was not populated. Knowledge acceptance writes `CharacterKnowledge`; relationship acceptance calls the source-key-idempotent procedure from migration 197 to create/reuse a directional relationship and insert a scene event. Consequently, relabelling pending rows alone would not make intelligence available to Story Point, relationship maps, scene histories or the Story Bible. These consumers read canonical records. Saved raw analysis remains available regardless of acceptance. + +Locations already separate significance, identity uncertainty and user decisions. Their contextual setting/consequence policy is domain-specific; it is retained rather than copied into knowledge or relationship scoring. Assets already resolve exact canonical matches automatically; remaining proposed identities previously all counted as attention. + +## Design + +`StoryIntelligenceReviewPolicy` is the common deterministic policy. It produces a persisted priority and readable reasons independently of `DecisionStatus`. States are Unassessed, Optional, Attention and Tracked. Tracked is assigned only together with a successful canonical write; decision status becomes AutoAccepted. Reviewed author decisions remain distinct. No AI interface is involved in the policy or browser. + +The existing High confidence band (0.75–1) is only one gate. Automatic acceptance also requires canonical identities, explicit state/direction, a valid scene, and supporting evidence for every retained appearance. Duplicate aliases block automatic identity resolution. Missing provenance remains optional rather than being guessed from an old High label. + +Knowledge retains the existing knowledge-state vocabulary. Ordinary explicitly learned/discovered/confirmed knowledge can be tracked. Beliefs, suspicion, misunderstanding, hearsay and inference stay available for optional interpretation; consequential uncertainty and same-scene awareness contradictions require attention. Original acquisition signals remain in the evidence. First-scene selection now orders by chapter, scene and scene sort order. Accepted knowledge IDs are recorded correctly (previously the candidate decision stored the state lookup ID). + +Relationships preserve the existing scene and source-review keys, factual versus changing tracks, reciprocity, emotional intensity and awareness of the other character. Conflict checks compare the same directed track. Reverse-direction disagreement is valid. Opposing states in one scene and weakly supported opposing states between surrounding observations can require attention. A supported change is allowed. Pair journeys are a display grouping, not a merge: all saved proposals and scene evidence remain available. + +Assets reuse the same priority model. Existing exact matching remains in place; uncertain consequential asset evidence can require attention, while ordinary proposed objects stay optional. Automatic creation of new asset identities/ownership is deliberately not added. + +The Review Centre uses persisted aggregate counts, not raw scene reconstruction. Its category browser opens the attention queue, with optional, tracked, unassessed and all-observation filters. Individual author edits reuse the existing review forms. Canonical views remain linked. Core manuscript completion and the character identity safeguard are unchanged; optional peer review never blocks Return to Book or the Writer Workspace. + +## Migration and existing imports + +This repository uses Dapper and numbered SQL/stored procedures, not EF Core. Apply `PlotLine/Sql/200_StoryIntelligenceExceptionReview.sql` before deploying the application. It adds priority/reason storage and an idempotent knowledge source key, plus review read/assessment procedures. Existing records start unassessed. The migration does not bulk-accept any manuscript data. + +Future preparation assesses saved candidates automatically. Existing imports have an explicit, antiforgery-protected **Update review priorities** POST. It rebuilds evidence from retained scene results and matches current pending stable keys in place. It does not delete unmatched older candidates or request paid reanalysis. Repeated calls are safe; an interrupted update can resume. Reviewed, ignored and already tracked candidates are not reinterpreted. Original reviewed proposal states are excluded from policy context because the author may have corrected them in canonical editors. + +Automatic acceptance and candidate state update share a database transaction. Knowledge inserts are source-key-idempotent, including manual import retries. The existing relationship acceptance procedure is reused. New preparation generations carry settled observations and evidence forward, and candidate saves cannot overwrite them. Historical decisions, including legacy reviewed relationship pairs, take precedence over newly generated proposals. Stale forms are rejected before manual materialisation. + +## Validation and limits + +Run `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj` and `dotnet build PlotLine.slnx` serially. `PlotLine.Tests/Sql/ExceptionReview.sql` is a development-only integration test requiring migration 200 and existing scene/character fixtures. It asserts canonical materialisation, retries, direction, scene events, author decisions, generation carry-forward and distinct counts; all fixture writes roll back. It must never be run against production. + +The actual compiled Review Centre was rendered with synthetic counts in Chromium in light and dark themes, using the existing CSS. These illustrative counts are not classification results for a production manuscript. Development receives migration 200 and the tested build; production is not changed. Existing imports require the explicit priority update to materialise newly eligible observations. + +This is a conservative deterministic first policy, not a semantic continuity detector. Equivalent facts expressed differently, missing learning events across distant scenes, overlapping reciprocal/directional tracks and the narrative explanation of every state change need deeper fact/event alignment. Existing unresolved names filtered by upstream import builders remain in raw analysis; this change detects duplicate-alias ambiguity in candidates but does not redesign character resolution. Legacy pair cards whose stable keys cannot be matched remain inspectable and optional. Existing knowledge vocabulary maps beliefs to Partially Knows and preserves reported/inferred acquisition in evidence; no unsupported new certainty/state is invented. Asset significance and new-identity autoacceptance are left for a dedicated asset design. diff --git a/PlotLine.Tests/ExceptionReviewTests.cs b/PlotLine.Tests/ExceptionReviewTests.cs new file mode 100644 index 00000000..ec432dab --- /dev/null +++ b/PlotLine.Tests/ExceptionReviewTests.cs @@ -0,0 +1,157 @@ +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(); + 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((method, args) => method switch + { + "ListAllAsync" => Task.FromResult>(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(assessment, options)!)); return Task.CompletedTask; } + var service = new StoryIntelligenceExceptionReviewService(repo, + Stub((m, a) => throw new Exception("No analysis/reconstruction during normal assessment")), + Stub((m, a) => throw new Exception("No analysis/reconstruction during normal assessment")), + Stub((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(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((m, a) => m == "BuildReviewAsync" + ? Task.FromResult(new StoryIntelligenceKnowledgeReviewViewModel { Candidates = [recovered] }) : throw new Exception(m)); + var reclassifier = new StoryIntelligenceExceptionReviewService(repo, reconstructed, + Stub((m, a) => throw new Exception("Wrong module")), + Stub((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(Func invoke) where T : class + { var result = DispatchProxy.Create(); ((Proxy)(object)result).Call = invoke; return result; } + public class Proxy : DispatchProxy + { + public Func Call { get; set; } = null!; + protected override object? Invoke(MethodInfo? method, object?[]? args) => Call(method!.Name, args); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index dcaeeb3f..e211eccc 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -19,6 +19,8 @@ using PlotLine.ViewModels; var tests = new (string Name, Action Test)[] { + ("Exception review uses evidence, identity, consequence and directional conflicts", ExceptionReviewTests.DomainPolicy), + ("Exception assessment preserves author decisions and scene history", ExceptionReviewTests.PreserveDecisionsAndObservations), ("Character card widths reflect displayed text without changing character data", CharacterCardLayoutTests.DisplayedContent), ("Scene relationship proposals preserve direction and validate acceptance", RelationshipDevelopmentTests.SceneReviewAndAcceptance), ("Location and asset merges require confirmation and distinct records", EntityMergeTests.ConfirmationAndDistinctRecordsAreRequired), @@ -1154,7 +1156,7 @@ static void StoryIntelligenceHeavyReviewModulesOfferBoundedRendering() var onboarding = File.ReadAllText(Path.Combine(root, "Services/OnboardingStoryIntelligenceService.cs")); var module = string.Equals(viewName, "StoryIntelligenceLocations.cshtml", StringComparison.Ordinal) ? "Location" : "Asset"; var candidateVariable = string.Equals(viewName, "StoryIntelligenceLocations.cshtml", StringComparison.Ordinal) ? "locationCandidates" : "assetCandidates"; - Assert(onboarding.Contains($"reviewCandidates.Get{module}ReviewAsync(frame.Batch, pageNumber, pageSize{(module == "Location" ? ", scope" : "")})", StringComparison.Ordinal), $"{viewName} should use persisted bounded candidate pages."); + Assert(onboarding.Contains($"reviewCandidates.Get{module}ReviewAsync(frame.Batch, pageNumber, pageSize{(module == "Location" ? ", scope" : ", candidateKey")})", StringComparison.Ordinal), $"{viewName} should use persisted bounded candidate pages."); Assert(view.Contains($"var {candidateVariable} = Model.{module}Review.Candidates.ToList();", StringComparison.Ordinal), $"{viewName} should render only the persisted candidate page."); } else @@ -1389,9 +1391,9 @@ static void StoryIntelligenceDetailedReviewGetsUseSelectedModulePaths() { ["StoryIntelligenceCharacters"] = "GetCharacterReviewAsync(batchId, page)", ["StoryIntelligenceLocations"] = "GetLocationReviewAsync(batchId, page, scope: scope)", - ["StoryIntelligenceAssets"] = "GetAssetReviewAsync(batchId, page)", - ["StoryIntelligenceRelationships"] = "GetRelationshipReviewAsync(batchId, page)", - ["StoryIntelligenceKnowledge"] = "GetKnowledgeReviewAsync(batchId, page)", + ["StoryIntelligenceAssets"] = "GetAssetReviewAsync(batchId, page, 25, candidateKey)", + ["StoryIntelligenceRelationships"] = "GetRelationshipReviewAsync(batchId, page, 25, candidateKey)", + ["StoryIntelligenceKnowledge"] = "GetKnowledgeReviewAsync(batchId, page, 25, candidateKey)", ["StoryIntelligenceNarrative"] = "GetNarrativeReviewAsync(batchId)" }; @@ -1423,9 +1425,9 @@ static void StoryIntelligenceDetailedReviewGetsUseSelectedModulePaths() var persistedReviewService = File.ReadAllText(Path.Combine(root, "Services/StoryIntelligenceReviewCandidateService.cs")); Assert(service.Contains("reviewCandidates.GetCharacterReviewAsync(frame.Batch, pageNumber, pageSize)", StringComparison.Ordinal), "Character GET should read persisted review candidates."); Assert(service.Contains("reviewCandidates.GetLocationReviewAsync(frame.Batch, pageNumber, pageSize, scope)", StringComparison.Ordinal), "Location GET should read persisted review candidates."); - Assert(service.Contains("reviewCandidates.GetAssetReviewAsync(frame.Batch, pageNumber, pageSize)", StringComparison.Ordinal), "Asset GET should read persisted review candidates."); - Assert(service.Contains("reviewCandidates.GetRelationshipReviewAsync(frame.Batch, pageNumber, pageSize)", StringComparison.Ordinal), "Relationship GET should read persisted review candidates."); - Assert(service.Contains("reviewCandidates.GetKnowledgeReviewAsync(frame.Batch, pageNumber, pageSize)", StringComparison.Ordinal), "Knowledge GET should read persisted review candidates."); + Assert(service.Contains("reviewCandidates.GetAssetReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)", StringComparison.Ordinal), "Asset GET should read persisted review candidates."); + Assert(service.Contains("reviewCandidates.GetRelationshipReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)", StringComparison.Ordinal), "Relationship GET should read persisted review candidates."); + Assert(service.Contains("reviewCandidates.GetKnowledgeReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)", StringComparison.Ordinal), "Knowledge GET should read persisted review candidates."); Assert(persistedReviewService.Contains("ListPageAsync", StringComparison.Ordinal), "Persisted review service should page through candidate rows."); Assert(!persistedReviewService.Contains("ListSceneResultsAsync", StringComparison.Ordinal), "Persisted review GET service must not parse retained Scene Intelligence JSON."); Assert(!persistedReviewService.Contains("GetRunAsync", StringComparison.Ordinal), "Persisted review GET service must not traverse old run batches."); @@ -1483,15 +1485,13 @@ static void StoryIntelligenceReviewCentreCompletedModulesUseCanonicalDestination Assert(centre.Contains("Explore Locations", StringComparison.Ordinal) && centre.Contains("\"StoryIntelligenceLocations\"", StringComparison.Ordinal), "Incomplete Locations should route to Location review."); Assert(centre.Contains("View Locations", StringComparison.Ordinal) && centre.Contains("\"Locations\"", StringComparison.Ordinal), "Complete Locations should route to Locations/Index."); - Assert(centre.Contains("\"Review Assets\"", StringComparison.Ordinal) && centre.Contains("\"StoryIntelligenceAssets\"", StringComparison.Ordinal), "Incomplete Assets should route to Asset review."); - Assert(centre.Contains("\"View Assets\"", StringComparison.Ordinal) && centre.Contains("\"StoryAssets\"", StringComparison.Ordinal), "Complete Assets should route to StoryAssets/Index."); - - Assert(centre.Contains("\"Review Relationships\"", StringComparison.Ordinal) && centre.Contains("\"StoryIntelligenceRelationships\"", StringComparison.Ordinal), "Incomplete Relationships should route to Relationship review."); - Assert(centre.Contains("\"View Relationships\"", StringComparison.Ordinal) && centre.Contains("\"RelationshipMap\"", StringComparison.Ordinal), "Complete Relationships should route to RelationshipMap/Index."); - Assert(centre.Contains("new { projectId = Model.ProjectID, bookId = Model.BookID }", StringComparison.Ordinal), "Book-scoped canonical destinations should include book context."); - - Assert(centre.Contains("\"Review Knowledge\"", StringComparison.Ordinal) && centre.Contains("\"StoryIntelligenceKnowledge\"", StringComparison.Ordinal), "Incomplete Knowledge should route to Knowledge review."); - Assert(centre.Contains("\"View Knowledge\"", StringComparison.Ordinal) && centre.Contains("\"StoryBible\"", StringComparison.Ordinal), "Complete Knowledge should route to StoryBible/Index."); + var tile = File.ReadAllText(Path.Combine(root, "Views/Shared/_StoryIntelligenceExceptionTile.cshtml")); + var workspace = File.ReadAllText(Path.Combine(root, "Views/IntelligenceReview/Index.cshtml")); + var exceptionModels = File.ReadAllText(Path.Combine(root, "ViewModels/StoryIntelligenceExceptionReviewViewModels.cs")); + Assert(tile.Contains("asp-controller=\"IntelligenceReview\"", StringComparison.Ordinal), "Exception categories should keep their observations accessible after acceptance."); + Assert(workspace.Contains("@Model.CanonicalController", StringComparison.Ordinal), "Observation browser should also link to canonical intelligence."); + foreach (var destination in new[] { "StoryBible", "RelationshipMap", "StoryAssets" }) + Assert(exceptionModels.Contains(destination, StringComparison.Ordinal), "Tracked intelligence must retain its canonical destination."); Assert(centre.Contains("Review Plot Lines & Threads", StringComparison.Ordinal), "Incomplete Plot should route to Plot review."); Assert(centre.Contains("Url.Action(\"StoryIntelligenceNarrative\", \"Onboarding\"", StringComparison.Ordinal), "Incomplete Plot should use the Story Intelligence Plot review route."); @@ -1538,7 +1538,7 @@ static void StoryIntelligenceDetailedReviewsReadPersistedCandidatePages() Assert(repository.Contains("CommandType.StoredProcedure", StringComparison.Ordinal), "Candidate repository should use stored procedures."); Assert(!repository.Contains("SELECT ", StringComparison.Ordinal), "Candidate repository should not use inline SELECT SQL."); Assert(onboarding.Contains("reviewCandidates.GetLocationReviewAsync(frame.Batch, pageNumber, pageSize, scope)", StringComparison.Ordinal), "Normal Location GET should use persisted candidate pages."); - Assert(onboarding.Contains("reviewCandidates.GetRelationshipReviewAsync(frame.Batch, pageNumber, pageSize)", StringComparison.Ordinal), "Normal Relationship GET should use persisted candidate pages."); + Assert(onboarding.Contains("reviewCandidates.GetRelationshipReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)", StringComparison.Ordinal), "Normal Relationship GET should use persisted candidate pages."); Assert(service.Contains("PreparePeerCandidatesAsync", StringComparison.Ordinal), "Scene JSON candidate builders should be isolated to deliberate preparation."); Assert(service.Contains("LoadPageAsync", StringComparison.Ordinal), "Normal review reads should use page loading."); Assert(!ExtractBetween(service, "public async Task GetLocationReviewAsync", "public async Task GetAssetReviewAsync").Contains("BuildReviewAsync", StringComparison.Ordinal), "Location GET must not call the old builder."); @@ -1590,9 +1590,9 @@ static void StoryIntelligenceModuleCompletionLifecycleUsesPersistedCandidates() Assert(onboarding.Contains("var result = await relationshipImport.ImportAsync(batch, form, false)", StringComparison.Ordinal), "Relationship import should not set completion directly."); Assert(onboarding.Contains("var result = await knowledgeImport.ImportAsync(batch, form, false)", StringComparison.Ordinal), "Knowledge import should not set completion directly."); Assert(onboarding.Contains("SummaryNeedsAttentionCount = summary.LocationUncertainCount", StringComparison.Ordinal), "Location attention count should report uncertainty independently of pending imports."); - Assert(onboarding.Contains("ReadyPendingCount(summary.AssetCandidateGenerationStatus, summary.AssetPendingCount)", StringComparison.Ordinal), "Review Centre should use persisted Asset pending count instead of an empty detailed page."); - Assert(onboarding.Contains("ReadyPendingCount(summary.RelationshipCandidateGenerationStatus, summary.RelationshipPendingCount)", StringComparison.Ordinal), "Review Centre should use persisted Relationship pending count instead of an empty detailed page."); - Assert(onboarding.Contains("ReadyPendingCount(summary.KnowledgeCandidateGenerationStatus, summary.KnowledgePendingCount)", StringComparison.Ordinal), "Review Centre should use persisted Knowledge pending count instead of an empty detailed page."); + Assert(onboarding.Contains("priorities.FirstOrDefault(x => x.Module == \"Assets\")?.AttentionCount", StringComparison.Ordinal), "Review Centre should use persisted Asset attention priority independently of the pending decision count."); + Assert(onboarding.Contains("priorities.FirstOrDefault(x => x.Module == \"Relationships\")?.AttentionCount", StringComparison.Ordinal), "Review Centre should use persisted Relationship attention priority independently of the pending decision count."); + Assert(onboarding.Contains("priorities.FirstOrDefault(x => x.Module == \"Knowledge\")?.AttentionCount", StringComparison.Ordinal), "Review Centre should use persisted Knowledge attention priority independently of the pending decision count."); Assert(!ExtractBetween(onboarding, "private async Task GetReviewFrameAsync", "private sealed record StoryIntelligenceReviewFrame").Contains("CompleteModuleIfReadyAsync", StringComparison.Ordinal), "Review Centre GET must not mark module completion."); Assert(summarySql.Contains("CandidateSummary", StringComparison.Ordinal), "Review Centre summary SQL should include persisted current generation state."); @@ -4733,7 +4733,7 @@ static void StoryIntelligenceReviewCentreCompletionIsCategoryScoped() Assert(onboardingStory.Contains("batch.RelationshipStageComplete = state.RelationshipReviewCompletedUtc is not null", StringComparison.Ordinal), "Resume should hydrate Relationship completion from durable state."); Assert(onboardingStory.Contains("batch.KnowledgeStageComplete = state.KnowledgeReviewCompletedUtc is not null", StringComparison.Ordinal), "Resume should hydrate Knowledge completion from durable state."); Assert(onboardingStory.Contains("batch.NarrativeStageComplete = state.NarrativeReviewCompletedUtc is not null", StringComparison.Ordinal), "Resume should hydrate Narrative completion from durable state."); - Assert(reviewView.Contains("Model.PipelineDashboard.RelationshipStageComplete", StringComparison.Ordinal), "Review Centre should render the scoped dashboard completion flags."); + Assert(reviewView.Contains("Model.ReviewSummaries.FirstOrDefault", StringComparison.Ordinal), "Review Centre should use per-category assessment counts independently from completion flags."); var locationGet = ExtractMethod(controller, "StoryIntelligenceLocations"); var assetGet = ExtractMethod(controller, "StoryIntelligenceAssets"); diff --git a/PlotLine.Tests/Sql/ExceptionReview.sql b/PlotLine.Tests/Sql/ExceptionReview.sql new file mode 100644 index 00000000..3aa131a3 --- /dev/null +++ b/PlotLine.Tests/Sql/ExceptionReview.sql @@ -0,0 +1,80 @@ +-- Run against DEVELOPMENT only, after migration 200. Every fixture write rolls back. +SET NOCOUNT ON; +SET XACT_ABORT ON; +SET QUOTED_IDENTIFIER ON; +IF DB_NAME()<>N'PlotDirector_Development' THROW 53900,'Development test only.',1; +IF COL_LENGTH('dbo.StoryIntelligenceReviewCandidates','ReviewPriority') IS NULL THROW 53901,'Migration missing.',1; +BEGIN TRANSACTION; +DECLARE @Book int,@Project int,@Scene int,@A int,@B int,@Generation int,@Candidate int,@Canonical int, + @Key nvarchar(450)=CONCAT(N'regression-',NEWID()),@Payload nvarchar(max),@Assessment nvarchar(max)=N'{"priority":"Tracked","reasons":["Regression evidence"],"version":1}'; +SELECT TOP(1) @Book=b.BookID,@Project=b.ProjectID,@Scene=s.SceneID FROM dbo.Books b + JOIN dbo.Chapters ch ON ch.BookID=b.BookID JOIN dbo.Scenes s ON s.ChapterID=ch.ChapterID + WHERE b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0 + AND (SELECT COUNT(*) FROM dbo.Characters c WHERE c.ProjectID=b.ProjectID AND c.IsArchived=0)>=2 ORDER BY b.BookID,s.SceneID; +SELECT @A=MIN(CharacterID),@B=MAX(CharacterID) FROM dbo.Characters WHERE ProjectID=@Project AND IsArchived=0; +IF @A IS NULL OR @A=@B THROW 53902,'Test needs two characters and a scene.',1; +UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET IsCurrent=0 WHERE BookID=@Book AND Module=N'Knowledge'; +INSERT dbo.StoryIntelligenceReviewCandidateGenerations(ProjectID,BookID,Module,Status,Source) VALUES(@Project,@Book,N'Knowledge',N'Ready',N'Regression'); +SET @Generation=CONVERT(int,SCOPE_IDENTITY()); +DECLARE @KnowledgeState int=(SELECT TOP(1) KnowledgeStateID FROM dbo.KnowledgeStates WHERE StateName=N'Knows'); +SET @Payload=(SELECT @Key [key],@A characterID,@KnowledgeState knowledgeStateID,N'Regression fact' knowledgeStatement,N'Regression evidence' evidence, + JSON_QUERY((SELECT @Scene sceneID,1 chapterNumber,1 sceneNumber,1 sortOrder FOR JSON PATH)) observations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER); +INSERT dbo.StoryIntelligenceReviewCandidates(ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,DisplayName,CandidatePayloadJson) + VALUES(@Generation,@Project,@Book,N'Knowledge',@Key,N'Regression fact',@Payload); +SET @Candidate=CONVERT(int,SCOPE_IDENTITY()); +EXEC dbo.StoryIntelligenceReview_Assess @Candidate,@Generation,@Payload,@Assessment; +SELECT @Canonical=DecisionCanonicalID FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateID=@Candidate AND DecisionStatus=N'AutoAccepted'; +IF @Canonical IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge WHERE CharacterKnowledgeID=@Canonical AND SceneID=@Scene AND CharacterID=@A AND KnowledgeStateID=@KnowledgeState) + THROW 53903,'Tracked knowledge missing from canonical story state.',1; +EXEC dbo.StoryIntelligenceReview_Assess @Candidate,@Generation,@Payload,@Assessment; +IF (SELECT COUNT(*) FROM dbo.CharacterKnowledge WHERE SourceReviewKey=@Key)<>1 THROW 53904,'Retry duplicated knowledge.',1; +-- Explicit reviewed/ignored rows cannot be reassessed. +UPDATE dbo.StoryIntelligenceReviewCandidates SET DecisionStatus=N'Reviewed',DecisionAction=N'Ignore',DecisionCanonicalID=NULL WHERE ReviewCandidateID=@Candidate; +EXEC dbo.StoryIntelligenceReview_Assess @Candidate,@Generation,@Payload,@Assessment; +IF NOT EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateID=@Candidate AND DecisionStatus=N'Reviewed' AND DecisionAction=N'Ignore') THROW 53905,'Author decision overwritten.',1; +-- A regenerated candidate inherits the prior author's decision instead of reaccepting it. +UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET IsCurrent=0 WHERE ReviewCandidateGenerationID=@Generation; +INSERT dbo.StoryIntelligenceReviewCandidateGenerations(ProjectID,BookID,Module,Status,Source) VALUES(@Project,@Book,N'Knowledge',N'Ready',N'Regression'); +SET @Generation=CONVERT(int,SCOPE_IDENTITY()); +INSERT dbo.StoryIntelligenceReviewCandidates(ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,DisplayName,CandidatePayloadJson) + VALUES(@Generation,@Project,@Book,N'Knowledge',@Key,N'Regression fact',@Payload); +SET @Candidate=CONVERT(int,SCOPE_IDENTITY()); +EXEC dbo.StoryIntelligenceReview_Assess @Candidate,@Generation,@Payload,@Assessment; +IF NOT EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateID=@Candidate AND DecisionAction=N'Ignore') THROW 53906,'Prior generation decision lost.',1; +UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET IsCurrent=0 WHERE BookID=@Book AND Module=N'Relationships'; +INSERT dbo.StoryIntelligenceReviewCandidateGenerations(ProjectID,BookID,Module,Status,Source) VALUES(@Project,@Book,N'Relationships',N'Ready',N'Regression'); +SET @Generation=CONVERT(int,SCOPE_IDENTITY()); +DECLARE @Type int=(SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Other'), + @State int=(SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates WHERE StateName=N'Friendly'),@Direction int=0,@RKey nvarchar(450),@FirstID int; +WHILE @Direction<2 +BEGIN + SET @RKey=CONCAT(@Key,N'-r-',@Direction); + SET @Payload=(SELECT @RKey [key],CASE WHEN @Direction=0 THEN @A ELSE @B END characterAID,CASE WHEN @Direction=0 THEN @B ELSE @A END characterBID, + @Scene firstSceneID,@Type relationshipTypeID,@State relationshipStateID,N'Development' proposalKind, + CAST(0 AS bit) isReciprocal,CAST(0 AS bit) isKnownToOtherCharacter,N'Regression development' development FOR JSON PATH,WITHOUT_ARRAY_WRAPPER); + INSERT dbo.StoryIntelligenceReviewCandidates(ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,DisplayName,CandidatePayloadJson) + VALUES(@Generation,@Project,@Book,N'Relationships',@RKey,N'Regression pair',@Payload); + SET @Candidate=CONVERT(int,SCOPE_IDENTITY()); + EXEC dbo.StoryIntelligenceReview_Assess @Candidate,@Generation,@Payload,@Assessment; + EXEC dbo.StoryIntelligenceReview_Assess @Candidate,@Generation,@Payload,@Assessment; + SELECT @Canonical=DecisionCanonicalID FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateID=@Candidate; + IF (SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE SourceReviewKey=@RKey AND SceneID=@Scene)<>1 THROW 53907,'Relationship scene evidence lost or duplicated.',1; + IF @Direction=0 SET @FirstID=@Canonical; + ELSE IF @FirstID=@Canonical THROW 53908,'Directional tracks flattened.',1; + SET @Direction+=1; +END; +DECLARE @Summary TABLE(Module nvarchar(40),IdentifiedCount int,TrackedCount int,OptionalCount int,AttentionCount int,UnassessedCount int,DecidedCount int,PairCount int); +INSERT @Summary EXEC dbo.StoryIntelligenceReview_Summary @Book; +IF NOT EXISTS(SELECT 1 FROM @Summary WHERE Module=N'Relationships' AND IdentifiedCount=2 AND TrackedCount=2 AND AttentionCount=0 AND PairCount=1) + THROW 53909,'Summary confuses extraction with attention.',1; +-- Repreparation retains settled observations, and a save cannot overwrite their payload. +EXEC dbo.StoryIntelligenceReviewCandidateGeneration_Begin @Project,@Book,N'Relationships',N'Regression'; +SELECT @Generation=ReviewCandidateGenerationID FROM dbo.StoryIntelligenceReviewCandidateGenerations WHERE BookID=@Book AND Module=N'Relationships' AND IsCurrent=1; +IF (SELECT COUNT(*) FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateGenerationID=@Generation AND DecisionStatus=N'AutoAccepted')<>2 + THROW 53910,'Settled observations disappeared during preparation.',1; +SET @Payload=JSON_MODIFY(@Payload,'$.development',N'Overwritten evidence'); +EXEC dbo.StoryIntelligenceReviewCandidate_Save @ReviewCandidateGenerationID=@Generation,@ProjectID=@Project,@BookID=@Book,@Module=N'Relationships',@StableKey=@RKey,@DisplayName=N'Regression pair',@SortOrder=1,@CandidatePayloadJson=@Payload; +IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateGenerationID=@Generation AND JSON_VALUE(CandidatePayloadJson,'$.development')=N'Overwritten evidence') + THROW 53911,'Settled evidence was overwritten.',1; +ROLLBACK; +SELECT N'PASS: canonical writes, retry safety, direction, scene events, decisions, generation preservation and counts; all fixtures rolled back.'; diff --git a/PlotLine/Controllers/IntelligenceReviewController.cs b/PlotLine/Controllers/IntelligenceReviewController.cs new file mode 100644 index 00000000..8d762778 --- /dev/null +++ b/PlotLine/Controllers/IntelligenceReviewController.cs @@ -0,0 +1,73 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.ViewModels; + +namespace PlotLine.Controllers; + +[Authorize] +[Route("intelligence-review")] +public sealed class IntelligenceReviewController( + IOnboardingStoryIntelligenceService onboarding, + IOnboardingStoryIntelligenceBatchStore batches, + ICurrentUserService user, + IStoryIntelligenceExceptionReviewService review, + ILogger logger) : Controller +{ + private static bool Supported(string module) => module is "Knowledge" or "Relationships" or "Assets"; + [HttpGet("")] + public async Task Index(Guid batchId, string module, string scope = "Attention", int page = 1) + { + if (!Supported(module)) return NotFound(); + var frame = await onboarding.GetReviewCentreAsync(batchId); + if (frame is null) return NotFound(); + if (!frame.CharacterGateSatisfied || !frame.SceneAnalysisComplete || frame.HasActiveRuns) + return RedirectToAction("StoryIntelligenceReviewCentre", "Onboarding", new { batchId }); + scope = scope is "Attention" or "Optional" or "Tracked" or "Unassessed" or "All" ? scope : "Attention"; + var all = (await review.ListAsync(frame.BookID, module)).Select(StoryIntelligenceReviewEntry.From).ToList(); + var selected = all.Where(x => scope == "All" || (scope == "Tracked" ? x.Row.DecisionStatus == "AutoAccepted" || (x.Row.DecisionStatus == "Reviewed" && x.Row.DecisionAction != "Ignore") + : x.Pending && x.Row.ReviewPriority == scope)).ToList(); + var pageCount = Math.Max(1, (int)Math.Ceiling(selected.Count / 25d)); + page = Math.Clamp(page, 1, pageCount); + var items = selected.Skip((page - 1) * 25).Take(25).ToList(); + var pairs = items.Select(x => x.PairKey).ToHashSet(); + return View(new StoryIntelligenceExceptionReviewViewModel + { + BatchID = batchId, + BookID = frame.BookID, + ProjectID = frame.ProjectID, + Module = module, + Scope = scope, + Page = page, + PageCount = pageCount, + Summary = frame.ReviewSummaries.FirstOrDefault(x => x.Module == module) ?? new() { Module = module }, + Items = items, + History = module == "Relationships" ? all.Where(x => pairs.Contains(x.PairKey)).OrderBy(x => x.Observations.FirstOrDefault()?.ChapterNumber) + .ThenBy(x => x.Observations.FirstOrDefault()?.SceneNumber).ThenBy(x => x.Observations.FirstOrDefault()?.SortOrder).ToList() : [] + }); + } + + [HttpPost("assess")] + [ValidateAntiForgeryToken] + public async Task Assess(Guid batchId, string module) + { + if (!Supported(module) || !user.UserId.HasValue) return NotFound(); + var frame = await onboarding.GetReviewCentreAsync(batchId); + var batch = await batches.GetAsync(user.UserId.Value, batchId); + if (frame is null || batch is null) return NotFound(); + if (!frame.CharacterGateSatisfied || !frame.SceneAnalysisComplete || frame.HasActiveRuns) + return BadRequest("Finish analysis and character identity review before updating priorities."); + try + { + await review.ReassessAsync(batch, module); + TempData["ReviewMessage"] = "Priorities updated from saved scene evidence. Supported observations are tracked automatically; your decisions are preserved."; + } + catch (Exception ex) + { + logger.LogError(ex, "Review reassessment failed for book {BookID}, module {Module}", batch.BookID, module); + TempData["ReviewError"] = "The update could not finish. Completed assessments are saved safely; retry to continue."; + } + return RedirectToAction(nameof(Index), new { batchId, module }); + } +} diff --git a/PlotLine/Controllers/OnboardingController.cs b/PlotLine/Controllers/OnboardingController.cs index 4d961a12..1a703ada 100644 --- a/PlotLine/Controllers/OnboardingController.cs +++ b/PlotLine/Controllers/OnboardingController.cs @@ -434,9 +434,9 @@ public sealed class OnboardingController( } [HttpGet("story-intelligence/assets")] - public async Task StoryIntelligenceAssets(Guid batchId, int page = 1) + public async Task StoryIntelligenceAssets(Guid batchId, int page = 1, string? candidateKey = null) { - var model = await storyIntelligence.GetAssetReviewAsync(batchId, page); + var model = await storyIntelligence.GetAssetReviewAsync(batchId, page, 25, candidateKey); if (model is null) { return NotFound(); @@ -461,9 +461,9 @@ public sealed class OnboardingController( } [HttpGet("story-intelligence/relationships")] - public async Task StoryIntelligenceRelationships(Guid batchId, int page = 1) + public async Task StoryIntelligenceRelationships(Guid batchId, int page = 1, string? candidateKey = null) { - var model = await storyIntelligence.GetRelationshipReviewAsync(batchId, page); + var model = await storyIntelligence.GetRelationshipReviewAsync(batchId, page, 25, candidateKey); if (model is null) { return NotFound(); @@ -633,9 +633,9 @@ public sealed class OnboardingController( } [HttpGet("story-intelligence/knowledge")] - public async Task StoryIntelligenceKnowledge(Guid batchId, int page = 1) + public async Task StoryIntelligenceKnowledge(Guid batchId, int page = 1, string? candidateKey = null) { - var model = await storyIntelligence.GetKnowledgeReviewAsync(batchId, page); + var model = await storyIntelligence.GetKnowledgeReviewAsync(batchId, page, 25, candidateKey); if (model is null) { return NotFound(); diff --git a/PlotLine/Data/Repositories.cs b/PlotLine/Data/Repositories.cs index ef922eb1..11461b2c 100644 --- a/PlotLine/Data/Repositories.cs +++ b/PlotLine/Data/Repositories.cs @@ -4093,6 +4093,7 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory) knowledge.SceneID, knowledge.KnowledgeStateID, knowledge.SourceEventID, + knowledge.SourceReviewKey, knowledge.Description }, commandType: CommandType.StoredProcedure); diff --git a/PlotLine/Data/StoryIntelligenceReviewCandidateRepository.cs b/PlotLine/Data/StoryIntelligenceReviewCandidateRepository.cs index bd8b9a2e..552121fe 100644 --- a/PlotLine/Data/StoryIntelligenceReviewCandidateRepository.cs +++ b/PlotLine/Data/StoryIntelligenceReviewCandidateRepository.cs @@ -6,6 +6,9 @@ namespace PlotLine.Data; public interface IStoryIntelligenceReviewCandidateRepository { + Task> ListAllAsync(int bookId, string module); + Task> GetReviewSummaryAsync(int bookId); + Task AssessAsync(int candidateId, int generationId, string payloadJson, string assessmentJson); Task RefreshPendingRelationshipsAsync(int bookId, int generationId, string payloadJson); Task BeginGenerationAsync(int projectId, int bookId, string module, string source); Task GetCurrentGenerationAsync(int bookId, string module); @@ -22,6 +25,25 @@ public interface IStoryIntelligenceReviewCandidateRepository public sealed class StoryIntelligenceReviewCandidateRepository(ISqlConnectionFactory connectionFactory) : IStoryIntelligenceReviewCandidateRepository { + public async Task> ListAllAsync(int bookId, string module) + { + using var connection = connectionFactory.CreateConnection(); + return (await connection.QueryAsync("dbo.StoryIntelligenceReview_List", + new { BookID=bookId, Module=module }, commandType: CommandType.StoredProcedure)).ToList(); + } + public async Task> GetReviewSummaryAsync(int bookId) + { + using var connection = connectionFactory.CreateConnection(); + return (await connection.QueryAsync("dbo.StoryIntelligenceReview_Summary", + new { BookID=bookId }, commandType: CommandType.StoredProcedure)).ToList(); + } + public async Task AssessAsync(int candidateId, int generationId, string payloadJson, string assessmentJson) + { + using var connection = connectionFactory.CreateConnection(); + await connection.ExecuteAsync("dbo.StoryIntelligenceReview_Assess", new { ReviewCandidateID=candidateId, + ExpectedGenerationID=generationId, PayloadJson=payloadJson, AssessmentJson=assessmentJson }, commandType: CommandType.StoredProcedure); + } + public async Task RefreshPendingRelationshipsAsync(int bookId, int generationId, string payloadJson) { using var connection = connectionFactory.CreateConnection(); diff --git a/PlotLine/Help/Articles/StoryIntelligence/Knowledge.md b/PlotLine/Help/Articles/StoryIntelligence/Knowledge.md index 03ad1ca1..c699a339 100644 --- a/PlotLine/Help/Articles/StoryIntelligence/Knowledge.md +++ b/PlotLine/Help/Articles/StoryIntelligence/Knowledge.md @@ -11,6 +11,8 @@ screenshot: # Reviewing Story Intelligence Knowledge +Supported, unambiguous knowledge is tracked automatically. Beliefs, suspicions, reported facts and inferred knowledge remain distinguishable in the saved evidence; consequential uncertainty or conflicting awareness is flagged with a reason. Lower-confidence ordinary observations are available for optional review rather than treated as urgent tasks. + Read who holds the knowledge and the supporting evidence. A character can believe something false, suspect a truth without proof, or discover a fact later than the reader. Choose a state that reflects the character at this point in the story. Create a distinct record, link the proposed existing match, merge duplicate suggestions, or ignore unsupported material. Previous and Next submit the displayed decisions. Check bulk selections before saving, especially where similar facts belong to different characters. diff --git a/PlotLine/Help/Articles/StoryIntelligence/Relationships.md b/PlotLine/Help/Articles/StoryIntelligence/Relationships.md index 0e82f884..1c34850d 100644 --- a/PlotLine/Help/Articles/StoryIntelligence/Relationships.md +++ b/PlotLine/Help/Articles/StoryIntelligence/Relationships.md @@ -11,6 +11,8 @@ screenshot: # Reviewing Story Intelligence Relationships +Supported scene observations are tracked automatically. Explore the exception queue or expand a pair's relationship journey to see its complete saved history, including both directions. Opposite feelings in different directions are valid; opposing interpretations on the same directional track, weakly supported reversals and uncertain major developments can be flagged. Missing direction in older analysis prevents automatic acceptance. + Each card proposes a fact or development in a particular scene. Read the scene and supporting context, then correct the track, state and direction before accepting. The confidence badge describes the suggestion, not the strength of the emotion. A relationship track is the underlying connection. Its state can change from Friendly to Tense or Reconciled as the story develops. Acceptance reuses a matching relationship where possible and adds this scene event, preserving existing history. diff --git a/PlotLine/Help/Articles/StoryIntelligence/ReviewCentre.md b/PlotLine/Help/Articles/StoryIntelligence/ReviewCentre.md index dea6fc9b..75c79a4b 100644 --- a/PlotLine/Help/Articles/StoryIntelligence/ReviewCentre.md +++ b/PlotLine/Help/Articles/StoryIntelligence/ReviewCentre.md @@ -16,3 +16,9 @@ Confirm character identities first so relationships, knowledge and plot analysis Preparing or Analysing means background work is still underway. Failed categories offer Retry when supported. Complete means that category has been handled; it does not mean every suggestion was accepted. Other categories can be reviewed in any order once unlocked. Locations let you explore significant settings and uncertain identities. Scene Metrics opens analysed values on the Timeline. Return to Book or the Writer Workspace whenever you want to continue writing. + +Knowledge, Relationships and Assets distinguish **observations identified**, **tracked**, **worth reviewing**, and **needs attention**. Tracked knowledge and relationship events are already usable elsewhere in Story Intelligence. Worth reviewing is optional; needs attention means there is a specific ambiguity, conflict or consequential uncertainty to inspect. Large extraction counts are not a list of mandatory tasks. + +Open a category to filter by priority, inspect saved scene evidence, or browse all observations, including your ignored decisions. Relationship journeys group a character pair while retaining both directions and every saved scene proposal. The tracked intelligence link opens its usual story view. + +Older imports initially show observations awaiting priority assessment. **Update review priorities** uses the saved analysis, accepts supported observations and explains remaining exceptions. It makes no new AI requests and preserves your reviewed decisions. Missing older evidence stays available for optional review. Return to your book at any time; optional review does not prevent writing. diff --git a/PlotLine/Models/CoreModels.cs b/PlotLine/Models/CoreModels.cs index d8f81638..5ed9a6b6 100644 --- a/PlotLine/Models/CoreModels.cs +++ b/PlotLine/Models/CoreModels.cs @@ -1229,6 +1229,8 @@ public sealed class KnowledgeState public sealed class CharacterKnowledgeItem { + [Microsoft.AspNetCore.Mvc.ModelBinding.BindNever] + public string? SourceReviewKey { get; set; } public int CharacterKnowledgeID { get; set; } public int CharacterID { get; set; } public string CharacterName { get; set; } = string.Empty; diff --git a/PlotLine/Models/StoryIntelligenceReviewAssessment.cs b/PlotLine/Models/StoryIntelligenceReviewAssessment.cs new file mode 100644 index 00000000..06470900 --- /dev/null +++ b/PlotLine/Models/StoryIntelligenceReviewAssessment.cs @@ -0,0 +1,33 @@ +namespace PlotLine.Models; + +// Review priority is independent of an author's decision and of extraction confidence. +public sealed record StoryIntelligenceReviewAssessment(string Priority, string[] Reasons, int Version = 1) +{ + public const string Tracked = "Tracked"; + public const string Optional = "Optional"; + public const string Attention = "Attention"; + public const string Unassessed = "Unassessed"; +} + +public sealed class StoryIntelligenceObservationEvidence +{ + public int SceneID { get; init; } + public decimal ChapterNumber { get; init; } + public decimal SceneNumber { get; init; } + public int SortOrder { get; init; } + public string? Signal { get; init; } + public string? Evidence { get; init; } + public decimal? Confidence { get; init; } +} + +public sealed class StoryIntelligenceReviewSummary +{ + public string Module { get; init; } = ""; + public int IdentifiedCount { get; init; } + public int TrackedCount { get; init; } + public int OptionalCount { get; init; } + public int AttentionCount { get; init; } + public int UnassessedCount { get; init; } + public int DecidedCount { get; init; } + public int PairCount { get; init; } +} diff --git a/PlotLine/Models/StoryIntelligenceReviewCandidateModels.cs b/PlotLine/Models/StoryIntelligenceReviewCandidateModels.cs index 7057c9da..413905a0 100644 --- a/PlotLine/Models/StoryIntelligenceReviewCandidateModels.cs +++ b/PlotLine/Models/StoryIntelligenceReviewCandidateModels.cs @@ -36,6 +36,8 @@ public sealed class StoryIntelligenceReviewCandidateGeneration public sealed class StoryIntelligenceReviewCandidateRow { + public string ReviewPriority { get; init; } = StoryIntelligenceReviewAssessment.Unassessed; + public string? AssessmentJson { get; init; } public int ReviewCandidateID { get; init; } public int ReviewCandidateGenerationID { get; init; } public int ProjectID { get; init; } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index ec122270..bea3be3c 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -240,6 +240,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/OnboardingStoryIntelligenceService.cs b/PlotLine/Services/OnboardingStoryIntelligenceService.cs index 09aa93cc..93d14047 100644 --- a/PlotLine/Services/OnboardingStoryIntelligenceService.cs +++ b/PlotLine/Services/OnboardingStoryIntelligenceService.cs @@ -15,9 +15,9 @@ public interface IOnboardingStoryIntelligenceService Task GetReviewCentreAsync(Guid batchId); Task GetCharacterReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25); Task GetLocationReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string scope = "significant"); - Task GetAssetReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25); - Task GetRelationshipReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25); - Task GetKnowledgeReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25); + Task GetAssetReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string? candidateKey = null); + Task GetRelationshipReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string? candidateKey = null); + Task GetKnowledgeReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string? candidateKey = null); Task GetNarrativeReviewAsync(Guid batchId); Task CancelAsync(Guid batchId); Task<(StoryIntelligenceProgressViewModel? Progress, StoryIntelligenceImportCommitResult Result)> CommitAsync(Guid batchId, int runId); @@ -65,7 +65,8 @@ public sealed class OnboardingStoryIntelligenceService( IStoryIntelligenceProgressNotifier notifier, ICurrentUserService currentUser, IStoryIntelligenceEntitlementService entitlement, - ILogger logger) : IOnboardingStoryIntelligenceService + ILogger logger, + IStoryIntelligenceExceptionReviewService? exceptionReview = null) : IOnboardingStoryIntelligenceService { private const string PromptVersionsSummary = "Chapter=Chapter-Structure-Prompt-V2; Scene=Scene-Prompt-V2"; private const string SourceType = "OnboardingWordCompanionChapter"; @@ -772,14 +773,14 @@ public sealed class OnboardingStoryIntelligenceService( public Task GetLocationReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string scope = "significant") => GetSelectedReviewAsync(batchId, "Locations", async frame => frame.Model.LocationReview = await reviewCandidates.GetLocationReviewAsync(frame.Batch, pageNumber, pageSize, scope)); - public Task GetAssetReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25) - => GetSelectedReviewAsync(batchId, "Assets", async frame => frame.Model.AssetReview = await reviewCandidates.GetAssetReviewAsync(frame.Batch, pageNumber, pageSize)); + public Task GetAssetReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string? candidateKey = null) + => GetSelectedReviewAsync(batchId, "Assets", async frame => frame.Model.AssetReview = await reviewCandidates.GetAssetReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)); - public Task GetRelationshipReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25) - => GetSelectedReviewAsync(batchId, "Relationships", async frame => frame.Model.RelationshipReview = await reviewCandidates.GetRelationshipReviewAsync(frame.Batch, pageNumber, pageSize)); + public Task GetRelationshipReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string? candidateKey = null) + => GetSelectedReviewAsync(batchId, "Relationships", async frame => frame.Model.RelationshipReview = await reviewCandidates.GetRelationshipReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)); - public Task GetKnowledgeReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25) - => GetSelectedReviewAsync(batchId, "Knowledge", async frame => frame.Model.KnowledgeReview = await reviewCandidates.GetKnowledgeReviewAsync(frame.Batch, pageNumber, pageSize)); + public Task GetKnowledgeReviewAsync(Guid batchId, int pageNumber = 1, int pageSize = 25, string? candidateKey = null) + => GetSelectedReviewAsync(batchId, "Knowledge", async frame => frame.Model.KnowledgeReview = await reviewCandidates.GetKnowledgeReviewAsync(frame.Batch, pageNumber, pageSize, candidateKey)); public Task GetNarrativeReviewAsync(Guid batchId) => GetSelectedReviewAsync(batchId, "PlotLinesThreads", async frame => @@ -842,6 +843,7 @@ public sealed class OnboardingStoryIntelligenceService( return null; } + var priorities = exceptionReview is null ? new List() : await exceptionReview.SummaryAsync(batch.BookID); var characterComplete = summary.CharacterReviewCompletedUtc is not null; var locationComplete = summary.LocationReviewCompletedUtc is not null; var assetComplete = summary.AssetReviewCompletedUtc is not null; @@ -857,6 +859,7 @@ public sealed class OnboardingStoryIntelligenceService( var model = new StoryIntelligenceProgressViewModel { + ReviewSummaries = priorities, BatchID = batch.BatchID, PreviewID = batch.PreviewID, ImportSessionID = summary.StoryIntelligenceBookPipelineID, @@ -888,21 +891,21 @@ public sealed class OnboardingStoryIntelligenceService( HasCommittedScenes = hasCommittedScenes, CanImport = !assetComplete, IsComplete = assetComplete, - SummaryNeedsAttentionCount = assetComplete ? 0 : ReadyPendingCount(summary.AssetCandidateGenerationStatus, summary.AssetPendingCount) + SummaryNeedsAttentionCount = priorities.FirstOrDefault(x => x.Module == "Assets")?.AttentionCount }, RelationshipReview = new StoryIntelligenceRelationshipReviewViewModel { HasCommittedScenes = hasCommittedScenes, CanImport = !relationshipComplete, IsComplete = relationshipComplete, - SummaryNeedsAttentionCount = relationshipComplete ? 0 : ReadyPendingCount(summary.RelationshipCandidateGenerationStatus, summary.RelationshipPendingCount) + SummaryNeedsAttentionCount = priorities.FirstOrDefault(x => x.Module == "Relationships")?.AttentionCount }, KnowledgeReview = new StoryIntelligenceKnowledgeReviewViewModel { HasCommittedScenes = hasCommittedScenes, CanImport = !knowledgeComplete, IsComplete = knowledgeComplete, - SummaryNeedsAttentionCount = knowledgeComplete ? 0 : ReadyPendingCount(summary.KnowledgeCandidateGenerationStatus, summary.KnowledgePendingCount) + SummaryNeedsAttentionCount = priorities.FirstOrDefault(x => x.Module == "Knowledge")?.AttentionCount }, NarrativeReview = new StoryIntelligenceNarrativeReviewViewModel { @@ -1151,6 +1154,15 @@ public sealed class OnboardingStoryIntelligenceService( return (null, new StoryIntelligenceImportCommitResult { Success = false, Message = "This Story Intelligence batch could not be found." }); } + if (exceptionReview is not null) + { + var pendingKeys = (await exceptionReview.ListAsync(batch.BookID, "Assets")) + .Where(x => x.DecisionStatus == "Pending").Select(x => x.StableKey).ToHashSet(StringComparer.OrdinalIgnoreCase); + if (form.Assets.Any(x => !pendingKeys.Contains(x.Key))) + return (await GetReviewCentreAsync(batchId), new StoryIntelligenceImportCommitResult + { Success=false, Message="These observations have already been decided or updated. Reload review before saving." }); + } + var result = await assetImport.ImportAsync(batch, form, false); if (result.Success) { @@ -1197,6 +1209,15 @@ public sealed class OnboardingStoryIntelligenceService( return (null, new StoryIntelligenceImportCommitResult { Success = false, Message = "This Story Intelligence batch could not be found." }); } + if (exceptionReview is not null) + { + var pendingKeys = (await exceptionReview.ListAsync(batch.BookID, "Relationships")) + .Where(x => x.DecisionStatus == "Pending").Select(x => x.StableKey).ToHashSet(StringComparer.OrdinalIgnoreCase); + if (form.Relationships.Any(x => !pendingKeys.Contains(x.Key))) + return (await GetReviewCentreAsync(batchId), new StoryIntelligenceImportCommitResult + { Success=false, Message="These observations have already been decided or updated. Reload review before saving." }); + } + var result = await relationshipImport.ImportAsync(batch, form, false); if (result.Success) { @@ -1242,6 +1263,15 @@ public sealed class OnboardingStoryIntelligenceService( return (null, new StoryIntelligenceImportCommitResult { Success = false, Message = "This Story Intelligence batch could not be found." }); } + if (exceptionReview is not null) + { + var pendingKeys = (await exceptionReview.ListAsync(batch.BookID, "Knowledge")) + .Where(x => x.DecisionStatus == "Pending").Select(x => x.StableKey).ToHashSet(StringComparer.OrdinalIgnoreCase); + if (form.Knowledge.Any(x => !pendingKeys.Contains(x.Key))) + return (await GetReviewCentreAsync(batchId), new StoryIntelligenceImportCommitResult + { Success=false, Message="These observations have already been decided or updated. Reload review before saving." }); + } + var result = await knowledgeImport.ImportAsync(batch, form, false); if (result.Success) { diff --git a/PlotLine/Services/StoryIntelligenceExceptionReviewService.cs b/PlotLine/Services/StoryIntelligenceExceptionReviewService.cs new file mode 100644 index 00000000..f48bab67 --- /dev/null +++ b/PlotLine/Services/StoryIntelligenceExceptionReviewService.cs @@ -0,0 +1,68 @@ +using System.Text.Json; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.ViewModels; + +namespace PlotLine.Services; + +public interface IStoryIntelligenceExceptionReviewService +{ + Task AssessPreparedAsync(int bookId, string module); + Task ReassessAsync(OnboardingStoryIntelligenceBatch batch, string module); + Task> SummaryAsync(int bookId); + Task> ListAsync(int bookId, string module); +} + +public sealed class StoryIntelligenceExceptionReviewService( + IStoryIntelligenceReviewCandidateRepository repository, + IStoryIntelligenceKnowledgeImportService knowledge, + IStoryIntelligenceRelationshipImportService relationships, + IStoryIntelligenceAssetImportService assets) : IStoryIntelligenceExceptionReviewService +{ + public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + public Task> SummaryAsync(int bookId) => repository.GetReviewSummaryAsync(bookId); + public Task> ListAsync(int bookId, string module) => repository.ListAllAsync(bookId, module); + public Task AssessPreparedAsync(int bookId, string module) => AssessAsync(bookId, module, new Dictionary()); + + // Explicit POST only: recover richer evidence from stored scene JSON, never call an AI client. + // Match stable keys in place. Unmatched older proposals stay visible and optional, never guessed or deleted. + public async Task ReassessAsync(OnboardingStoryIntelligenceBatch batch, string module) + { + Dictionary payloads = module switch + { + StoryIntelligenceReviewModules.Knowledge => (await knowledge.BuildReviewAsync(batch)).Candidates.ToDictionary(x => x.Key, x => JsonSerializer.Serialize(x, JsonOptions)), + StoryIntelligenceReviewModules.Relationships => (await relationships.BuildReviewAsync(batch)).Candidates.ToDictionary(x => x.Key, x => JsonSerializer.Serialize(x, JsonOptions)), + StoryIntelligenceReviewModules.Assets => (await assets.BuildReviewAsync(batch)).Candidates.ToDictionary(x => x.Key, x => JsonSerializer.Serialize(x, JsonOptions)), + _ => throw new ArgumentException("Unsupported review category.", nameof(module)) + }; + await AssessAsync(batch.BookID, module, payloads); + } + + private async Task AssessAsync(int bookId, string module, IReadOnlyDictionary refreshed) + { + if (module is not (StoryIntelligenceReviewModules.Knowledge or StoryIntelligenceReviewModules.Relationships or StoryIntelligenceReviewModules.Assets)) return; + var rows = await repository.ListAllAsync(bookId, module); + string Payload(StoryIntelligenceReviewCandidateRow row) => row.DecisionStatus == "Pending" && refreshed.TryGetValue(row.StableKey, out var json) ? json : row.CandidatePayloadJson; + // Ignored proposals are not evidence against a later observation. Reviewed proposals may + // have been corrected in canonical editors; do not reinterpret their original AI state. + var contextRows = rows.Where(x => x.DecisionStatus is "Pending" or "AutoAccepted").ToList(); + var knowledgeContext = module == StoryIntelligenceReviewModules.Knowledge + ? contextRows.Select(x => JsonSerializer.Deserialize(Payload(x), JsonOptions)!).ToList() : []; + var relationshipContext = module == StoryIntelligenceReviewModules.Relationships + ? contextRows.Select(x => JsonSerializer.Deserialize(Payload(x), JsonOptions)!).ToList() : []; + // Classify the whole snapshot before accepting any item; conflicts cannot disappear as rows are accepted. + var assessments = rows.Where(x => x.DecisionStatus == "Pending").Select(row => + { + var payload = Payload(row); + var assessment = module switch + { + StoryIntelligenceReviewModules.Knowledge => StoryIntelligenceReviewPolicy.Knowledge(JsonSerializer.Deserialize(payload, JsonOptions)!, knowledgeContext), + StoryIntelligenceReviewModules.Relationships => StoryIntelligenceReviewPolicy.Relationship(JsonSerializer.Deserialize(payload, JsonOptions)!, relationshipContext), + _ => StoryIntelligenceReviewPolicy.Asset(JsonSerializer.Deserialize(payload, JsonOptions)!) + }; + return (Row: row, Payload: payload, Assessment: assessment); + }).ToList(); + foreach (var item in assessments) + await repository.AssessAsync(item.Row.ReviewCandidateID, item.Row.ReviewCandidateGenerationID, item.Payload, JsonSerializer.Serialize(item.Assessment, JsonOptions)); + } +} diff --git a/PlotLine/Services/StoryIntelligenceKnowledgeImportService.cs b/PlotLine/Services/StoryIntelligenceKnowledgeImportService.cs index bd679de5..5f5ae690 100644 --- a/PlotLine/Services/StoryIntelligenceKnowledgeImportService.cs +++ b/PlotLine/Services/StoryIntelligenceKnowledgeImportService.cs @@ -62,6 +62,12 @@ public sealed class StoryIntelligenceKnowledgeImportService( Candidates = visibleCandidates.Select(candidate => new StoryIntelligenceKnowledgeReviewCandidateViewModel { Key = candidate.Key, + CharacterID = candidate.CharacterID, + StoryAssetID = candidate.StoryAssetID, + RawConfidence = candidate.Confidence, + AmbiguousIdentity = candidate.AmbiguousIdentity, + Observations = candidate.Appearances.OrderBy(a => a.ChapterNumber).ThenBy(a => a.SceneNumber).ThenBy(a => a.SortOrder).Select(a => new StoryIntelligenceObservationEvidence + { SceneID=a.SceneID, ChapterNumber=a.ChapterNumber, SceneNumber=a.SceneNumber, SortOrder=a.SortOrder, Signal=a.ChangeType, Evidence=a.Evidence, Confidence=a.Confidence }).ToList(), CharacterName = candidate.CharacterName, KnowledgeStatement = candidate.KnowledgeStatement, KnowledgeStateID = ResolveKnowledgeStateID(lookupData.KnowledgeStates, selectedStateIds.GetValueOrDefault(candidate.Key), candidate.KnowledgeStateName), @@ -129,6 +135,7 @@ public sealed class StoryIntelligenceKnowledgeImportService( continue; } + choice.AcceptedKnowledgeID = null; if (string.Equals(choice.Action, StoryIntelligenceKnowledgeImportActions.Ignore, StringComparison.OrdinalIgnoreCase)) { ignored++; @@ -152,10 +159,11 @@ public sealed class StoryIntelligenceKnowledgeImportService( return new StoryIntelligenceImportCommitResult { Success = false, Message = "Choose a valid knowledge state for each knowledge item you want to create." }; } - var firstAppearance = candidate.Appearances.OrderBy(appearance => appearance.SceneNumber).First(); + var firstAppearance = candidate.Appearances.OrderBy(appearance => appearance.ChapterNumber).ThenBy(appearance => appearance.SceneNumber).ThenBy(appearance => appearance.SortOrder).First(); knowledgeId = await characters.SaveKnowledgeAsync(new CharacterKnowledgeItem { CharacterID = candidate.CharacterID, + SourceReviewKey = candidate.Key, StoryAssetID = candidate.StoryAssetID, PlotThreadID = null, SceneID = firstAppearance.SceneID, @@ -170,6 +178,7 @@ public sealed class StoryIntelligenceKnowledgeImportService( linkedExisting++; } + choice.AcceptedKnowledgeID = knowledgeId; resolvedKnowledge[candidate.Key] = knowledgeId.Value; AddDecision(batch, candidate.Key, choice.Action, knowledgeId.Value, KnowledgeLabel(candidate), true); } @@ -198,6 +207,7 @@ public sealed class StoryIntelligenceKnowledgeImportService( continue; } + choice.AcceptedKnowledgeID = targetKnowledgeId; resolvedKnowledge[candidate.Key] = targetKnowledgeId; merged++; AddDecision(batch, candidate.Key, StoryIntelligenceKnowledgeImportActions.Alias, targetKnowledgeId, KnowledgeLabel(candidate), true); @@ -372,13 +382,16 @@ public sealed class StoryIntelligenceKnowledgeImportService( candidate.KnowledgeStateName = KnowledgeStateFromSignal(changeType, statement, knowledgeStates); } + candidate.AmbiguousIdentity |= character.Ambiguous; candidate.Confidence = Max(candidate.Confidence, confidence); candidate.FirstScene ??= BuildSceneReference(importedScene); candidate.ExampleScene ??= BuildFirstAppearance(importedScene, parsed); candidate.Evidence ??= Clean(evidence); candidate.Appearances.Add(new KnowledgeAppearanceImport( importedScene.SceneID, + importedScene.ChapterNumber, importedScene.SceneNumber, + importedScene.SortOrder, importedScene.SceneTitle, changeType, evidence, @@ -751,6 +764,7 @@ public sealed class StoryIntelligenceKnowledgeImportService( public int? StoryAssetID { get; } = storyAssetId; public int? ExistingKnowledgeID { get; } = existingKnowledgeId; public string? ExistingKnowledgeLabel { get; } = existingKnowledgeLabel; + public bool AmbiguousIdentity { get; set; } public decimal? Confidence { get; set; } public string? FirstScene { get; set; } public string? ExampleScene { get; set; } @@ -760,7 +774,9 @@ public sealed class StoryIntelligenceKnowledgeImportService( private sealed record KnowledgeAppearanceImport( int SceneID, + decimal ChapterNumber, decimal SceneNumber, + int SortOrder, string SceneTitle, string? ChangeType, string? Evidence, @@ -773,11 +789,16 @@ public sealed class StoryIntelligenceKnowledgeImportService( public void Add(string? name, int characterId, string characterName) { var key = Clean(name); - if (string.IsNullOrWhiteSpace(key) || byName.ContainsKey(key)) + if (string.IsNullOrWhiteSpace(key)) { return; } + if (byName.TryGetValue(key, out var previous)) + { + if (previous.CharacterID != characterId) byName[key] = previous with { Ambiguous = true }; + return; + } byName[key] = new CharacterMatch(characterId, characterName); } @@ -792,7 +813,7 @@ public sealed class StoryIntelligenceKnowledgeImportService( public void Add(string? name, int storyAssetId, string assetName) { var key = Clean(name); - if (string.IsNullOrWhiteSpace(key) || byName.ContainsKey(key)) + if (string.IsNullOrWhiteSpace(key)) { return; } @@ -807,6 +828,6 @@ public sealed class StoryIntelligenceKnowledgeImportService( } } - private sealed record CharacterMatch(int CharacterID, string CharacterName); + private sealed record CharacterMatch(int CharacterID, string CharacterName, bool Ambiguous = false); private sealed record AssetMatch(int StoryAssetID, string AssetName); } diff --git a/PlotLine/Services/StoryIntelligenceRelationshipImportService.cs b/PlotLine/Services/StoryIntelligenceRelationshipImportService.cs index 1897c946..a1623350 100644 --- a/PlotLine/Services/StoryIntelligenceRelationshipImportService.cs +++ b/PlotLine/Services/StoryIntelligenceRelationshipImportService.cs @@ -59,9 +59,15 @@ public sealed class StoryIntelligenceRelationshipImportService( Candidates = visibleCandidates.Select(candidate => new StoryIntelligenceRelationshipReviewCandidateViewModel { Key = candidate.Key, + CharacterAID = candidate.CharacterAID, CharacterBID = candidate.CharacterBID, + RawConfidence = candidate.Confidence, AmbiguousIdentity = candidate.AmbiguousIdentity, + Observations = candidate.Appearances.Select(a => new StoryIntelligenceObservationEvidence + { SceneID=a.SceneID, ChapterNumber=a.ChapterNumber, SceneNumber=a.SceneNumber, SortOrder=a.SortOrder, Signal=a.Signal, Evidence=a.Evidence, Confidence=a.Confidence }).ToList(), ReviewRulesVersion = 3, ProposalKind = candidate.ProposalKind, RelationshipState = candidate.RelationshipState, + HasExplicitState = lookupData.RelationshipStates.Any(x => string.Equals(x.StateName, candidate.RelationshipState, StringComparison.OrdinalIgnoreCase)), + HasExplicitType = lookupData.RelationshipTypes.Any(x => string.Equals(x.TypeName, candidate.RelationshipType, StringComparison.OrdinalIgnoreCase)), RelationshipStateID = MatchRelationshipState(lookupData.RelationshipStates, candidate.RelationshipState), IsReciprocal = candidate.IsReciprocal, IsKnownToOtherCharacter = candidate.IsKnownToOtherCharacter, @@ -294,6 +300,7 @@ public sealed class StoryIntelligenceRelationshipImportService( characterB.CharacterID, characterB.CharacterName, type, existing?.CharacterRelationshipID, existing is null ? null : $"{existing.CharacterAName} / {existing.RelationshipTypeName} / {existing.CharacterBName}") { + AmbiguousIdentity = characterA.Ambiguous || characterB.Ambiguous, ProposalKind = kind, RelationshipState = state, IsReciprocal = reciprocal, IsKnownToOtherCharacter = proposal?.IsKnownToOtherCharacter ?? false, Intensity = proposal?.Intensity is >= 1 and <= 10 ? proposal.Intensity : null, @@ -799,6 +806,7 @@ public sealed class StoryIntelligenceRelationshipImportService( int? existingRelationshipId, string? existingRelationshipLabel) { + public bool AmbiguousIdentity { get; init; } public string ProposalKind { get; init; } = "Development"; public string RelationshipState { get; init; } = "Unknown"; public bool IsReciprocal { get; init; } @@ -841,11 +849,16 @@ public sealed class StoryIntelligenceRelationshipImportService( public void Add(string? name, int characterId, string characterName) { var key = Clean(name); - if (string.IsNullOrWhiteSpace(key) || byName.ContainsKey(key)) + if (string.IsNullOrWhiteSpace(key)) { return; } + if (byName.TryGetValue(key, out var previous)) + { + if (previous.CharacterID != characterId) byName[key] = previous with { Ambiguous = true }; + return; + } byName[key] = new CharacterMatch(characterId, characterName); } @@ -911,5 +924,5 @@ public sealed class StoryIntelligenceRelationshipImportService( _ => 0 }; - private sealed record CharacterMatch(int CharacterID, string CharacterName); + private sealed record CharacterMatch(int CharacterID, string CharacterName, bool Ambiguous = false); } diff --git a/PlotLine/Services/StoryIntelligenceReviewCandidateService.cs b/PlotLine/Services/StoryIntelligenceReviewCandidateService.cs index bb66e836..b7b4b553 100644 --- a/PlotLine/Services/StoryIntelligenceReviewCandidateService.cs +++ b/PlotLine/Services/StoryIntelligenceReviewCandidateService.cs @@ -13,9 +13,9 @@ public interface IStoryIntelligenceReviewCandidateService Task PreparePeerCandidatesAsync(OnboardingStoryIntelligenceBatch batch); Task GetCharacterReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize); Task GetLocationReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string scope = "significant"); - Task GetAssetReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize); - Task GetRelationshipReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize); - Task GetKnowledgeReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize); + Task GetAssetReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string? candidateKey = null); + Task GetRelationshipReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string? candidateKey = null); + Task GetKnowledgeReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string? candidateKey = null); Task MarkCharacterDecisionsAsync(int bookId, IEnumerable choices); Task MarkLocationDecisionsAsync(int bookId, IEnumerable choices); Task MarkAssetDecisionsAsync(int bookId, IEnumerable choices); @@ -35,7 +35,8 @@ public sealed class StoryIntelligenceReviewCandidateService( ILocationRepository locations, IAssetRepository assets, IStoryIntelligencePipelineStateService pipelineState, - ILogger logger) : IStoryIntelligenceReviewCandidateService + ILogger logger, + IStoryIntelligenceExceptionReviewService? exceptionReview = null) : IStoryIntelligenceReviewCandidateService { private const int MaxPageSize = 100; private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); @@ -238,9 +239,9 @@ public sealed class StoryIntelligenceReviewCandidateService( }; } - public async Task GetAssetReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize) + public async Task GetAssetReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string? candidateKey = null) { - var page = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Assets, pageNumber, pageSize); + var page = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Assets, pageNumber, pageSize, candidateKey); var allPendingPage = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Assets, 1, MaxPageSize); var projectAssets = (await assets.ListAssetsAsync(batch.ProjectID)).ToList(); var targetOptions = await BuildAssetTargetOptionsAsync(projectAssets, allPendingPage.Items); @@ -249,7 +250,7 @@ public sealed class StoryIntelligenceReviewCandidateService( HasCommittedScenes = true, CanImport = page.Items.Count > 0, IsComplete = page.GenerationReady && page.PendingCount == 0, - SummaryNeedsAttentionCount = page.PendingCount, + SummaryNeedsAttentionCount = exceptionReview is null ? null : (await exceptionReview.SummaryAsync(batch.BookID)).FirstOrDefault(x => x.Module == StoryIntelligenceReviewModules.Assets)?.AttentionCount, PageNumber = page.PageNumber, PageSize = page.PageSize, TotalCandidateCount = page.TotalCount, @@ -259,16 +260,16 @@ public sealed class StoryIntelligenceReviewCandidateService( }; } - public async Task GetRelationshipReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize) + public async Task GetRelationshipReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string? candidateKey = null) { var lookupData = await characters.GetLookupsAsync(batch.ProjectID); - var page = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Relationships, pageNumber, pageSize); + var page = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Relationships, pageNumber, pageSize, candidateKey); return new StoryIntelligenceRelationshipReviewViewModel { HasCommittedScenes = true, CanImport = page.Items.Count > 0, IsComplete = page.GenerationReady && page.PendingCount == 0, - SummaryNeedsAttentionCount = page.PendingCount, + SummaryNeedsAttentionCount = exceptionReview is null ? null : (await exceptionReview.SummaryAsync(batch.BookID)).FirstOrDefault(x => x.Module == StoryIntelligenceReviewModules.Relationships)?.AttentionCount, PageNumber = page.PageNumber, PageSize = page.PageSize, TotalCandidateCount = page.TotalCount, @@ -283,16 +284,16 @@ public sealed class StoryIntelligenceReviewCandidateService( }; } - public async Task GetKnowledgeReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize) + public async Task GetKnowledgeReviewAsync(OnboardingStoryIntelligenceBatch batch, int pageNumber, int pageSize, string? candidateKey = null) { var lookupData = await characters.GetLookupsAsync(batch.ProjectID); - var page = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Knowledge, pageNumber, pageSize); + var page = await LoadPageAsync(batch.BookID, StoryIntelligenceReviewModules.Knowledge, pageNumber, pageSize, candidateKey); return new StoryIntelligenceKnowledgeReviewViewModel { HasCommittedScenes = true, CanImport = page.Items.Count > 0, IsComplete = page.GenerationReady && page.PendingCount == 0, - SummaryNeedsAttentionCount = page.PendingCount, + SummaryNeedsAttentionCount = exceptionReview is null ? null : (await exceptionReview.SummaryAsync(batch.BookID)).FirstOrDefault(x => x.Module == StoryIntelligenceReviewModules.Knowledge)?.AttentionCount, PageNumber = page.PageNumber, PageSize = page.PageSize, TotalCandidateCount = page.TotalCount, @@ -528,7 +529,7 @@ public sealed class StoryIntelligenceReviewCandidateService( StableKey = choice.Key, DecisionAction = choice.Action, DecisionTargetKey = choice.AliasTargetKey, - DecisionCanonicalID = choice.KnowledgeStateID + DecisionCanonicalID = choice.AcceptedKnowledgeID }); } @@ -562,12 +563,33 @@ public sealed class StoryIntelligenceReviewCandidateService( CandidateType = candidateType(candidate), DisplayName = displayName(candidate), SortOrder = sortOrder, + Confidence = candidate switch + { + StoryIntelligenceKnowledgeReviewCandidateViewModel knowledge => knowledge.RawConfidence, + StoryIntelligenceRelationshipReviewCandidateViewModel relationship => relationship.RawConfidence, + _ => null + }, ExistingCanonicalID = existingCanonicalId(candidate), CandidatePayloadJson = JsonSerializer.Serialize(candidate, JsonOptions) }); + if (row.DecisionStatus is "Reviewed" or "AutoAccepted") continue; + + var observations = candidate switch + { + StoryIntelligenceKnowledgeReviewCandidateViewModel knowledge => knowledge.Observations, + StoryIntelligenceRelationshipReviewCandidateViewModel relationship => relationship.Observations, + _ => (IReadOnlyList)[] + }; var evidenceOrder = 0; - foreach (var item in evidence(candidate).Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.OrdinalIgnoreCase).Take(5)) + foreach (var observation in observations) + { + var evidenceText = observation.Evidence; + if (string.IsNullOrWhiteSpace(evidenceText)) continue; + await candidates.SaveEvidenceAsync(row.ReviewCandidateID, observation.SceneID, + evidenceText[..Math.Min(1000, evidenceText.Length)], observation.Confidence, ++evidenceOrder); + } + foreach (var item in (observations.Count > 0 ? [] : evidence(candidate)).Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.OrdinalIgnoreCase).Take(5)) { evidenceOrder++; await candidates.SaveEvidenceAsync(row.ReviewCandidateID, null, item!, null, evidenceOrder); @@ -575,6 +597,11 @@ public sealed class StoryIntelligenceReviewCandidateService( } var completedGeneration = await candidates.CompleteGenerationAsync(generation.ReviewCandidateGenerationID); + if (exceptionReview is not null) + { + await exceptionReview.AssessPreparedAsync(batch.BookID, module); + completedGeneration = await candidates.GetCurrentGenerationAsync(batch.BookID, module); + } await CompleteModuleIfReadyAsync(batch, module, completedGeneration); logger.LogInformation( "Prepared persisted Story Intelligence review candidates. BatchID={BatchID} ProjectID={ProjectID} BookID={BookID} Module={Module} Count={Count}", @@ -635,7 +662,7 @@ public sealed class StoryIntelligenceReviewCandidateService( return 0; } - private async Task> LoadPageAsync(int bookId, string module, int pageNumber, int pageSize) + private async Task> LoadPageAsync(int bookId, string module, int pageNumber, int pageSize, string? candidateKey = null) { pageNumber = Math.Max(1, pageNumber); pageSize = Math.Clamp(pageSize <= 0 ? 25 : pageSize, 1, MaxPageSize); @@ -646,6 +673,12 @@ public sealed class StoryIntelligenceReviewCandidateService( return new CandidatePage([], pageNumber, pageSize, 0, 0, false); } + if (!string.IsNullOrWhiteSpace(candidateKey)) + { + var selected = (await candidates.ListAllAsync(bookId, module)).Where(x => x.DecisionStatus == "Pending" && x.StableKey == candidateKey) + .Select(x => JsonSerializer.Deserialize(x.CandidatePayloadJson, JsonOptions)!).ToList(); + return new CandidatePage(selected, 1, pageSize, generation.CandidateCount, selected.Count, true); + } var maxPage = generation.PendingCount <= 0 ? 1 : (int)Math.Ceiling(generation.PendingCount / (double)pageSize); diff --git a/PlotLine/Services/StoryIntelligenceReviewPolicy.cs b/PlotLine/Services/StoryIntelligenceReviewPolicy.cs new file mode 100644 index 00000000..7ae03571 --- /dev/null +++ b/PlotLine/Services/StoryIntelligenceReviewPolicy.cs @@ -0,0 +1,89 @@ +using System.Text.RegularExpressions; +using PlotLine.Models; +using PlotLine.ViewModels; + +namespace PlotLine.Services; + +/// Deterministic assessment of saved evidence, never an AI request or a confidence-only filter. +public static class StoryIntelligenceReviewPolicy +{ + // Matches the existing extraction UI's High band. Evidence and identity gates are also mandatory. + public const decimal HighConfidence = .75m; + private static string Normalise(string? value) => Regex.Replace(value?.ToLowerInvariant() ?? "", @"[^\p{L}\p{N}]+", " ").Trim(); + private static bool Consequential(string? text) => Regex.IsMatch(text ?? "", + @"\b(betray\w*|murder\w*|kill\w*|confess\w*|blackmail\w*|expos\w*|revelation|secret identity|divorc\w*|break.?up|rescu\w*|threat\w*)\b", RegexOptions.IgnoreCase); + private static bool Supported(IReadOnlyList observations) => observations.Count > 0 + && observations.All(x => x.SceneID > 0 && x.Confidence >= HighConfidence && x.Confidence <= 1m && !string.IsNullOrWhiteSpace(x.Evidence)); + private static StoryIntelligenceReviewAssessment Result(string priority, params string[] reasons) => new(priority, reasons); + + public static StoryIntelligenceReviewAssessment Knowledge(StoryIntelligenceKnowledgeReviewCandidateViewModel item, + IReadOnlyList context) + { + var significant = Consequential(item.KnowledgeStatement + " " + item.Evidence); + if (item.AmbiguousIdentity) + return Result(StoryIntelligenceReviewAssessment.Attention, "More than one character shares this name or alias. Confirm the identity before using this knowledge."); + var conflicting = context.Any(other => other.Key != item.Key && other.CharacterID == item.CharacterID + && Normalise(other.KnowledgeStatement) == Normalise(item.KnowledgeStatement) + && other.KnowledgeStateName != item.KnowledgeStateName + && other.Observations.Any(a => item.Observations.Any(b => a.SceneID == b.SceneID)) + && (other.KnowledgeStateName == "Unaware" || item.KnowledgeStateName == "Unaware")); + if (conflicting) + return Result(StoryIntelligenceReviewAssessment.Attention, "The same scene suggests both awareness and lack of awareness of this fact. Check the order of events."); + // Beliefs, hearsay and inference stay explicitly different from established knowledge. + var subjective = item.KnowledgeStateName is "Suspects" or "Misunderstands" or "Partially Knows" + || item.Observations.Any(x => Regex.IsMatch(x.Signal ?? "", "told|infer|believ|suspect|misunderstand", RegexOptions.IgnoreCase)); + if (significant && (subjective || !Supported(item.Observations))) + return Result(StoryIntelligenceReviewAssessment.Attention, "This consequential information depends on an uncertain knowledge state or incomplete evidence."); + if (subjective) + return Result(StoryIntelligenceReviewAssessment.Optional, "A belief, suspicion or reported fact may benefit from your interpretation; it is not treated as established knowledge."); + if (item.CharacterID > 0 && item.KnowledgeStateID > 0 && Supported(item.Observations) + && item.Observations.All(x => Regex.IsMatch(x.Signal ?? "", "^(Learns|Realises|Realizes|Discovers|Confirms|Knows)$", RegexOptions.IgnoreCase))) + return Result(StoryIntelligenceReviewAssessment.Tracked, "A resolved character and explicit scene evidence support this knowledge state."); + return Result(StoryIntelligenceReviewAssessment.Optional, "The saved evidence does not establish enough detail for automatic acceptance. Review when useful."); + } + + private static string Track(StoryIntelligenceRelationshipReviewCandidateViewModel x) => x.IsReciprocal + ? $"{Math.Min(x.CharacterAID, x.CharacterBID)}:{Math.Max(x.CharacterAID, x.CharacterBID)}:mutual:{x.RelationshipType}" + : $"{x.CharacterAID}>{x.CharacterBID}:{x.RelationshipType}"; + private static int Polarity(string state) => Normalise(state) switch + { + "friendly" or "trusting" or "close" or "romantic" or "deep attachment" => 1, + "hostile" or "enemy" or "enemies" or "distrustful" => -1, + _ => 0 + }; + public static StoryIntelligenceReviewAssessment Relationship(StoryIntelligenceRelationshipReviewCandidateViewModel item, + IReadOnlyList context) + { + if (item.AmbiguousIdentity) + return Result(StoryIntelligenceReviewAssessment.Attention, "More than one character shares a participant's name or alias. Confirm who is involved."); + var significant = Consequential(item.Development + " " + item.ExampleContext) || item.ProposalKind == "Factual"; + if (item.NeedsDirectionReview) + return Result(significant ? StoryIntelligenceReviewAssessment.Attention : StoryIntelligenceReviewAssessment.Optional, + "The saved analysis does not establish direction or whether this feeling is mutual."); + var track = context.Where(x => Track(x) == Track(item)).OrderBy(x => x.FirstChapterNumber) + .ThenBy(x => x.FirstSceneNumber).ThenBy(x => x.FirstSceneID).ToList(); + if (track.Any(x => x.Key != item.Key && x.FirstSceneID == item.FirstSceneID + && Polarity(x.RelationshipState) * Polarity(item.RelationshipState) == -1)) + return Result(StoryIntelligenceReviewAssessment.Attention, "This scene contains opposing interpretations of the same directional relationship."); + var index = track.FindIndex(x => x.Key == item.Key); + if (index > 0 && index < track.Count - 1 + && Polarity(track[index - 1].RelationshipState) == Polarity(track[index + 1].RelationshipState) + && Polarity(item.RelationshipState) * Polarity(track[index - 1].RelationshipState) == -1 + && !Consequential(item.Development + " " + item.ExampleContext) && !Supported(item.Observations)) + return Result(StoryIntelligenceReviewAssessment.Attention, "An opposing state between surrounding observations has weak support. Check the transition in context."); + if (significant && !Supported(item.Observations)) + return Result(StoryIntelligenceReviewAssessment.Attention, "A major development or factual tie has incomplete supporting evidence."); + if (item.CharacterAID > 0 && item.CharacterBID > 0 && item.CharacterAID != item.CharacterBID + && item.RelationshipStateID > 0 && item.RelationshipTypeID > 0 && item.FirstSceneID > 0 + && !string.IsNullOrWhiteSpace(item.Development) && Supported(item.Observations) + && item.HasExplicitType + && (item.ProposalKind == "Factual" || (item.HasExplicitState && !string.Equals(item.RelationshipState, "Unknown", StringComparison.OrdinalIgnoreCase)))) + return Result(StoryIntelligenceReviewAssessment.Tracked, "Scene evidence supports the identified participants, direction and relationship state."); + return Result(StoryIntelligenceReviewAssessment.Optional, "The interpretation or supporting detail is uncertain. Review if useful to your story."); + } + + public static StoryIntelligenceReviewAssessment Asset(StoryIntelligenceAssetReviewCandidateViewModel item) + => Result(Consequential(item.ExampleContext) && item.Confidence != "High" + ? StoryIntelligenceReviewAssessment.Attention : StoryIntelligenceReviewAssessment.Optional, + "Existing exact matches are linked automatically. Confirm a new asset's identity or ownership when it matters to the story."); +} diff --git a/PlotLine/Sql/200_StoryIntelligenceExceptionReview.sql b/PlotLine/Sql/200_StoryIntelligenceExceptionReview.sql new file mode 100644 index 00000000..cc844a4b --- /dev/null +++ b/PlotLine/Sql/200_StoryIntelligenceExceptionReview.sql @@ -0,0 +1,246 @@ +-- Review priority is independent from author decisions. Existing data starts unassessed. +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +SET XACT_ABORT ON; +GO +IF COL_LENGTH('dbo.StoryIntelligenceReviewCandidates','ReviewPriority') IS NULL + ALTER TABLE dbo.StoryIntelligenceReviewCandidates ADD ReviewPriority nvarchar(20) NOT NULL CONSTRAINT DF_ReviewCandidate_Priority DEFAULT N'Unassessed', + AssessmentJson nvarchar(max) NULL; +GO +IF COL_LENGTH('dbo.CharacterKnowledge','SourceReviewKey') IS NULL + ALTER TABLE dbo.CharacterKnowledge ADD SourceReviewKey nvarchar(450) NULL; +GO +IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.CharacterKnowledge') AND name='UX_CharacterKnowledge_ReviewSource') + CREATE UNIQUE INDEX UX_CharacterKnowledge_ReviewSource ON dbo.CharacterKnowledge(SceneID,SourceReviewKey) WHERE SourceReviewKey IS NOT NULL; +GO +-- Preserve normal author editing. Imports are insert-once, including retries after interrupted requests. +CREATE OR ALTER PROCEDURE dbo.CharacterKnowledge_Save + @CharacterKnowledgeID int=NULL,@CharacterID int,@StoryAssetID int=NULL,@PlotThreadID int=NULL, + @SceneID int,@KnowledgeStateID int,@SourceEventID int=NULL,@Description nvarchar(max)=NULL,@SourceReviewKey nvarchar(450)=NULL +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + IF ISNULL(@CharacterKnowledgeID,0)=0 + BEGIN + IF @SourceReviewKey IS NOT NULL + SELECT @CharacterKnowledgeID=CharacterKnowledgeID FROM dbo.CharacterKnowledge WITH(UPDLOCK,HOLDLOCK) + WHERE SceneID=@SceneID AND SourceReviewKey=@SourceReviewKey; + IF ISNULL(@CharacterKnowledgeID,0)=0 + BEGIN + INSERT dbo.CharacterKnowledge(CharacterID,StoryAssetID,PlotThreadID,SceneID,KnowledgeStateID,SourceEventID,Description,SourceReviewKey) + VALUES(@CharacterID,@StoryAssetID,@PlotThreadID,@SceneID,@KnowledgeStateID,@SourceEventID,@Description,@SourceReviewKey); + SET @CharacterKnowledgeID=CONVERT(int,SCOPE_IDENTITY()); + END; + END + ELSE + UPDATE dbo.CharacterKnowledge SET CharacterID=@CharacterID,StoryAssetID=@StoryAssetID,PlotThreadID=@PlotThreadID, + SceneID=@SceneID,KnowledgeStateID=@KnowledgeStateID,SourceEventID=@SourceEventID,Description=@Description,UpdatedDate=SYSUTCDATETIME() + WHERE CharacterKnowledgeID=@CharacterKnowledgeID; + COMMIT; + SELECT @CharacterKnowledgeID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReview_List @BookID int,@Module nvarchar(40) +AS +BEGIN + SET NOCOUNT ON; + SELECT c.* FROM dbo.StoryIntelligenceReviewCandidates c + JOIN dbo.StoryIntelligenceReviewCandidateGenerations g ON g.ReviewCandidateGenerationID=c.ReviewCandidateGenerationID + WHERE g.BookID=@BookID AND g.Module=@Module AND g.IsCurrent=1 AND g.Status=N'Ready' + ORDER BY c.SortOrder,c.ReviewCandidateID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReview_Summary @BookID int +AS +BEGIN + SET NOCOUNT ON; + SELECT g.Module,COUNT(c.ReviewCandidateID) IdentifiedCount, + SUM(CASE WHEN c.DecisionStatus=N'AutoAccepted' OR (c.DecisionStatus=N'Reviewed' AND c.DecisionAction IN(N'CreateNew',N'LinkExisting',N'Alias')) THEN 1 ELSE 0 END) TrackedCount, + SUM(CASE WHEN c.DecisionStatus=N'Pending' AND c.ReviewPriority=N'Optional' THEN 1 ELSE 0 END) OptionalCount, + SUM(CASE WHEN c.DecisionStatus=N'Pending' AND c.ReviewPriority=N'Attention' THEN 1 ELSE 0 END) AttentionCount, + SUM(CASE WHEN c.DecisionStatus=N'Pending' AND c.ReviewPriority=N'Unassessed' THEN 1 ELSE 0 END) UnassessedCount, + SUM(CASE WHEN c.DecisionStatus=N'Reviewed' THEN 1 ELSE 0 END) DecidedCount, + COUNT(DISTINCT CASE WHEN g.Module=N'Relationships' THEN + CASE WHEN TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterAID'))>0 AND TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterBID'))>0 + THEN CASE WHEN TRY_CONVERT(int,JSON_VALUE(c.CandidatePayloadJson,'$.characterAID'))@Key THROW 53201,'Review identity changed.',1; + -- Rebuilding a generation must not overturn an earlier author decision, even after batch resume. + DECLARE @PreviousID int; + SELECT TOP(1) @PreviousID=ReviewCandidateID FROM dbo.StoryIntelligenceReviewCandidates + WHERE BookID=@BookID AND Module=@Module AND DecisionStatus<>N'Pending' AND ReviewCandidateID<>@ReviewCandidateID + AND (StableKey=@Key OR (@Module=N'Relationships' AND DecisionStatus=N'Reviewed' + AND ISNULL(TRY_CONVERT(int,JSON_VALUE(CandidatePayloadJson,'$.reviewRulesVersion')),0)<3 + AND ((JSON_VALUE(CandidatePayloadJson,'$.characterAName')=JSON_VALUE(@PayloadJson,'$.characterAName') AND JSON_VALUE(CandidatePayloadJson,'$.characterBName')=JSON_VALUE(@PayloadJson,'$.characterBName')) + OR (JSON_VALUE(CandidatePayloadJson,'$.characterAName')=JSON_VALUE(@PayloadJson,'$.characterBName') AND JSON_VALUE(CandidatePayloadJson,'$.characterBName')=JSON_VALUE(@PayloadJson,'$.characterAName'))))) + ORDER BY CASE WHEN DecisionStatus=N'Reviewed' THEN 0 ELSE 1 END,ReviewCandidateID DESC; + IF @PreviousID IS NOT NULL + BEGIN + UPDATE c SET DecisionStatus=p.DecisionStatus,DecisionAction=p.DecisionAction,DecisionTargetKey=p.DecisionTargetKey, + DecisionCanonicalID=p.DecisionCanonicalID,ReviewedUtc=p.ReviewedUtc,ReviewPriority=p.ReviewPriority,AssessmentJson=p.AssessmentJson + FROM dbo.StoryIntelligenceReviewCandidates c JOIN dbo.StoryIntelligenceReviewCandidates p ON p.ReviewCandidateID=@PreviousID + WHERE c.ReviewCandidateID=@ReviewCandidateID; + END + ELSE + BEGIN + DECLARE @CanonicalID int,@SceneID int,@CharacterID int,@StateID int,@AssetID int,@Description nvarchar(max); + DECLARE @Results TABLE(ID int); + IF @Priority=N'Tracked' + BEGIN + IF @Module=N'Knowledge' + BEGIN + SELECT TOP(1) @SceneID=TRY_CONVERT(int,JSON_VALUE(value,'$.sceneID')) FROM OPENJSON(@PayloadJson,'$.observations') + ORDER BY TRY_CONVERT(decimal(18,4),JSON_VALUE(value,'$.chapterNumber')),TRY_CONVERT(decimal(18,4),JSON_VALUE(value,'$.sceneNumber')),TRY_CONVERT(int,JSON_VALUE(value,'$.sortOrder')); + SET @CharacterID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.characterID')); + SET @StateID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.knowledgeStateID')); + SET @AssetID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.storyAssetID')); + SET @CanonicalID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.existingKnowledgeID')); + IF NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE s.SceneID=@SceneID AND ch.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND s.IsArchived=0 AND ch.IsArchived=0) + OR NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@CharacterID AND ProjectID=@ProjectID AND IsArchived=0) + THROW 53202,'Knowledge scope changed.',1; + IF @AssetID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.StoryAssets WHERE StoryAssetID=@AssetID AND ProjectID=@ProjectID AND IsArchived=0) + THROW 53203,'Knowledge asset scope changed.',1; + IF @CanonicalID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge WHERE CharacterKnowledgeID=@CanonicalID AND CharacterID=@CharacterID AND KnowledgeStateID=@StateID AND SceneID=@SceneID) + SET @CanonicalID=NULL; + IF @CanonicalID IS NULL + BEGIN + SELECT @Description=CONCAT(statement,CHAR(10),N'Evidence: ',evidence) FROM OPENJSON(@PayloadJson) + WITH(statement nvarchar(max) '$.knowledgeStatement',evidence nvarchar(max) '$.evidence'); + INSERT @Results EXEC dbo.CharacterKnowledge_Save @CharacterID=@CharacterID,@StoryAssetID=@AssetID,@SceneID=@SceneID,@KnowledgeStateID=@StateID,@Description=@Description,@SourceReviewKey=@Key; + SELECT @CanonicalID=ID FROM @Results; + END; + END + ELSE IF @Module=N'Relationships' + BEGIN + DECLARE @A int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.characterAID')),@B int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.characterBID')), + @TypeID int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.relationshipTypeID')), + @Permanent bit=CASE WHEN JSON_VALUE(@PayloadJson,'$.proposalKind')=N'Factual' THEN 1 ELSE 0 END, + @Reciprocal bit=CASE WHEN JSON_VALUE(@PayloadJson,'$.isReciprocal')=N'true' THEN 1 ELSE 0 END, + @Known bit=CASE WHEN JSON_VALUE(@PayloadJson,'$.isKnownToOtherCharacter')=N'true' THEN 1 ELSE 0 END, + @Intensity int=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.intensity')); + SET @SceneID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.firstSceneID')); + SET @StateID=TRY_CONVERT(int,JSON_VALUE(@PayloadJson,'$.relationshipStateID')); + SELECT @Description=development FROM OPENJSON(@PayloadJson) WITH(development nvarchar(max) '$.development'); + INSERT @Results EXEC dbo.StoryIntelligenceRelationship_AcceptDevelopment @ProjectID=@ProjectID,@BookID=@BookID,@SceneID=@SceneID,@SourceReviewKey=@Key, + @CharacterAID=@A,@CharacterBID=@B,@RelationshipTypeID=@TypeID,@RelationshipStateID=@StateID,@IsPermanent=@Permanent, + @IsReciprocal=@Reciprocal,@IsKnownToOtherCharacter=@Known,@Intensity=@Intensity,@Description=@Description; + SELECT @CanonicalID=ID FROM @Results; + END + ELSE THROW 53204,'Automatic creation is not supported for this module.',1; + IF @CanonicalID IS NULL THROW 53205,'Automatic acceptance did not return a canonical record.',1; + END; + UPDATE dbo.StoryIntelligenceReviewCandidates SET CandidatePayloadJson=@PayloadJson,AssessmentJson=@AssessmentJson,ReviewPriority=@Priority, + Confidence=TRY_CONVERT(decimal(9,6),JSON_VALUE(@PayloadJson,'$.rawConfidence')), + DecisionStatus=CASE WHEN @CanonicalID IS NOT NULL THEN N'AutoAccepted' ELSE DecisionStatus END, + DecisionAction=CASE WHEN @CanonicalID IS NOT NULL THEN N'CreateNew' ELSE DecisionAction END, + DecisionCanonicalID=COALESCE(@CanonicalID,DecisionCanonicalID),UpdatedUtc=SYSUTCDATETIME() + WHERE ReviewCandidateID=@ReviewCandidateID; + END; + UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET PendingCount=(SELECT COUNT(*) FROM dbo.StoryIntelligenceReviewCandidates + WHERE ReviewCandidateGenerationID=@ExpectedGenerationID AND DecisionStatus=N'Pending'),UpdatedUtc=SYSUTCDATETIME() + WHERE ReviewCandidateGenerationID=@ExpectedGenerationID; + COMMIT; +END; +GO + +-- Carry settled observations into new preparation generations so history and decisions stay visible. +CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReviewCandidateGeneration_Begin + @ProjectID int,@BookID int,@Module nvarchar(40),@Source nvarchar(80)=N'SceneIntelligencePreparation' +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRANSACTION; + DECLARE @Previous int,@Generation int; + SELECT @Previous=ReviewCandidateGenerationID FROM dbo.StoryIntelligenceReviewCandidateGenerations WITH(UPDLOCK,HOLDLOCK) + WHERE BookID=@BookID AND Module=@Module AND IsCurrent=1; + UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET IsCurrent=0,UpdatedUtc=SYSUTCDATETIME() WHERE ReviewCandidateGenerationID=@Previous; + INSERT dbo.StoryIntelligenceReviewCandidateGenerations(ProjectID,BookID,Module,Status,Source) VALUES(@ProjectID,@BookID,@Module,N'Preparing',@Source); + SET @Generation=CONVERT(int,SCOPE_IDENTITY()); + IF @Module IN(N'Knowledge',N'Relationships',N'Assets') + BEGIN + INSERT dbo.StoryIntelligenceReviewCandidates(ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,CandidateType,DisplayName,SortOrder,Confidence, + ExistingCanonicalID,DecisionStatus,DecisionAction,DecisionTargetKey,DecisionCanonicalID,CandidatePayloadJson,ReviewedUtc,ReviewPriority,AssessmentJson) + SELECT @Generation,ProjectID,BookID,Module,StableKey,CandidateType,DisplayName,SortOrder,Confidence, + ExistingCanonicalID,DecisionStatus,DecisionAction,DecisionTargetKey,DecisionCanonicalID,CandidatePayloadJson,ReviewedUtc,ReviewPriority,AssessmentJson + FROM dbo.StoryIntelligenceReviewCandidates WHERE ReviewCandidateGenerationID=@Previous AND DecisionStatus<>N'Pending'; + INSERT dbo.StoryIntelligenceReviewCandidateEvidence(ReviewCandidateID,SceneID,EvidenceText,Confidence,SortOrder) + SELECT newRow.ReviewCandidateID,e.SceneID,e.EvidenceText,e.Confidence,e.SortOrder + FROM dbo.StoryIntelligenceReviewCandidateEvidence e JOIN dbo.StoryIntelligenceReviewCandidates oldRow ON oldRow.ReviewCandidateID=e.ReviewCandidateID + JOIN dbo.StoryIntelligenceReviewCandidates newRow ON newRow.ReviewCandidateGenerationID=@Generation AND newRow.StableKey=oldRow.StableKey + WHERE oldRow.ReviewCandidateGenerationID=@Previous; + END; + COMMIT; + SELECT * FROM dbo.StoryIntelligenceReviewCandidateGenerations WHERE ReviewCandidateGenerationID=@Generation; +END; +GO +CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceReviewCandidate_Save + @ReviewCandidateGenerationID int, + @ProjectID int, + @BookID int, + @Module nvarchar(40), + @StableKey nvarchar(450), + @CandidateType nvarchar(80) = NULL, + @DisplayName nvarchar(450), + @SortOrder int, + @Confidence decimal(9,4) = NULL, + @ExistingCanonicalID int = NULL, + @CandidatePayloadJson nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + + MERGE dbo.StoryIntelligenceReviewCandidates AS target + USING (SELECT @ReviewCandidateGenerationID AS ReviewCandidateGenerationID, @StableKey AS StableKey) AS source + ON target.ReviewCandidateGenerationID = source.ReviewCandidateGenerationID + AND target.StableKey = source.StableKey + WHEN MATCHED AND (target.Module NOT IN(N'Knowledge',N'Relationships',N'Assets') OR target.DecisionStatus=N'Pending') THEN + UPDATE SET CandidateType = @CandidateType, + DisplayName = @DisplayName, + SortOrder = @SortOrder, + Confidence = @Confidence, + ExistingCanonicalID = @ExistingCanonicalID, + CandidatePayloadJson = @CandidatePayloadJson, + UpdatedUtc = SYSUTCDATETIME() + WHEN NOT MATCHED THEN + INSERT (ReviewCandidateGenerationID, ProjectID, BookID, Module, StableKey, CandidateType, DisplayName, SortOrder, Confidence, ExistingCanonicalID, CandidatePayloadJson) + VALUES (@ReviewCandidateGenerationID, @ProjectID, @BookID, @Module, @StableKey, @CandidateType, @DisplayName, @SortOrder, @Confidence, @ExistingCanonicalID, @CandidatePayloadJson); + + SELECT * + FROM dbo.StoryIntelligenceReviewCandidates + WHERE ReviewCandidateGenerationID = @ReviewCandidateGenerationID + AND StableKey = @StableKey; +END; +GO + diff --git a/PlotLine/ViewModels/OnboardingViewModels.cs b/PlotLine/ViewModels/OnboardingViewModels.cs index ee653e62..98f45fb0 100644 --- a/PlotLine/ViewModels/OnboardingViewModels.cs +++ b/PlotLine/ViewModels/OnboardingViewModels.cs @@ -160,6 +160,7 @@ public sealed class StoryIntelligenceAuthorPlotContextForm public sealed class StoryIntelligenceProgressViewModel { + public IReadOnlyList ReviewSummaries { get; set; } = []; public StoryIntelligenceJobProgress Job { get; init; } = new(); public Guid? BatchID { get; init; } public Guid? PreviewID { get; init; } @@ -669,6 +670,14 @@ public sealed class StoryIntelligenceRelationshipReviewViewModel public sealed class StoryIntelligenceRelationshipReviewCandidateViewModel { + public bool HasExplicitState { get; init; } + public bool HasExplicitType { get; init; } + public int CharacterAID { get; init; } + public int CharacterBID { get; init; } + public decimal? RawConfidence { get; init; } + public bool AmbiguousIdentity { get; init; } + public IReadOnlyList Observations { get; init; } = []; + public string ProposalKind { get; init; } = "Development"; public string RelationshipState { get; init; } = "Unknown"; public int RelationshipStateID { get; init; } @@ -750,6 +759,12 @@ public sealed class StoryIntelligenceKnowledgeReviewViewModel public sealed class StoryIntelligenceKnowledgeReviewCandidateViewModel { + public int CharacterID { get; init; } + public int? StoryAssetID { get; init; } + public decimal? RawConfidence { get; init; } + public bool AmbiguousIdentity { get; init; } + public IReadOnlyList Observations { get; init; } = []; + public string Key { get; init; } = string.Empty; public string CharacterName { get; init; } = string.Empty; public string KnowledgeStatement { get; init; } = string.Empty; @@ -774,6 +789,8 @@ public sealed class StoryIntelligenceKnowledgeImportForm public sealed class StoryIntelligenceKnowledgeImportChoiceForm { + [Microsoft.AspNetCore.Mvc.ModelBinding.BindNever] + public int? AcceptedKnowledgeID { get; set; } public string Key { get; set; } = string.Empty; public string Action { get; set; } = StoryIntelligenceKnowledgeImportActions.CreateNew; public int? KnowledgeStateID { get; set; } diff --git a/PlotLine/ViewModels/StoryIntelligenceExceptionReviewViewModels.cs b/PlotLine/ViewModels/StoryIntelligenceExceptionReviewViewModels.cs new file mode 100644 index 00000000..f541ce22 --- /dev/null +++ b/PlotLine/ViewModels/StoryIntelligenceExceptionReviewViewModels.cs @@ -0,0 +1,84 @@ +using System.Text.Json; +using PlotLine.Models; +using PlotLine.Services; + +namespace PlotLine.ViewModels; + +public sealed class StoryIntelligenceExceptionReviewViewModel +{ + public Guid? BatchID { get; init; } + public int BookID { get; init; } + public int ProjectID { get; init; } + public string CanonicalController => Module switch { "Knowledge" => "StoryBible", "Relationships" => "RelationshipMap", _ => "StoryAssets" }; + public string Module { get; init; } = ""; + public string Scope { get; init; } = "Attention"; + public StoryIntelligenceReviewSummary Summary { get; init; } = new(); + public int Page { get; init; } + public int PageCount { get; init; } + public IReadOnlyList Items { get; init; } = []; + public IReadOnlyList History { get; init; } = []; +} + +public sealed class StoryIntelligenceReviewEntry +{ + public required StoryIntelligenceReviewCandidateRow Row { get; init; } + public string Pair { get; init; } = ""; + public string PairKey { get; init; } = ""; + public string Direction { get; init; } = ""; + public string Detail { get; init; } = ""; + public IReadOnlyList Observations { get; init; } = []; + public string Evidence { get; init; } = ""; + public string State { get; init; } = ""; + public bool Pending => Row.DecisionStatus == "Pending"; + public StoryIntelligenceReviewAssessment Assessment => string.IsNullOrWhiteSpace(Row.AssessmentJson) + ? new(StoryIntelligenceReviewAssessment.Unassessed, ["This import has not been assessed for review priority. Update priorities using the saved analysis."]) + : JsonSerializer.Deserialize(Row.AssessmentJson, StoryIntelligenceExceptionReviewService.JsonOptions)!; + public string Status => Row.DecisionStatus switch + { + "AutoAccepted" => "Automatically tracked", + "Reviewed" => Row.DecisionAction == "Ignore" ? "Ignored by you" : "Reviewed by you", + _ => Row.ReviewPriority switch { "Attention" => "Needs attention", "Optional" => "Worth reviewing", _ => "Not yet assessed" } + }; + public static StoryIntelligenceReviewEntry From(StoryIntelligenceReviewCandidateRow row) + { + var options = StoryIntelligenceExceptionReviewService.JsonOptions; + if (row.Module == StoryIntelligenceReviewModules.Relationships) + { + var x = JsonSerializer.Deserialize(row.CandidatePayloadJson, options)!; + var pair = new[] { x.CharacterAName, x.CharacterBName }.OrderBy(n => n, StringComparer.OrdinalIgnoreCase); + return new() + { + Row = row, + Pair = string.Join(" / ", pair), + PairKey = x.CharacterAID > 0 && x.CharacterBID > 0 ? $"{Math.Min(x.CharacterAID, x.CharacterBID)}:{Math.Max(x.CharacterAID, x.CharacterBID)}" : string.Join(" / ", pair), + Direction = $"{x.CharacterAName} {(x.IsReciprocal ? "↔" : "→")} {x.CharacterBName}", + Detail = x.Development ?? x.ExampleContext ?? "", + State = x.RelationshipState, + Evidence = x.ExampleContext ?? "", + Observations = x.Observations + }; + } + if (row.Module == StoryIntelligenceReviewModules.Knowledge) + { + var x = JsonSerializer.Deserialize(row.CandidatePayloadJson, options)!; + return new() + { + Row = row, + Detail = $"{x.CharacterName} · {x.KnowledgeStateName}", + State = x.KnowledgeStateName, + Evidence = x.Evidence ?? "", + Observations = x.Observations + }; + } + var a = JsonSerializer.Deserialize(row.CandidatePayloadJson, options)!; + return new() { Row = row, Detail = $"{a.Category} · {a.AppearsInScenes} scenes", Evidence = a.ExampleContext ?? "" }; + } +} + +public sealed class StoryIntelligenceExceptionTileViewModel +{ + public Guid? BatchID { get; init; } + public string Module { get; init; } = ""; + public bool Blocked { get; init; } + public StoryIntelligenceReviewSummary? Summary { get; init; } +} diff --git a/PlotLine/Views/IntelligenceReview/Index.cshtml b/PlotLine/Views/IntelligenceReview/Index.cshtml new file mode 100644 index 00000000..7c7f5714 --- /dev/null +++ b/PlotLine/Views/IntelligenceReview/Index.cshtml @@ -0,0 +1,79 @@ +@model StoryIntelligenceExceptionReviewViewModel +@{ + ViewData["Title"] = Model.Module + " intelligence"; + var editAction = "StoryIntelligence" + Model.Module; +} +
+
+
+

Story Intelligence

+

@Model.Module

+

@Model.Summary.IdentifiedCount observations identified · @Model.Summary.TrackedCount tracked · @Model.Summary.OptionalCount worth reviewing · @Model.Summary.AttentionCount need attention

+

Your manuscript is available to use. Review is optional work you can return to; tracked observations are already available in Story Intelligence.

+ @if (Model.Module == "Relationships") {

Across @Model.Summary.PairCount character pairs. Each scene and direction is preserved in the relationship history.

} +
+ @if (TempData["ReviewMessage"] is string message) {
@message
} + @if (TempData["ReviewError"] is string error) {
@error
} + + @if (Model.Summary.UnassessedCount > 0 || Model.Summary.OptionalCount > 0 || Model.Summary.AttentionCount > 0) + { +
+ +

Update priorities from the saved analysis and automatically accept well-supported observations. No new AI analysis is requested. Your reviewed and ignored decisions stay unchanged.

+ @if (Model.Summary.UnassessedCount > 0) {

@Model.Summary.UnassessedCount observations have not yet been assessed.

} + +
+ } + @if (Model.Items.Count == 0) {
No observations in this view. Other observations remain accessible using the filters above.
} +
+ @foreach (var item in Model.Items) + { +
+ @item.Row.DisplayName@item.Status +
+ @if (!string.IsNullOrWhiteSpace(item.Direction)) {

@item.Direction · @item.State

} +

@item.Detail

+ @if (item.Pending || item.Row.DecisionStatus == "AutoAccepted") {

@string.Join(" ", item.Assessment.Reasons)

} +
Scene evidence (@item.Observations.Count) + @if (item.Observations.Count == 0) {

@item.Evidence

} + @foreach (var observation in item.Observations) { +

Chapter @observation.ChapterNumber.ToString("0.##"), scene @observation.SceneNumber.ToString("0.##") · @observation.Signal
@observation.Evidence

+ } +
+ @if (item.Pending) { Review this observation } +
+
+ } +
+ @if (Model.History.Count > 0) { +

Relationship journeys

+

Complete saved history for the pairs on this page, including both directions and observations outside the selected filter.

+ @foreach (var pair in Model.History.GroupBy(x => x.PairKey)) { +
@pair.First().Pair · @pair.Count() observations + @foreach (var entry in pair) { +
@entry.Direction · @entry.State

@entry.Detail · @entry.Status

+ @foreach (var observation in entry.Observations) {

Chapter @observation.ChapterNumber.ToString("0.##"), scene @observation.SceneNumber.ToString("0.##"): @observation.Evidence

} +
+ } +
+ } + } +
+ @if (Model.Page > 1) { Previous } + Page @Model.Page of @Model.PageCount + @if (Model.Page < Model.PageCount) { Next } + Back to Review Centre + View tracked @Model.Module.ToLowerInvariant() + Return to Book +
+
+
+ +@section Scripts { + +} diff --git a/PlotLine/Views/Onboarding/StoryIntelligenceAssets.cshtml b/PlotLine/Views/Onboarding/StoryIntelligenceAssets.cshtml index 8a657cc9..5cae5471 100644 --- a/PlotLine/Views/Onboarding/StoryIntelligenceAssets.cshtml +++ b/PlotLine/Views/Onboarding/StoryIntelligenceAssets.cshtml @@ -9,7 +9,7 @@

Story Intelligence

Review Assets

-

Review important object suggestions that need a create, same-asset, or ignore decision.

+

Review selected object suggestions when their identity or ownership matters to your story. Other suggestions can wait.

@if (TempData["OnboardingStoryIntelligenceError"] is string error) diff --git a/PlotLine/Views/Onboarding/StoryIntelligenceKnowledge.cshtml b/PlotLine/Views/Onboarding/StoryIntelligenceKnowledge.cshtml index 17738c30..f3819de0 100644 --- a/PlotLine/Views/Onboarding/StoryIntelligenceKnowledge.cshtml +++ b/PlotLine/Views/Onboarding/StoryIntelligenceKnowledge.cshtml @@ -11,7 +11,7 @@

Story Intelligence

Review Knowledge

-

Review facts, discoveries, beliefs, and suspicions that need an author decision.

+

Review selected facts, discoveries, beliefs and suspicions. You can return to your book without deciding every observation.

@if (TempData["OnboardingStoryIntelligenceError"] is string error) diff --git a/PlotLine/Views/Onboarding/StoryIntelligenceReviewCentre.cshtml b/PlotLine/Views/Onboarding/StoryIntelligenceReviewCentre.cshtml index 8bebabdd..45c24505 100644 --- a/PlotLine/Views/Onboarding/StoryIntelligenceReviewCentre.cshtml +++ b/PlotLine/Views/Onboarding/StoryIntelligenceReviewCentre.cshtml @@ -34,29 +34,9 @@ @* "Characters" "Review Characters" "StoryIntelligenceCharacters" "View Characters" new { projectId = Model.ProjectID } *@ @await ReviewCharacters() - @await ReviewModule( - "Assets", - Model.AssetNeedsAttentionCount, - Model.PipelineDashboard.AssetStageComplete, - !Model.CharacterGateSatisfied, - "Important objects and possessions found in the manuscript.", - "Review Assets", - "StoryIntelligenceAssets", - "View Assets", - "StoryAssets", - new { projectId = Model.ProjectID }) + @await Html.PartialAsync("_StoryIntelligenceExceptionTile", new StoryIntelligenceExceptionTileViewModel { BatchID=Model.BatchID, Module="Assets", Blocked=!Model.CharacterGateSatisfied, Summary=Model.ReviewSummaries.FirstOrDefault(x => x.Module == "Assets") }) - @await ReviewModule( - "Knowledge", - Model.KnowledgeNeedsAttentionCount, - Model.PipelineDashboard.KnowledgeStageComplete, - !Model.CharacterGateSatisfied, - "Facts, discoveries, beliefs, and suspicions found in the manuscript.", - "Review Knowledge", - "StoryIntelligenceKnowledge", - "View Knowledge", - "StoryBible", - new { projectId = Model.ProjectID }) + @await Html.PartialAsync("_StoryIntelligenceExceptionTile", new StoryIntelligenceExceptionTileViewModel { BatchID=Model.BatchID, Module="Knowledge", Blocked=!Model.CharacterGateSatisfied, Summary=Model.ReviewSummaries.FirstOrDefault(x => x.Module == "Knowledge") })

Locations

@@ -71,17 +51,7 @@ @await ReviewPlotSynthesis() - @await ReviewModule( - "Relationships", - Model.RelationshipNeedsAttentionCount, - Model.PipelineDashboard.RelationshipStageComplete, - !Model.CharacterGateSatisfied, - "Character relationships found in scene evidence.", - "Review Relationships", - "StoryIntelligenceRelationships", - "View Relationships", - "RelationshipMap", - new { projectId = Model.ProjectID, bookId = Model.BookID }) + @await Html.PartialAsync("_StoryIntelligenceExceptionTile", new StoryIntelligenceExceptionTileViewModel { BatchID=Model.BatchID, Module="Relationships", Blocked=!Model.CharacterGateSatisfied, Summary=Model.ReviewSummaries.FirstOrDefault(x => x.Module == "Relationships") }) @await ReviewMetrics(!Model.CharacterGateSatisfied) diff --git a/PlotLine/Views/Shared/_StoryIntelligenceExceptionTile.cshtml b/PlotLine/Views/Shared/_StoryIntelligenceExceptionTile.cshtml new file mode 100644 index 00000000..66a8ac66 --- /dev/null +++ b/PlotLine/Views/Shared/_StoryIntelligenceExceptionTile.cshtml @@ -0,0 +1,12 @@ +@model StoryIntelligenceExceptionTileViewModel +
+

@Model.Module

+ @if (Model.Summary is { } summary) { + @summary.IdentifiedCount observations identified +

@summary.TrackedCount tracked · @summary.OptionalCount worth reviewing · @summary.AttentionCount need attention

+ @if (summary.PairCount > 0) {

Across @summary.PairCount character pairs

} + @if (summary.UnassessedCount > 0) {

@summary.UnassessedCount awaiting priority assessment

} + } else {

Preparing saved observations

} + @if (Model.Blocked) { Resolve Characters first } + else { Explore @Model.Module } +