Compare commits

...

2 Commits

5 changed files with 152 additions and 3 deletions

View File

@ -27,3 +27,9 @@ No migrations have been applied to Development and no deployment has occurred du
## Context reuse
The pre-existing Names tab now mounts the same shared workspace. Its adapter only supplies authorised Context endpoints and retains component state keyed by pane and book. Separate windows have separate JavaScript state. Book-scoped Context refresh policy ignores paragraph/scene movement; character invalidation continues through the workspace's established connection and remount lifecycle. Character links open canonical records elsewhere. No new connections or manuscript-focus commands are introduced.
## Query plan stability
Authenticated Development acceptance exposed a timeout when a cached catalogue plan was reused across different prefix/default/locale/usage filters on a small cast. Forward-only migration 333 recompiles the final catalogue statement for the current parameters, without changing matching, metadata, ordering or pagination. Migration 325 remains immutable. Qualification now alternates narrow and broad searches, locale/era criteria and assigned/available filters with a two-character cast, in addition to the 500-character fixture. The benchmark restores the latest procedure after measuring historical SQL, so tests do not leave the database on an earlier definition.
Context Names state is keyed by series and pane, so switching books within the same series retains the author's search and selection. Requests still use the current authorised Context book; moving to another series uses independent state.

View File

@ -10,7 +10,7 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=r
await page.route('**/Characters/Reanalyse**',r=>{posts.push(r.request().postData());return r.fulfill({json:{success:true,characterID:5,characterEnrichmentRunID:777,status:'Queued',bookID:12,currentMessage:'Synthetic analysis queued'}});});
await page.goto(base+'/character-workspace-fixture');await page.locator('[data-character-reanalyse-button]').waitFor({state:'attached'});
async function open(){await page.locator('[data-character-ribbon] .dropdown-toggle').click();await page.locator('[data-character-reanalyse-button]').click();await page.locator('.pd-ai-confirm').waitFor();}
fs.mkdirSync('/tmp/pd-ai-allowances',{recursive:true});await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('requires an AI-enabled subscription'));assert.equal(await page.locator('.pd-ai-confirm a').getAttribute('href'),'/ManageAccount/Subscription');assert.equal(posts.length,0);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-restriction.png`});await page.keyboard.press('Escape');assert.equal(await page.locator('.pd-ai-confirm').count(),0);
fs.mkdirSync('/tmp/pd-ai-allowances',{recursive:true});await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('requires an AI-enabled subscription'));assert.equal(await page.locator('.pd-ai-confirm a').getAttribute('href'),'/ManageAccount/Subscription');assert.equal(posts.length,0);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-restriction.png`});await page.keyboard.press('Escape');await page.locator('.pd-ai-confirm').waitFor({state:'detached'});
allowed=true;await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('10 AI credits'));await page.getByRole('button',{name:'Cancel',exact:true}).click();assert.equal(posts.length,0);await open();await page.getByRole('button',{name:'Continue · 10 credits',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-character-analysis-status]')?.textContent==='Queued');assert.equal(posts.length,1);assert.match(posts[0],/name="expectedCredits"\r\n\r\n10/);assert.match(posts[0],/name="requestID"\r\n\r\n[a-f0-9-]{36}/i);assert(posts[0].includes('__RequestVerificationToken'));
await page.goto(base+'/ai-policy-fixture/admin');assert.equal(await page.locator('form input[name=Action][value=Operation]').count(),1);assert((await page.locator('body').innerText()).includes('Unrecorded'));assert.equal(await page.locator('form').filter({has:page.locator('input[name=SubscriptionLevelID][value="1"]')}).locator('[name=Enabled] option[value=true]').count(),0);
for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-admin-${theme}.png`});}

View File

@ -77,8 +77,11 @@ internal static class NameVerificationDatabaseTests
await Measure("initialResults",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});await Measure("catalogueSearch",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("selectedMetadata",async()=>{await catalogue.RecogniseAsync("GEORGE",null,null);});await Measure("characterAssociations",async()=>{await catalogue.ListUsedDecorationsAsync(user,project,null,"GEORGE","Project");});await Measure("localCandidateSearch",async()=>{await manuscripts.Search(user,project,"Rose");});await Measure("verificationCacheRead",async()=>{await service.Read(user,project,"Rose");});
var sqlRoot=Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,"../../../../PlotLine/Sql"));
async Task Apply(string file){foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(Path.Combine(sqlRoot,file)),@"^GO\s*$",System.Text.RegularExpressions.RegexOptions.Multiline|System.Text.RegularExpressions.RegexOptions.IgnoreCase)){if(!string.IsNullOrWhiteSpace(batch))await db.ExecuteAsync(batch);}}
try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("initialResultsBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});}finally{await Apply("325_NamesRecordedUsage.sql");}
try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("initialResultsBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});}finally{await Apply("333_NameSearchPlanStability.sql");}
Console.WriteLine("PERFORMANCE synthetic qualification, 500 characters / 5009 paragraphs, median milliseconds "+JsonSerializer.Serialize(measurements));
await db.ExecuteAsync("UPDATE dbo.Characters SET IsArchived=1 WHERE ProjectID=@ProjectID AND CharacterName NOT IN(N'George',N'Hamish')",new{ProjectID=project});
foreach(var filter in new NameSearchFilter[]{new(){ProjectID=project,Search="George"},new(){ProjectID=project},new(){ProjectID=project,LocaleCode="US",BirthYear=1950,NameType="Canonical"},new(){ProjectID=project,UsedOnly=true},new(){ProjectID=project,UsedOnly=false},new(){ProjectID=project,Search="Ge"},new(){ProjectID=project}}){var clock=Stopwatch.StartNew();await catalogue.SearchAsync(user,filter);Check(clock.Elapsed<TimeSpan.FromSeconds(10),"small-cast search remains bounded across prefix/default/locale/usage plan changes");}
}
finally
{

View File

@ -0,0 +1,140 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Recompile the bounded catalogue query for the current prefix/locale/usage filters.
-- Avoid reusing a narrow-prefix or small-cast plan for an unfiltered directory.
-- Live migration 325 remains immutable; data, matching and ordering are unchanged.
CREATE OR ALTER PROCEDURE dbo.GivenName_Search
@UserID int,
@ProjectID int,
@BookID int = NULL,
@Search nvarchar(120) = NULL,
@LocaleCode nvarchar(16) = NULL,
@BirthYear int = NULL,
@GenderPreference nvarchar(12) = NULL,
@GenderThreshold decimal(9,4) = NULL,
@NameType nvarchar(40) = NULL,
@MinimumUsage decimal(9,4) = NULL,
@UsedScope nvarchar(20) = N'Project',
@UsedOnly bit = NULL,
@Page int = 1,
@PageSize int = 25
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID = @ProjectID AND UserID = @UserID AND IsActive = 1)
BEGIN
SELECT TOP (0) CAST(NULL AS int) AS GivenNameID;
RETURN;
END;
IF @Page < 1 SET @Page = 1;
IF @PageSize < 1 SET @PageSize = 25;
IF @PageSize > 100 SET @PageSize = 100;
DECLARE @NameLocaleID int = NULL;
IF @LocaleCode IS NOT NULL
BEGIN
SELECT TOP (1) @NameLocaleID = NameLocaleID FROM dbo.NameLocales WHERE LocaleCode = @LocaleCode AND IsActive = 1;
END;
;WITH CandidateNames AS
(
SELECT * FROM dbo.GivenNames g
WHERE g.IsActive=1 AND (@NameType IS NULL OR g.NameType=@NameType)
AND (@Search IS NULL OR g.NormalisedName LIKE UPPER(LTRIM(RTRIM(@Search)))+N'%' COLLATE Latin1_General_100_CI_AI_SC OR g.DisplayName LIKE @Search+N'%')
), UsageChoice AS
(
SELECT
u.*,
l.LocaleCode,
l.DisplayName AS LocaleDisplayName,
ROW_NUMBER() OVER (PARTITION BY u.GivenNameID ORDER BY
CASE WHEN @BirthYear IS NOT NULL AND @BirthYear BETWEEN u.BirthYearFrom AND u.BirthYearTo THEN 0 ELSE 1 END,
CASE WHEN @BirthYear IS NULL THEN ABS(1960 - ((u.BirthYearFrom + u.BirthYearTo) / 2)) ELSE ABS(@BirthYear - ((u.BirthYearFrom + u.BirthYearTo) / 2)) END,
u.UsageWeight DESC) AS rn
FROM dbo.NameUsages u
INNER JOIN CandidateNames candidates ON candidates.GivenNameID=u.GivenNameID
INNER JOIN dbo.NameLocales l ON l.NameLocaleID = u.NameLocaleID
WHERE u.IsActive = 1
AND (@NameLocaleID IS NULL OR u.NameLocaleID = @NameLocaleID)
),
Used AS
(
SELECT g.GivenNameID, COUNT(DISTINCT c.CharacterID) AS UsedCount,
SUM(CASE WHEN c.MatchType=N'Character' THEN 1 ELSE 0 END) AS PrimaryCount,
SUM(CASE WHEN c.MatchType=N'Alias' THEN 1 ELSE 0 END) AS AliasCount,
MAX(CASE WHEN c.CharacterTypeCode='animal' THEN 1 ELSE 0 END) AS HasAnimalAssociation,
CASE WHEN COUNT(DISTINCT c.CharacterTypeCode)=1 THEN MIN(c.CharacterTypeCode) END AS AssociationTypeCode,
CAST(N'' AS nvarchar(max)) AS UsedSummary
FROM CandidateNames g
INNER JOIN
(
SELECT c.CharacterID, c.ProjectID, c.CharacterName AS MatchedName, c.CharacterTypeCode, N'Character' AS MatchType
FROM dbo.Characters c WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID
UNION
SELECT c.CharacterID, c.ProjectID, ca.Alias, c.CharacterTypeCode, N'Alias'
FROM dbo.CharacterAliases ca JOIN dbo.Characters c ON c.CharacterID=ca.CharacterID
WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID
AND UPPER(LTRIM(RTRIM(ca.Alias))) COLLATE Latin1_General_100_CI_AI_SC <> UPPER(LTRIM(RTRIM(c.CharacterName)))
) c ON UPPER(LTRIM(RTRIM(c.MatchedName))) = g.NormalisedName COLLATE Latin1_General_100_CI_AI_SC
GROUP BY g.GivenNameID
),
Related AS
(
SELECT x.GivenNameID,
STRING_AGG(CONVERT(nvarchar(max), x.DisplayName), N', ') AS RelatedForms
FROM
(
SELECT r.FromGivenNameID AS GivenNameID, t.DisplayName
FROM dbo.NameRelationships r
INNER JOIN dbo.GivenNames t ON t.GivenNameID = r.ToGivenNameID
WHERE r.IsActive = 1
UNION
SELECT r.ToGivenNameID AS GivenNameID, f.DisplayName
FROM dbo.NameRelationships r
INNER JOIN dbo.GivenNames f ON f.GivenNameID = r.FromGivenNameID
WHERE r.IsActive = 1 AND r.IsBidirectional = 1
) x
GROUP BY x.GivenNameID
),
Filtered AS
(
SELECT
g.GivenNameID, g.GivenNameKey, g.DisplayName, g.NormalisedName, g.NameType, g.IsWordAmbiguous,
u.MaleWeight, u.FemaleWeight, u.UsageWeight, u.Confidence, u.BirthYearFrom, u.BirthYearTo, u.LocaleCode, u.LocaleDisplayName, u.SourceType,
rel.RelatedForms,
COALESCE(used.UsedSummary, N'') AS UsedSummary,
COALESCE(used.UsedCount, 0) AS UsedCount,
COALESCE(used.PrimaryCount,0) AS PrimaryCount, COALESCE(used.AliasCount,0) AS AliasCount, COALESCE(used.HasAnimalAssociation,0) AS HasAnimalAssociation, used.AssociationTypeCode,
COUNT(1) OVER() AS TotalRows
FROM CandidateNames g
LEFT JOIN UsageChoice u ON u.GivenNameID = g.GivenNameID AND u.rn = 1
LEFT JOIN Used used ON used.GivenNameID = g.GivenNameID
LEFT JOIN Related rel ON rel.GivenNameID = g.GivenNameID
WHERE g.IsActive = 1
AND (@Search IS NULL OR g.NormalisedName LIKE UPPER(LTRIM(RTRIM(@Search))) + N'%' COLLATE Latin1_General_100_CI_AI_SC OR g.DisplayName LIKE @Search + N'%')
AND (@NameType IS NULL OR g.NameType = @NameType)
AND (@MinimumUsage IS NULL OR u.UsageWeight >= @MinimumUsage)
AND (@UsedOnly IS NULL OR (@UsedOnly = 1 AND COALESCE(used.UsedCount, 0) > 0) OR (@UsedOnly = 0 AND COALESCE(used.UsedCount, 0) = 0))
AND (
@GenderPreference IS NULL
OR @GenderThreshold IS NULL
OR (@GenderPreference = N'Female' AND u.FemaleWeight >= @GenderThreshold)
OR (@GenderPreference = N'Male' AND u.MaleWeight >= @GenderThreshold)
OR (@GenderPreference = N'Mixed' AND u.MaleWeight >= (1 - @GenderThreshold) AND u.FemaleWeight >= (1 - @GenderThreshold))
)
)
SELECT *
FROM Filtered
ORDER BY
CASE WHEN @Search IS NOT NULL AND NormalisedName = UPPER(LTRIM(RTRIM(@Search))) COLLATE Latin1_General_100_CI_AI_SC THEN 0 ELSE 1 END,
UsageWeight DESC,
DisplayName
OFFSET (@Page - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY
OPTION (RECOMPILE);
END;
GO

View File

@ -4,7 +4,7 @@
window.PlotDirectorContextLifecycles.names={
mount(node,{paneId}){
const host=node.querySelector('[data-context-names]'),root=host?.querySelector('[data-names-workspace]');if(!root)return;
const book=host.dataset.book,key=book+':'+paneId;
const book=host.dataset.book,key=root.dataset.project+':'+paneId;
root.dataset.searchUrl='/Writing/Context/Names/Search?contextBookId='+encodeURIComponent(book);
root.dataset.detailsUrl='/Writing/Context/Names/Details?contextBookId='+encodeURIComponent(book);
// A pane owns its reference-tool state. No manuscript-focus commands or SignalR connections.