Add authorised chapter-scoped Context Intent palette reads
This commit is contained in:
parent
b76af35ecd
commit
04334b6bd9
@ -1,7 +1,10 @@
|
||||
# Context Intent task 67: implementation checkpoint
|
||||
|
||||
Status: partial implementation, not ready for acceptance. No task-67 migration,
|
||||
database change or deployment has been performed. The task remains incomplete.
|
||||
Status: partial implementation, not ready for acceptance. The task remains incomplete.
|
||||
The palette read path described below is implemented; checklist storage and the shared
|
||||
interactive Intent component are still outstanding. CYJ records qualification and
|
||||
Development deployment outcomes for each exact commit; source preparation alone is
|
||||
not evidence that a migration is applied or a feature is accepted.
|
||||
The former schema-release blocker is resolved: use the installed controller route
|
||||
and `Docs/Deployment/AutomaticDevelopment.md` under standing Development authority.
|
||||
Do not request individual routine Development SQL approval.
|
||||
@ -30,8 +33,40 @@ verification search: it does not preserve exact original passage offsets or sele
|
||||
longest overlapping multi-entity matches. Intent preparation does not invoke that
|
||||
paid verification workflow or change its contracts.
|
||||
|
||||
There is no Context endpoint, palette data loader, UI or persistence wired to this
|
||||
utility yet. Passing these tests does not establish feature acceptance.
|
||||
The text utility is not yet wired to accepted manuscript updates, interactive UI or
|
||||
persistence. Passing these tests does not establish feature acceptance.
|
||||
|
||||
## Authorised palette read path (2 December 2026)
|
||||
|
||||
`ContextIntentPalette` and `GET /Writing/Context/Intent/Palette` provide a shared,
|
||||
read-only JSON projection for later Context/Writer presentation. Required query
|
||||
parameters are `bookID` and `chapterID`; `sceneID` is optional. Default results are
|
||||
associated with that chapter/scene. `widerStory=true` includes the project catalog,
|
||||
with plotlines/threads restricted to the selected book or project-wide records;
|
||||
`search` matches names/aliases literally, case-insensitively, up to 200 characters.
|
||||
|
||||
Forward migration `343_ContextIntentPalette.sql` defines the stored procedure. It
|
||||
authorises the active project/book/chapter/optional scene before returning data,
|
||||
including for chapter-only scopes with no scenes or prose. Canonical characters,
|
||||
locations, assets, threads and plotlines reuse existing stores and association tables.
|
||||
Aliases come from canonical alias tables. Pending entity candidates require a current
|
||||
Ready preparation generation; pending narrative candidates reuse their persisted
|
||||
review store. Candidate scene provenance comes from persisted evidence tables.
|
||||
No raw Scene Intelligence JSON, preparation, AI, confirmation or fact write occurs.
|
||||
|
||||
Typed identities deduplicate appearances, preserve multiple provenance labels, and
|
||||
retain unconfirmed candidates separately from proposed canonical merge targets.
|
||||
Recorded and planned thread milestones remain labelled distinctly. Ambiguity checks
|
||||
consider catalog spellings beyond the displayed page. Results contain up to 200
|
||||
identities and an explicit `hasMore` flag; a bounded palette page must never be used
|
||||
as a complete manuscript matching index. Sources name scoped scene IDs, not Word
|
||||
positions. The endpoint never reads or mutates NarrativeFocus or Word presence.
|
||||
|
||||
`ContextIntentPaletteTests` covers identity/label separation, aliases, provenance,
|
||||
defensive snapshots, conflicting identity metadata, chapter scope, query bounds and
|
||||
pagination. Focused harness: `--context-intent-palette`. The deployed read path also
|
||||
needs real authenticated Development checks; see CYJ for actual results. This is not
|
||||
the checklist UI, a separate Intent window, or full task acceptance.
|
||||
|
||||
## Shared draft editing preparation (2 December 2026)
|
||||
|
||||
@ -138,8 +173,9 @@ before requesting a release. Reconcile any uncertain receipt before retrying.
|
||||
|
||||
The resumed source branch is `feature/context-intent-67-resume`, based on
|
||||
`9a3f4fbb` and including the original preparation commit `5bee47e6`. No task-67
|
||||
external write or deployment has occurred to reconcile. Do not treat preparation
|
||||
external write or deployment had occurred at the earlier draft checkpoint. For later
|
||||
palette qualification/deployment, reconcile the exact receipts recorded in CYJ. Do not treat preparation
|
||||
helpers or passing pure tests as feature acceptance. Required endpoint/persistence,
|
||||
shared UI, palette loading/search, accepted Word updates, Hold/Follow refresh,
|
||||
shared UI, palette UI integration, accepted Word updates, Hold/Follow refresh,
|
||||
backup/restore/deletion integration, schema qualification, Development deployment
|
||||
and genuine browser persistence/reload acceptance all remain outstanding.
|
||||
|
||||
87
PlotLine.Tests/Browser/context-intent-palette-acceptance.cjs
Normal file
87
PlotLine.Tests/Browser/context-intent-palette-acceptance.cjs
Normal file
@ -0,0 +1,87 @@
|
||||
// Backend palette milestone only. This does not certify the unfinished Intent UI.
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const {open} = require('./dev-acceptance.cjs');
|
||||
let session, stage = 'login';
|
||||
(async () => {
|
||||
try {
|
||||
session = await open();
|
||||
const project = await session.project();
|
||||
const book = await session.create('Books', '?projectId='+project, {BookTitle:'Intent palette acceptance',BookNumber:1});
|
||||
const chapter = await session.create('Chapters', '?bookId='+book, {ChapterTitle:'Empty chapter palette',ChapterNumber:1});
|
||||
const otherBook = await session.create('Books', '?projectId='+project, {BookTitle:'Other scoped book',BookNumber:2});
|
||||
const otherChapter = await session.create('Chapters', '?bookId='+otherBook, {ChapterTitle:'Other chapter',ChapterNumber:1});
|
||||
const base = {bookID:book, chapterID:chapter};
|
||||
async function read(query={}, expected=200) {
|
||||
const url = '/Writing/Context/Intent/Palette?'+new URLSearchParams({...base,...query});
|
||||
const result = await session.page.evaluate(async url => {
|
||||
const response = await fetch(url, {credentials:'same-origin'});
|
||||
return {status:response.status, data:response.status===200?await response.json():null};
|
||||
}, url);
|
||||
assert.equal(result.status, expected);
|
||||
return result.data;
|
||||
}
|
||||
stage='chapter-only/no-prose read';
|
||||
assert.deepEqual((await read()).entries, []);
|
||||
stage='canonical equal-label fixtures';
|
||||
const name='Palette shared name';
|
||||
const person = await session.create('Characters','?projectId='+project,{CharacterName:name},async page=>{
|
||||
const sex=page.locator('[name=CustomSex]');
|
||||
if(await sex.isEnabled() && await sex.getAttribute('required')!==null) await sex.fill('Unspecified');
|
||||
});
|
||||
const place = await session.create('Locations','?projectId='+project,{LocationName:name});
|
||||
const literal = await session.create('Locations','?projectId='+project,{LocationName:'Palette literal %'});
|
||||
stage='wider story identity and literal search';
|
||||
const wider = await read({widerStory:true, search:'SHARED NAME'});
|
||||
assert.deepEqual(new Set(wider.entries.map(e=>e.key)), new Set(['character:'+person,'location:'+place]));
|
||||
assert(wider.entries.every(e=>e.possiblyAmbiguous && !e.isCandidate && !e.inScope));
|
||||
assert.equal(wider.hasMore,false);
|
||||
assert.deepEqual((await read({widerStory:true,search:'%'})).entries.map(e=>e.key),['location:'+literal]);
|
||||
assert.deepEqual((await read()).entries, []);
|
||||
async function scene(location, title) {
|
||||
await session.goto('/Scenes/Create?chapterId='+chapter);
|
||||
const page=session.page;
|
||||
await page.locator('#SceneTitle').fill(title);
|
||||
await page.locator('#PrimaryLocationID').selectOption(String(location));
|
||||
await page.getByRole('button',{name:'Create scene',exact:true}).click();
|
||||
await page.waitForURL('**/Scenes/Edit/*');
|
||||
return Number(new URL(page.url()).pathname.split('/').at(-1));
|
||||
}
|
||||
stage='recorded chapter/scene associations';
|
||||
const first=await scene(place,'Palette first scene'), second=await scene(literal,'Palette second scene');
|
||||
let scoped=await read({sceneID:first});
|
||||
assert.deepEqual(scoped.entries.map(e=>e.key),['location:'+place]);
|
||||
assert(scoped.entries[0].inScope && scoped.entries[0].possiblyAmbiguous);
|
||||
assert.deepEqual(scoped.entries[0].sources,[{sceneID:first,provenance:'Scene location'}]);
|
||||
assert.deepEqual((await read({sceneID:second})).entries.map(e=>e.key),['location:'+literal]);
|
||||
assert.deepEqual(new Set((await read()).entries.map(e=>e.key)),new Set(['location:'+place,'location:'+literal]));
|
||||
stage='invalid and mismatched scope denial';
|
||||
await read({chapterID:otherChapter},403);
|
||||
await read({bookID:otherBook},403);
|
||||
await read({chapterID:otherChapter,bookID:otherBook,sceneID:first},403);
|
||||
await read({sceneID:0},400);
|
||||
await read({search:'x'.repeat(201)},400);
|
||||
stage='fresh login persistence and read-only source';
|
||||
await session.close(); session=await open();
|
||||
scoped=await read({sceneID:first});
|
||||
assert.equal(scoped.entries[0].key,'location:'+place);
|
||||
await session.goto('/Scenes/Edit/'+first);
|
||||
assert.equal(await session.page.locator('#PrimaryLocationID').inputValue(),String(place));
|
||||
assert.equal(await session.page.locator('#SceneTitle').inputValue(),'Palette first scene');
|
||||
console.log(JSON.stringify({passed:true,milestone:'palette read path only',checks:[
|
||||
'chapter without prose or scenes','canonical identity separation and hidden-label ambiguity',
|
||||
'case-insensitive wider search and literal percent','chapter and optional scene associations/provenance',
|
||||
'book/chapter/scene mismatch denial and query limits','fresh login reads authoritative saved sources'
|
||||
],featureUrl:'https://dev.plotdirector.com/Writing/Context/Intent/Palette?'+new URLSearchParams(base),
|
||||
limitations:['interactive checklist/palette component and candidate fixture acceptance remain outstanding']}));
|
||||
} catch(error) {
|
||||
console.error('Intent palette acceptance failed at '+stage+' ('+error.name+'). No credentials logged.');
|
||||
process.exitCode=1;
|
||||
} finally {
|
||||
if(session) {
|
||||
try { await session.cleanup(); console.log('PASS disposable Intent palette project cleanup'); }
|
||||
catch { console.error('Intent palette cleanup needs documented resume.'); process.exitCode=1; }
|
||||
finally { await session.close(); }
|
||||
}
|
||||
}
|
||||
})().catch(()=>{console.error('Intent palette session failed; preserve run journal.');process.exitCode=1;});
|
||||
61
PlotLine.Tests/ContextIntentPaletteTests.cs
Normal file
61
PlotLine.Tests/ContextIntentPaletteTests.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using PlotLine.Services.Context;
|
||||
using static PlotLine.Services.Context.ContextIntentPalette;
|
||||
|
||||
internal static class ContextIntentPaletteTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
|
||||
static void Reject(Action action)
|
||||
{
|
||||
try { action(); } catch (ArgumentException) { return; }
|
||||
throw new Exception("Expected invalid palette query rejection.");
|
||||
}
|
||||
var scope = new IntentPaletteScope(1, 2, 3, null);
|
||||
Row[] rows = [
|
||||
new("character:5", "Aster", "character", false, true, true),
|
||||
new("character:5", "Aster", "character", false, true, false),
|
||||
new("candidate:9", "Aster", "character", true, false, true),
|
||||
new("location:5", "Aster", "location", false, false, true)
|
||||
];
|
||||
AliasRow[] aliases = [new("character:5", " Captain "), new("character:5", "CAPTAIN"),
|
||||
new("character:5", "Aster"), new("candidate:9", ""), new("asset:1", "Unrelated")];
|
||||
SourceRow[] sources = [new("character:5", 8, "Recorded appearance"),
|
||||
new("character:5", 8, "Recorded appearance"), new("character:5", 8, "Planned reference"),
|
||||
new("asset:1", 8, "Unrelated")];
|
||||
var frame = Compose(scope, rows, aliases, sources);
|
||||
Check(frame.Scope == scope && frame.Entries.Count == 3 && !frame.HasMore,
|
||||
"Chapter-only scope and identity deduplication are preserved.");
|
||||
var character = frame.Entries[0];
|
||||
Check(character.Key == "character:5" && character.InScope && character.PossiblyAmbiguous,
|
||||
"Any ambiguous/source appearance survives deduplication.");
|
||||
Check(character.Aliases.SequenceEqual(new[] { "Aster", "Captain" }) && character.Sources.Count == 2,
|
||||
"Aliases and provenance deduplicate independently without unrelated attachments.");
|
||||
Check(frame.Entries[1].IsCandidate && !frame.Entries[1].InScope && !frame.Entries[2].IsCandidate,
|
||||
"Equal labels, proposed identities and cross-kind numeric IDs never merge.");
|
||||
Check(frame.Entries[1].Sources.Count == 0 && frame.Entries[1].Aliases.Count == 1,
|
||||
"No candidate evidence or aliases are inferred from equal canonical labels.");
|
||||
aliases[0] = new("character:5", "Changed");
|
||||
sources[0] = new("character:5", 9, "Changed");
|
||||
Check(character.Aliases[1] == "Captain" && character.Sources.All(s => s.SceneID == 8),
|
||||
"Frame attachments are stable snapshots.");
|
||||
var many = Enumerable.Range(1, 201).Select(i => new Row($"asset:{i}", $"Asset {i}", "asset", false, false, false)).ToArray();
|
||||
var page = Compose(scope, many, [], []);
|
||||
Check(page.Entries.Count == PageSize && page.HasMore && page.Entries[^1].Key == "asset:200",
|
||||
"Overflow is explicit and order is preserved; a page is never a complete match index.");
|
||||
Check(!Compose(scope, many.Take(200).ToArray(), [], []).HasMore, "An exact page is complete.");
|
||||
Validate(new(2, 3));
|
||||
Validate(new(2, 3, 4, true, " Aster "));
|
||||
Reject(() => Validate(new(0, 3)));
|
||||
Reject(() => Validate(new(2, 0)));
|
||||
Reject(() => Validate(new(2, 3, 0)));
|
||||
Reject(() => Validate(new(2, 3, Search: new string('x', 201))));
|
||||
Reject(() => Validate(new(2, 3, Search: null!)));
|
||||
try
|
||||
{
|
||||
Compose(scope, [rows[0], rows[0] with { IsCandidate = true }], [], []);
|
||||
throw new Exception("Conflicting identity metadata was accepted.");
|
||||
}
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
}
|
||||
@ -22,6 +22,7 @@ if(args.Contains("--scene-creation")){await SceneCreationTests.Run();return;}
|
||||
if(args.Contains("--help-visibility")){HelpVisibilityTests.Run();return;}
|
||||
if(args.Contains("--context-intent-text")){ContextIntentTextTests.Run();Console.WriteLine("PASS Context Intent paste preview, identity deduplication and deterministic passage matching");return;}
|
||||
if(args.Contains("--context-intent-draft")){ContextIntentDraftTests.Run();Console.WriteLine("PASS Context Intent author draft editing, explicit coverage and scoped evidence");return;}
|
||||
if(args.Contains("--context-intent-palette")){ContextIntentPaletteTests.Run();Console.WriteLine("PASS Context Intent scoped palette identity, provenance and bounded query contracts");return;}
|
||||
if(args.Contains("--application-domain")){ApplicationDomainBoundaryTests.Run();return;}
|
||||
if(args.Contains("--spatial-context-database")){await SpatialContextDatabaseTests.Run(args.Last());return;}
|
||||
if(args.Contains("--location-taxonomy-fixture")){await LocationsWorkspaceDatabaseTests.ExportTaxonomy(args[^2],args[^1]);return;}
|
||||
@ -251,6 +252,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),
|
||||
("Context Intent deterministic text preparation",ContextIntentTextTests.Run),
|
||||
("Context Intent author draft operations",ContextIntentDraftTests.Run),
|
||||
("Context Intent palette projection",ContextIntentPaletteTests.Run),
|
||||
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
|
||||
("Context committed-save notifications and scope",()=>ContextSavedDataTests.Run().GetAwaiter().GetResult()),
|
||||
("Context main-page navigation safety and delegated link coverage",ContextWorkspaceNavigationTests.Run),
|
||||
|
||||
24
PlotLine/Controllers/ContextIntentController.cs
Normal file
24
PlotLine/Controllers/ContextIntentController.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services.Context;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("Writing/Context/Intent")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ContextIntentController(ContextIntentPalette palette) : Controller
|
||||
{
|
||||
// Reusable read endpoint for both Context and the docked Writer component.
|
||||
// It takes an explicit held scope and never follows or changes the Word caret.
|
||||
[HttpGet("Palette")]
|
||||
public async Task<IActionResult> Palette([FromQuery] IntentPaletteQuery query)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest();
|
||||
try { return Json(await palette.Read(query)); }
|
||||
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
|
||||
catch (UnauthorizedAccessException) { return Forbid(); }
|
||||
catch (SqlException e) when (e.Number == 51010) { return Forbid(); }
|
||||
}
|
||||
}
|
||||
@ -311,6 +311,7 @@ public class Program
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextSpatial>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextThreads>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextAssets>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextIntentPalette>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextWarnings>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipEditing>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();
|
||||
|
||||
72
PlotLine/Services/Context/ContextIntentPalette.cs
Normal file
72
PlotLine/Services/Context/ContextIntentPalette.cs
Normal file
@ -0,0 +1,72 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
using PlotLine.Data;
|
||||
|
||||
namespace PlotLine.Services.Context;
|
||||
|
||||
public sealed record IntentPaletteQuery(int BookID, int ChapterID, int? SceneID = null,
|
||||
bool WiderStory = false, string Search = "");
|
||||
public sealed record IntentPaletteScope(int ProjectID, int BookID, int ChapterID, int? SceneID);
|
||||
public sealed record IntentPaletteSource(int SceneID, string Provenance);
|
||||
public sealed record IntentPaletteEntry(string Key, string Name, string Kind, bool IsCandidate,
|
||||
bool InScope, bool PossiblyAmbiguous, IReadOnlyList<string> Aliases,
|
||||
IReadOnlyList<IntentPaletteSource> Sources);
|
||||
public sealed record IntentPaletteFrame(IntentPaletteScope Scope,
|
||||
IReadOnlyList<IntentPaletteEntry> Entries, bool HasMore);
|
||||
|
||||
// The database authorises the exact chapter/optional scene before any catalog is
|
||||
// returned. Reads neither prepare candidates nor move the manuscript or focus.
|
||||
public sealed class ContextIntentPalette(ISqlConnectionFactory connections, ICurrentUserService user)
|
||||
{
|
||||
public const int PageSize = 200;
|
||||
public sealed record Row(string EntityKey, string Name, string Kind, bool IsCandidate,
|
||||
bool InScope, bool PossiblyAmbiguous);
|
||||
public sealed record AliasRow(string EntityKey, string Alias);
|
||||
public sealed record SourceRow(string EntityKey, int SceneID, string Provenance);
|
||||
|
||||
public async Task<IntentPaletteFrame> Read(IntentPaletteQuery query)
|
||||
{
|
||||
Validate(query);
|
||||
var author = user.UserId ?? throw new UnauthorizedAccessException();
|
||||
using var db = connections.CreateConnection();
|
||||
using var result = await db.QueryMultipleAsync("dbo.ContextIntent_Palette",
|
||||
new { UserID = author, query.BookID, query.ChapterID, query.SceneID, query.WiderStory, Search = query.Search.Trim() },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
var scope = await result.ReadSingleAsync<IntentPaletteScope>();
|
||||
var rows = (await result.ReadAsync<Row>()).ToArray();
|
||||
var aliases = (await result.ReadAsync<AliasRow>()).ToArray();
|
||||
var sources = (await result.ReadAsync<SourceRow>()).ToArray();
|
||||
if (scope.BookID != query.BookID || scope.ChapterID != query.ChapterID || scope.SceneID != query.SceneID)
|
||||
throw new InvalidOperationException("The palette returned a different Intent scope.");
|
||||
return Compose(scope, rows, aliases, sources);
|
||||
}
|
||||
|
||||
public static void Validate(IntentPaletteQuery query)
|
||||
{
|
||||
if (query.BookID <= 0 || query.ChapterID <= 0 || query.SceneID <= 0 || query.Search is null || query.Search.Length > 200)
|
||||
throw new ArgumentException("Choose a saved chapter and optional scene; search with at most 200 characters.");
|
||||
}
|
||||
|
||||
// One identity can have many recorded/planned appearances and aliases. Labels
|
||||
// never merge identities, including pending candidates with proposed targets.
|
||||
public static IntentPaletteFrame Compose(IntentPaletteScope scope, IReadOnlyList<Row> rows,
|
||||
IReadOnlyList<AliasRow> aliases, IReadOnlyList<SourceRow> sources)
|
||||
{
|
||||
var identities = rows.GroupBy(r => r.EntityKey, StringComparer.Ordinal).ToArray();
|
||||
var byAlias = aliases.ToLookup(a => a.EntityKey, StringComparer.Ordinal);
|
||||
var bySource = sources.ToLookup(s => s.EntityKey, StringComparer.Ordinal);
|
||||
var entries = identities.Take(PageSize).Select(group =>
|
||||
{
|
||||
var row = group.First();
|
||||
if (group.Any(r => r.Name != row.Name || r.Kind != row.Kind || r.IsCandidate != row.IsCandidate))
|
||||
throw new InvalidOperationException("Conflicting Story Element identity metadata.");
|
||||
return new IntentPaletteEntry(row.EntityKey, row.Name, row.Kind, row.IsCandidate,
|
||||
group.Any(r => r.InScope), group.Any(r => r.PossiblyAmbiguous),
|
||||
Array.AsReadOnly(byAlias[row.EntityKey].Select(a => a.Alias.Trim()).Prepend(row.Name)
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray()),
|
||||
Array.AsReadOnly(bySource[row.EntityKey].Select(s => new IntentPaletteSource(s.SceneID, s.Provenance))
|
||||
.Distinct().OrderBy(s => s.SceneID).ThenBy(s => s.Provenance, StringComparer.Ordinal).ToArray()));
|
||||
}).ToArray();
|
||||
return new(scope, Array.AsReadOnly(entries), identities.Length > PageSize);
|
||||
}
|
||||
}
|
||||
108
PlotLine/Sql/343_ContextIntentPalette.sql
Normal file
108
PlotLine/Sql/343_ContextIntentPalette.sql
Normal file
@ -0,0 +1,108 @@
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
-- Read-only projection over authoritative identities, associations and prepared
|
||||
-- review candidates. No preparation, materialisation or manuscript navigation.
|
||||
CREATE OR ALTER PROCEDURE dbo.ContextIntent_Palette
|
||||
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL,
|
||||
@WiderStory bit=0,@Search nvarchar(200)=N''
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
DECLARE @project int;
|
||||
SELECT @project=b.ProjectID FROM dbo.Chapters c
|
||||
JOIN dbo.Books b ON b.BookID=c.BookID AND b.IsArchived=0
|
||||
JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0
|
||||
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
|
||||
WHERE c.ChapterID=@ChapterID AND c.BookID=@BookID AND c.IsArchived=0;
|
||||
IF @project IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS(
|
||||
SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0))
|
||||
THROW 51010,'This Intent scope is unavailable.',1;
|
||||
SET @Search=LTRIM(RTRIM(ISNULL(@Search,N'')));
|
||||
SELECT @project ProjectID,@BookID BookID,@ChapterID ChapterID,@SceneID SceneID;
|
||||
|
||||
SELECT SceneID,POVCharacterID,PrimaryLocationID INTO #scope FROM dbo.Scenes
|
||||
WHERE ChapterID=@ChapterID AND IsArchived=0 AND (@SceneID IS NULL OR SceneID=@SceneID);
|
||||
CREATE TABLE #entities(EntityKey nvarchar(80) NOT NULL PRIMARY KEY,Name nvarchar(450) NOT NULL,
|
||||
Kind nvarchar(20) NOT NULL,IsCandidate bit NOT NULL);
|
||||
INSERT #entities
|
||||
SELECT CONCAT(N'character:',CharacterID),CharacterName,N'character',0 FROM dbo.Characters WHERE ProjectID=@project AND IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'location:',LocationID),LocationName,N'location',0 FROM dbo.Locations WHERE ProjectID=@project AND IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'asset:',StoryAssetID),AssetName,N'asset',0 FROM dbo.StoryAssets WHERE ProjectID=@project AND IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'plotline:',PlotLineID),PlotLineName,N'plotline',0 FROM dbo.PlotLines WHERE ProjectID=@project AND IsArchived=0 AND (BookID IS NULL OR BookID=@BookID)
|
||||
UNION ALL SELECT CONCAT(N'thread:',t.PlotThreadID),t.ThreadTitle,N'thread',0 FROM dbo.PlotThreads t
|
||||
JOIN dbo.PlotLines l ON l.PlotLineID=t.PlotLineID AND l.ProjectID=@project AND l.IsArchived=0 AND (l.BookID IS NULL OR l.BookID=@BookID) WHERE t.IsArchived=0;
|
||||
-- An undecided identity remains a candidate even when it proposes an existing
|
||||
-- target. A proposed target is not an author-confirmed merge.
|
||||
INSERT #entities
|
||||
SELECT CONCAT(N'candidate:',c.ReviewCandidateID),c.DisplayName,
|
||||
CASE c.Module WHEN N'Characters' THEN N'character' WHEN N'Locations' THEN N'location' ELSE N'asset' END,1
|
||||
FROM dbo.StoryIntelligenceReviewCandidates c
|
||||
JOIN dbo.StoryIntelligenceReviewCandidateGenerations g ON g.ReviewCandidateGenerationID=c.ReviewCandidateGenerationID
|
||||
WHERE c.ProjectID=@project AND c.BookID=@BookID AND g.ProjectID=@project AND g.BookID=@BookID
|
||||
AND g.IsCurrent=1 AND g.Status=N'Ready' AND c.Module=g.Module
|
||||
AND c.Module IN(N'Characters',N'Locations',N'Assets') AND c.DecisionStatus=N'Pending';
|
||||
INSERT #entities
|
||||
SELECT CONCAT(N'narrative-candidate:',NarrativeCandidateID),ProposedTitle,
|
||||
CASE CandidateType WHEN N'PlotLine' THEN N'plotline' ELSE N'thread' END,1
|
||||
FROM dbo.StoryIntelligenceNarrativeCandidates
|
||||
WHERE ProjectID=@project AND BookID=@BookID AND Status=N'Pending' AND CandidateType IN(N'PlotLine',N'Thread');
|
||||
|
||||
CREATE TABLE #sources(EntityKey nvarchar(80) NOT NULL,SceneID int NOT NULL,Provenance nvarchar(100) NOT NULL);
|
||||
INSERT #sources
|
||||
SELECT CONCAT(N'character:',sc.CharacterID),sc.SceneID,N'Recorded appearance' FROM dbo.SceneCharacters sc JOIN #scope s ON s.SceneID=sc.SceneID
|
||||
UNION ALL SELECT CONCAT(N'character:',POVCharacterID),SceneID,N'Point of view' FROM #scope WHERE POVCharacterID IS NOT NULL
|
||||
UNION ALL SELECT CONCAT(N'location:',PrimaryLocationID),SceneID,N'Scene location' FROM #scope WHERE PrimaryLocationID IS NOT NULL
|
||||
UNION ALL SELECT CONCAT(N'location:',v.ID),sc.SceneID,N'Recorded character position' FROM dbo.SceneCharacters sc JOIN #scope s ON s.SceneID=sc.SceneID
|
||||
CROSS APPLY(VALUES(sc.LocationID),(sc.EntryLocationID),(sc.ExitLocationID))v(ID) WHERE v.ID IS NOT NULL
|
||||
UNION ALL SELECT CONCAT(N'location:',a.LocationID),a.SceneID,N'Recorded asset position' FROM dbo.SceneAssetLocations a JOIN #scope s ON s.SceneID=a.SceneID
|
||||
UNION ALL SELECT CONCAT(N'location:',o.LocationID),o.SceneID,N'Recorded floor-plan occupancy' FROM dbo.SceneFloorPlanOccupancy o JOIN #scope s ON s.SceneID=o.SceneID
|
||||
UNION ALL SELECT CONCAT(N'asset:',a.StoryAssetID),a.SceneID,N'Recorded asset event' FROM dbo.AssetEvents a JOIN #scope s ON s.SceneID=a.SceneID
|
||||
UNION ALL SELECT CONCAT(N'asset:',a.StoryAssetID),a.SceneID,N'Recorded asset position' FROM dbo.SceneAssetLocations a JOIN #scope s ON s.SceneID=a.SceneID
|
||||
UNION ALL SELECT CONCAT(N'asset:',a.StoryAssetID),a.SceneID,N'Recorded custody' FROM dbo.AssetCustodyEvents a JOIN #scope s ON s.SceneID=a.SceneID
|
||||
UNION ALL SELECT CONCAT(N'thread:',t.PlotThreadID),t.SceneID,N'Recorded thread association' FROM dbo.SceneThreads t JOIN #scope s ON s.SceneID=t.SceneID
|
||||
UNION ALL SELECT CONCAT(N'thread:',t.PlotThreadID),t.SceneID,N'Recorded thread event' FROM dbo.ThreadEvents t JOIN #scope s ON s.SceneID=t.SceneID
|
||||
UNION ALL SELECT CONCAT(N'thread:',t.PlotThreadID),v.SceneID,v.Source FROM dbo.PlotThreads t
|
||||
CROSS APPLY(VALUES(t.IntroducedSceneID,N'Recorded introduction'),(t.ActualResolutionSceneID,N'Recorded resolution'),(t.PlannedResolutionSceneID,N'Planned resolution'))v(SceneID,Source)
|
||||
JOIN #scope s ON s.SceneID=v.SceneID
|
||||
UNION ALL SELECT CONCAT(N'candidate:',c.ReviewCandidateID),ev.SceneID,N'Prepared candidate evidence; unconfirmed'
|
||||
FROM dbo.StoryIntelligenceReviewCandidates c JOIN dbo.StoryIntelligenceReviewCandidateEvidence ev ON ev.ReviewCandidateID=c.ReviewCandidateID JOIN #scope s ON s.SceneID=ev.SceneID
|
||||
JOIN #entities e ON e.EntityKey=CONCAT(N'candidate:',c.ReviewCandidateID);
|
||||
INSERT #sources
|
||||
SELECT e.EntityKey,ev.SceneID,N'Prepared narrative candidate evidence; unconfirmed'
|
||||
FROM dbo.StoryIntelligenceNarrativeCandidateEvidence ev JOIN #scope s ON s.SceneID=ev.SceneID
|
||||
JOIN #entities e ON e.EntityKey=CONCAT(N'narrative-candidate:',ev.NarrativeCandidateID);
|
||||
INSERT #sources
|
||||
SELECT CONCAT(N'plotline:',t.PlotLineID),s.SceneID,s.Provenance FROM #sources s
|
||||
JOIN dbo.PlotThreads t ON s.EntityKey=CONCAT(N'thread:',t.PlotThreadID)
|
||||
JOIN #entities e ON e.EntityKey=CONCAT(N'plotline:',t.PlotLineID);
|
||||
INSERT #sources
|
||||
SELECT CONCAT(N'plotline:',te.TargetPlotLineID),te.SceneID,N'Recorded plotline contribution'
|
||||
FROM dbo.ThreadEvents te JOIN #scope s ON s.SceneID=te.SceneID
|
||||
JOIN #entities e ON e.EntityKey=CONCAT(N'plotline:',te.TargetPlotLineID);
|
||||
|
||||
CREATE TABLE #aliases(EntityKey nvarchar(80) NOT NULL,Alias nvarchar(450) NOT NULL);
|
||||
INSERT #aliases SELECT EntityKey,Name FROM #entities
|
||||
UNION ALL SELECT e.EntityKey,a.Alias FROM dbo.CharacterAliases a JOIN #entities e ON e.EntityKey=CONCAT(N'character:',a.CharacterID)
|
||||
UNION ALL SELECT e.EntityKey,a.Alias FROM dbo.LocationAliases a JOIN #entities e ON e.EntityKey=CONCAT(N'location:',a.LocationID)
|
||||
UNION ALL SELECT e.EntityKey,a.Alias FROM dbo.AssetAliases a JOIN #entities e ON e.EntityKey=CONCAT(N'asset:',a.StoryAssetID);
|
||||
DELETE FROM #aliases WHERE LEN(LTRIM(RTRIM(Alias)))=0;
|
||||
CREATE INDEX IX_IntentPalette_Alias ON #aliases(Alias,EntityKey);
|
||||
CREATE INDEX IX_IntentPalette_IdentityAlias ON #aliases(EntityKey,Alias);
|
||||
CREATE INDEX IX_IntentPalette_Source ON #sources(EntityKey);
|
||||
-- Fetch one extra identity to report a bounded search honestly. Do not silently
|
||||
-- lose scoped identities or imply that a partial page is a complete match index.
|
||||
SELECT TOP(201) e.*,CONVERT(bit,CASE WHEN EXISTS(SELECT 1 FROM #sources s WHERE s.EntityKey=e.EntityKey) THEN 1 ELSE 0 END) InScope
|
||||
INTO #selected FROM #entities e
|
||||
WHERE (@WiderStory=1 OR EXISTS(SELECT 1 FROM #sources s WHERE s.EntityKey=e.EntityKey))
|
||||
AND (@Search=N'' OR EXISTS(SELECT 1 FROM #aliases a WHERE a.EntityKey=e.EntityKey AND CHARINDEX(@Search COLLATE Latin1_General_100_CI_AS_SC,a.Alias COLLATE Latin1_General_100_CI_AS_SC)>0))
|
||||
ORDER BY InScope DESC,e.Name,e.EntityKey;
|
||||
SELECT s.*,CONVERT(bit,CASE WHEN EXISTS(
|
||||
SELECT 1 FROM #aliases a JOIN #aliases other ON other.Alias COLLATE Latin1_General_100_CI_AS_SC=a.Alias COLLATE Latin1_General_100_CI_AS_SC AND other.EntityKey<>a.EntityKey
|
||||
WHERE a.EntityKey=s.EntityKey) THEN 1 ELSE 0 END) PossiblyAmbiguous
|
||||
FROM #selected s ORDER BY s.InScope DESC,s.Name,s.EntityKey;
|
||||
SELECT DISTINCT a.EntityKey,a.Alias FROM #aliases a JOIN #selected s ON s.EntityKey=a.EntityKey ORDER BY a.EntityKey,a.Alias;
|
||||
SELECT DISTINCT r.EntityKey,r.SceneID,r.Provenance FROM #sources r JOIN #selected s ON s.EntityKey=r.EntityKey ORDER BY r.EntityKey,r.SceneID,r.Provenance;
|
||||
END;
|
||||
GO
|
||||
Loading…
x
Reference in New Issue
Block a user