diff --git a/Docs/Investigations/2026-11-04-word-companion-contracts.md b/Docs/Investigations/2026-11-04-word-companion-contracts.md new file mode 100644 index 00000000..b48eb225 --- /dev/null +++ b/Docs/Investigations/2026-11-04-word-companion-contracts.md @@ -0,0 +1,1279 @@ +# Current Companion data contracts + +Source inventory, not a new protocol. Names/types below are C# declarations; MVC/SignalR use the configured/default JSON conventions. JavaScript tolerates several Pascal/camel variants. Computed properties are labelled. Exact defaults/validation remain in the linked source. HTTP routes are in `2026-11-04-word-companion-http-api.csv`. + +## PlotLine/Models/WordCompanionApiModels.cs + +### WordCompanionProjectDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L3) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `string Title` | stored/request/response field | + +### WordCompanionProjectsResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L9) + +| Property declaration | Kind | +|---|---| +| `IReadOnlyList Projects` | stored/request/response field | + +### WordCompanionBookDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L14) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `string Title` | stored/request/response field | +| `string? Subtitle` | stored/request/response field | +| `string DisplayTitle` | computed | +| `int SortOrder` | stored/request/response field | +| `bool UsesExplicitScenes` | stored/request/response field | + +### WordCompanionBooksResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L24) + +| Property declaration | Kind | +|---|---| +| `IReadOnlyList Books` | stored/request/response field | + +### WordCompanionSceneStructureDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L29) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `string Title` | stored/request/response field | +| `int SortOrder` | stored/request/response field | +| `string RevisionStatus` | stored/request/response field | +| `int? EstimatedWords` | stored/request/response field | +| `int? ActualWords` | stored/request/response field | + +### WordCompanionChapterStructureDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L39) + +| Property declaration | Kind | +|---|---| +| `int ChapterId` | stored/request/response field | +| `string Title` | stored/request/response field | +| `int SortOrder` | stored/request/response field | +| `IReadOnlyList Scenes` | stored/request/response field | + +### WordCompanionBookStructureResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L47) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `IReadOnlyList Chapters` | stored/request/response field | + +### WordCompanionChaptersResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L53) + +| Property declaration | Kind | +|---|---| +| `IReadOnlyList Chapters` | stored/request/response field | + +### WordCompanionChapterDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L58) + +| Property declaration | Kind | +|---|---| +| `int ChapterId` | stored/request/response field | +| `string Title` | stored/request/response field | +| `int SortOrder` | stored/request/response field | + +### WordCompanionResolveSceneRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L65) + +| Property declaration | Kind | +|---|---| +| `string? ChapterTitle` | stored/request/response field | +| `string? SceneTitle` | stored/request/response field | + +### WordCompanionResolveSceneResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L71) + +| Property declaration | Kind | +|---|---| +| `bool Matched` | stored/request/response field | +| `bool ChapterMatched` | stored/request/response field | +| `int? ChapterId` | stored/request/response field | +| `int? SceneId` | stored/request/response field | +| `string? MatchType` | stored/request/response field | +| `int? BookId` | stored/request/response field | +| `string? ChapterTitleSearched` | stored/request/response field | +| `string? SceneTitleSearched` | stored/request/response field | +| `int? AvailableChapterCount` | stored/request/response field | +| `int? AvailableSceneCount` | stored/request/response field | +| `bool BookAccessible` | stored/request/response field | + +### WordCompanionLinkItemDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L86) + +| Property declaration | Kind | +|---|---| +| `int CharacterId` | stored/request/response field | +| `int AssetId` | stored/request/response field | +| `int LocationId` | stored/request/response field | +| `string Name` | stored/request/response field | +| `bool Linked` | stored/request/response field | + +### WordCompanionSceneCompanionResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L95) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `int ChapterId` | stored/request/response field | +| `string ChapterTitle` | stored/request/response field | +| `string SceneTitle` | stored/request/response field | +| `int? ActualWords` | stored/request/response field | +| `int? EstimatedWords` | stored/request/response field | +| `string? WritingBrief` | stored/request/response field | +| `bool Blocked` | stored/request/response field | +| `string? BlockedReason` | stored/request/response field | +| `int? PrimaryLocationId` | stored/request/response field | +| `IReadOnlyList Characters` | stored/request/response field | +| `IReadOnlyList Assets` | stored/request/response field | +| `IReadOnlyList Locations` | stored/request/response field | + +### WordCompanionSyncSceneRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L112) + +| Property declaration | Kind | +|---|---| +| `string? ChapterTitle` | stored/request/response field | +| `int? ChapterSortOrder` | stored/request/response field | +| `string? SceneTitle` | stored/request/response field | +| `int? SceneSortOrder` | stored/request/response field | +| `int ActualWords` | stored/request/response field | +| `string? DocumentId` | stored/request/response field | +| `string? ContentHash` | stored/request/response field | + +### WordCompanionSyncSceneResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L123) + +| Property declaration | Kind | +|---|---| +| `int ChapterId` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `bool ChapterCreated` | stored/request/response field | +| `bool SceneCreated` | stored/request/response field | +| `bool ActualWordsUpdated` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionCreateSceneRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L133) + +| Property declaration | Kind | +|---|---| +| `string? SceneTitle` | stored/request/response field | + +### WordCompanionCreateSceneResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L138) + +| Property declaration | Kind | +|---|---| +| `int ChapterId` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionCreateChapterRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L145) + +| Property declaration | Kind | +|---|---| +| `string? Title` | stored/request/response field | +| `int? SortOrder` | stored/request/response field | + +### WordCompanionCreateChapterResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L151) + +| Property declaration | Kind | +|---|---| +| `int ChapterId` | stored/request/response field | +| `string Title` | stored/request/response field | +| `int SortOrder` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionSyncManuscriptRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L159) + +| Property declaration | Kind | +|---|---| +| `string? DocumentId` | stored/request/response field | +| `IReadOnlyList Chapters` | stored/request/response field | + +### WordCompanionSyncChapterRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L165) + +| Property declaration | Kind | +|---|---| +| `string? Title` | stored/request/response field | +| `int? SortOrder` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `IReadOnlyList Scenes` | stored/request/response field | + +### WordCompanionSyncManuscriptSceneRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L173) + +| Property declaration | Kind | +|---|---| +| `string? Title` | stored/request/response field | +| `int? SortOrder` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `string? ContentHash` | stored/request/response field | + +### WordCompanionSyncManuscriptResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L181) + +| Property declaration | Kind | +|---|---| +| `int ChaptersCreated` | stored/request/response field | +| `int ChaptersUpdated` | stored/request/response field | +| `int ScenesCreated` | stored/request/response field | +| `int ScenesUpdated` | stored/request/response field | +| `IReadOnlyList ItemsNotMatched` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionUpdateSceneLinksRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L191) + +| Property declaration | Kind | +|---|---| +| `IReadOnlyList CharacterIds` | stored/request/response field | +| `IReadOnlyList AssetIds` | stored/request/response field | +| `IReadOnlyList LocationIds` | stored/request/response field | +| `int? PrimaryLocationId` | stored/request/response field | + +### WordCompanionUpdateSceneLinksResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L199) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `int CharactersUpdated` | stored/request/response field | +| `int AssetsUpdated` | stored/request/response field | +| `int LocationsUpdated` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionUpdateWordCountRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L208) + +| Property declaration | Kind | +|---|---| +| `int? ActualWords` | stored/request/response field | +| `int? ActualWordCount` | stored/request/response field | +| `DateTime? LastWorkedOn` | stored/request/response field | + +### WordCompanionUpdateWordCountResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L215) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `int ActualWords` | stored/request/response field | +| `DateTime? LastWorkedOn` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionRuntimeSceneWordCountRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L223) + +| Property declaration | Kind | +|---|---| +| `Guid DocumentGuid` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `int ChapterId` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `int WordCount` | stored/request/response field | + +### WordCompanionRuntimeCurrentSceneRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L232) + +| Property declaration | Kind | +|---|---| +| `Guid DocumentGuid` | stored/request/response field | +| `int ProjectId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `int ChapterId` | stored/request/response field | +| `int SceneId` | stored/request/response field | + +### WordCompanionRuntimeCurrentSceneResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L241) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `int ChapterId` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `string SceneUrl` | stored/request/response field | +| `StoryPosition? Position` | computed | + +### WordCompanionRuntimeCharacterAliasDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L251) + +| Property declaration | Kind | +|---|---| +| `int CharacterId` | stored/request/response field | +| `string Name` | stored/request/response field | +| `string MatchText` | stored/request/response field | +| `bool IsDisplayName` | stored/request/response field | + +### WordCompanionRuntimeCharacterAliasResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L259) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `IReadOnlyList Characters` | stored/request/response field | + +### WordCompanionRuntimeCharacterSuggestionsRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L265) + +| Property declaration | Kind | +|---|---| +| `Guid DocumentGuid` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `IReadOnlyList CharacterIds` | stored/request/response field | + +### WordCompanionRuntimeCharacterSuggestionsResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L272) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `int CreatedCount` | stored/request/response field | +| `int SkippedCount` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionRuntimeAssetAliasDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L280) + +| Property declaration | Kind | +|---|---| +| `int AssetId` | stored/request/response field | +| `string Name` | stored/request/response field | +| `string MatchText` | stored/request/response field | +| `bool IsDisplayName` | stored/request/response field | + +### WordCompanionRuntimeAssetAliasResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L288) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `IReadOnlyList Assets` | stored/request/response field | + +### WordCompanionRuntimeAssetSuggestionsRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L294) + +| Property declaration | Kind | +|---|---| +| `Guid DocumentGuid` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `IReadOnlyList AssetIds` | stored/request/response field | + +### WordCompanionRuntimeAssetSuggestionsResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L301) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `int CreatedCount` | stored/request/response field | +| `int SkippedCount` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionRuntimeLocationAliasDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L309) + +| Property declaration | Kind | +|---|---| +| `int LocationId` | stored/request/response field | +| `int? ParentLocationId` | stored/request/response field | +| `string Name` | stored/request/response field | +| `string LocationPath` | stored/request/response field | +| `string MatchText` | stored/request/response field | +| `bool IsDisplayName` | stored/request/response field | +| `bool ExcludeFromCompanionDetection` | stored/request/response field | +| `int DetectionPriority` | stored/request/response field | + +### WordCompanionRuntimeLocationAliasResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L321) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `IReadOnlyList Locations` | stored/request/response field | + +### WordCompanionRuntimeLocationSuggestionsRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L327) + +| Property declaration | Kind | +|---|---| +| `Guid DocumentGuid` | stored/request/response field | +| `int SceneId` | stored/request/response field | +| `IReadOnlyList LocationIds` | stored/request/response field | + +### WordCompanionRuntimeLocationSuggestionsResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L334) + +| Property declaration | Kind | +|---|---| +| `int SceneId` | stored/request/response field | +| `int CreatedCount` | stored/request/response field | +| `int SkippedCount` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionManuscriptDocumentDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L342) + +| Property declaration | Kind | +|---|---| +| `int ManuscriptDocumentId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `int ProjectId` | stored/request/response field | +| `Guid DocumentGuid` | stored/request/response field | +| `int BindingVersion` | stored/request/response field | +| `DateTime CreatedUtc` | stored/request/response field | +| `DateTime? LastSyncUtc` | stored/request/response field | +| `DateTime? LastOpenedUtc` | stored/request/response field | +| `bool IsActive` | stored/request/response field | + +### WordCompanionManuscriptBookResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L355) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `WordCompanionManuscriptDocumentDto? ManuscriptDocument` | stored/request/response field | + +### WordCompanionRuntimeBookResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L361) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `string ProjectTitle` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `string BookTitle` | stored/request/response field | +| `string? BookSubtitle` | stored/request/response field | +| `bool UsesExplicitScenes` | stored/request/response field | +| `DateTime? LastSyncUtc` | stored/request/response field | +| `WordCompanionManuscriptDocumentDto ManuscriptDocument` | stored/request/response field | + +### WordCompanionManuscriptLinkRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L373) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `Guid? DocumentGuid` | stored/request/response field | + +### WordCompanionManuscriptLinkResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L379) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `WordCompanionManuscriptDocumentDto ManuscriptDocument` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionManuscriptUnlinkRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L386) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `Guid? DocumentGuid` | stored/request/response field | + +### WordCompanionManuscriptUnlinkResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L392) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `int ManuscriptDocumentId` | stored/request/response field | +| `int ChaptersUnlinked` | stored/request/response field | +| `int ScenesUnlinked` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionCreateBookRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L401) + +| Property declaration | Kind | +|---|---| +| `string? Title` | stored/request/response field | + +### WordCompanionCreateBookResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L406) + +| Property declaration | Kind | +|---|---| +| `int BookId` | stored/request/response field | +| `string Title` | stored/request/response field | +| `string? Subtitle` | stored/request/response field | +| `int SortOrder` | stored/request/response field | +| `bool UsesExplicitScenes` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionManuscriptImportSceneRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L416) + +| Property declaration | Kind | +|---|---| +| `string? Title` | stored/request/response field | +| `int? SortOrder` | stored/request/response field | +| `int WordCount` | stored/request/response field | + +### WordCompanionManuscriptImportChapterRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L423) + +| Property declaration | Kind | +|---|---| +| `string? Title` | stored/request/response field | +| `int? SortOrder` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `IReadOnlyList Scenes` | stored/request/response field | + +### WordCompanionManuscriptAnalyseRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L431) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `Guid? DocumentGuid` | stored/request/response field | +| `int ChapterCount` | stored/request/response field | +| `int SceneCount` | stored/request/response field | +| `int WordCount` | stored/request/response field | + +### WordCompanionManuscriptAnalyseResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L441) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `string ProjectTitle` | stored/request/response field | +| `string BookTitle` | stored/request/response field | +| `string? BookSubtitle` | stored/request/response field | +| `bool UsesExplicitScenes` | stored/request/response field | +| `int ChapterCount` | stored/request/response field | +| `int SceneCount` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `int ExistingChapterCount` | stored/request/response field | +| `int ExistingSceneCount` | stored/request/response field | +| `int LinkedChapterCount` | stored/request/response field | +| `bool CanImport` | stored/request/response field | +| `bool RequiresReplaceConfirmation` | stored/request/response field | +| `string Message` | stored/request/response field | + +### WordCompanionManuscriptImportRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L460) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `Guid? DocumentGuid` | stored/request/response field | +| `int BindingVersion` | stored/request/response field | +| `bool ReplacePlanned` | stored/request/response field | +| `IReadOnlyList Chapters` | stored/request/response field | + +### WordCompanionManuscriptImportResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L470) + +| Property declaration | Kind | +|---|---| +| `bool Imported` | stored/request/response field | +| `bool RequiresReplaceConfirmation` | stored/request/response field | +| `string Message` | stored/request/response field | +| `int ProjectId` | stored/request/response field | +| `int BookId` | stored/request/response field | +| `int ChaptersCreated` | stored/request/response field | +| `int ScenesCreated` | stored/request/response field | +| `int ArchivedChapters` | stored/request/response field | +| `int ArchivedScenes` | stored/request/response field | +| `WordCompanionManuscriptDocumentDto? ManuscriptDocument` | stored/request/response field | + +### WordCompanionCharacterCandidateDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L484) + +| Property declaration | Kind | +|---|---| +| `string Text` | stored/request/response field | +| `int MentionCount` | stored/request/response field | +| `string Confidence` | stored/request/response field | +| `int QualityScore` | stored/request/response field | +| `string Category` | stored/request/response field | +| `string Reason` | stored/request/response field | +| `bool IsExistingCharacterMatch` | stored/request/response field | + +### WordCompanionDiscoverCharactersRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L495) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `string? DocumentText` | stored/request/response field | +| `bool IncludeExcluded` | stored/request/response field | + +### WordCompanionDiscoverCharactersResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L502) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `IReadOnlyList Candidates` | stored/request/response field | + +### WordCompanionCreateDiscoveredCharactersRequest + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L508) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `IReadOnlyList CandidateNames` | stored/request/response field | + +### WordCompanionCreatedCharacterDto + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L514) + +| Property declaration | Kind | +|---|---| +| `int CharacterId` | stored/request/response field | +| `string Name` | stored/request/response field | +| `bool Created` | stored/request/response field | + +### WordCompanionCreateDiscoveredCharactersResponse + +[Declaration](../../PlotLine/Models/WordCompanionApiModels.cs#L521) + +| Property declaration | Kind | +|---|---| +| `int ProjectId` | stored/request/response field | +| `int CreatedCount` | stored/request/response field | +| `int SkippedCount` | stored/request/response field | +| `IReadOnlyList Characters` | stored/request/response field | +| `string Message` | stored/request/response field | + +## PlotLine/Models/WordCompanionPresenceModels.cs + +### WordCompanionPresenceRegistration + +[Declaration](../../PlotLine/Models/WordCompanionPresenceModels.cs#L10) + +| Property declaration | Kind | +|---|---| +| `int? UserID` | stored/request/response field | +| `string? CompanionVersion` | stored/request/response field | +| `string? MachineName` | stored/request/response field | +| `bool DocumentOpen` | stored/request/response field | +| `string? CurrentDocumentName` | stored/request/response field | +| `int? LinkedProjectID` | stored/request/response field | +| `int? LinkedBookID` | stored/request/response field | + +### WordCompanionPresenceHeartbeat + +[Declaration](../../PlotLine/Models/WordCompanionPresenceModels.cs#L21) + +| Property declaration | Kind | +|---|---| +| `string? CompanionVersion` | stored/request/response field | +| `string? MachineName` | stored/request/response field | +| `bool DocumentOpen` | stored/request/response field | +| `string? CurrentDocumentName` | stored/request/response field | +| `int? LinkedProjectID` | stored/request/response field | +| `int? LinkedBookID` | stored/request/response field | + +### WordCompanionPresenceStatus + +[Declaration](../../PlotLine/Models/WordCompanionPresenceModels.cs#L31) + +| Property declaration | Kind | +|---|---| +| `int UserID` | stored/request/response field | +| `bool IsConnected` | stored/request/response field | +| `string Status` | stored/request/response field | +| `string? CompanionVersion` | stored/request/response field | +| `string? MachineName` | stored/request/response field | +| `bool DocumentOpen` | stored/request/response field | +| `string? CurrentDocumentName` | stored/request/response field | +| `int? LinkedProjectID` | stored/request/response field | +| `int? LinkedBookID` | stored/request/response field | +| `StoryPosition? CurrentStoryPosition` | stored/request/response field | +| `DateTime? ConnectedUtc` | stored/request/response field | +| `DateTime? LastHeartbeatUtc` | stored/request/response field | + +## PlotLine/Models/WritingWorkspacePresenceModels.cs + +### WritingWorkspaceScope + +[Declaration](../../PlotLine/Models/WritingWorkspacePresenceModels.cs#L20) + +| Property declaration | Kind | +|---|---| +| `int? ProjectID` | stored/request/response field | +| `int? BookID` | stored/request/response field | + +### WritingWindowRegistration + +[Declaration](../../PlotLine/Models/WritingWorkspacePresenceModels.cs#L26) + +| Property declaration | Kind | +|---|---| +| `string? BrowserWindowID` | stored/request/response field | +| `int? ProjectID` | stored/request/response field | +| `int? BookID` | stored/request/response field | +| `string? CurrentRoute` | stored/request/response field | +| `string? WritingRole` | stored/request/response field | +| `string? DisplayLabel` | stored/request/response field | + +### WritingWindowHeartbeat + +[Declaration](../../PlotLine/Models/WritingWorkspacePresenceModels.cs#L36) + +| Property declaration | Kind | +|---|---| +| `string? BrowserWindowID` | stored/request/response field | +| `int? ProjectID` | stored/request/response field | +| `int? BookID` | stored/request/response field | +| `string? CurrentRoute` | stored/request/response field | +| `string? WritingRole` | stored/request/response field | +| `string? DisplayLabel` | stored/request/response field | + +### WritingWindowPresence + +[Declaration](../../PlotLine/Models/WritingWorkspacePresenceModels.cs#L46) + +| Property declaration | Kind | +|---|---| +| `string BrowserWindowID` | stored/request/response field | +| `int UserID` | stored/request/response field | +| `int? ProjectID` | stored/request/response field | +| `int? BookID` | stored/request/response field | +| `string CurrentRoute` | stored/request/response field | +| `string WritingRole` | stored/request/response field | +| `string? DisplayLabel` | stored/request/response field | +| `bool IsActive` | stored/request/response field | +| `DateTime ConnectedUtc` | stored/request/response field | +| `DateTime LastSeenUtc` | stored/request/response field | + +### WritingWorkspaceStatus + +[Declaration](../../PlotLine/Models/WritingWorkspacePresenceModels.cs#L60) + +| Property declaration | Kind | +|---|---| +| `int UserID` | stored/request/response field | +| `int? ProjectID` | stored/request/response field | +| `int? BookID` | stored/request/response field | +| `bool WordCompanionConnected` | stored/request/response field | +| `bool WordDocumentOpen` | stored/request/response field | +| `int? WordProjectID` | stored/request/response field | +| `int? WordBookID` | stored/request/response field | +| `StoryPosition? CurrentStoryPosition` | stored/request/response field | +| `IReadOnlyList Windows` | stored/request/response field | +| `WritingWindowPresence? Launcher` | stored/request/response field | +| `WritingWindowPresence? Context` | stored/request/response field | +| `WritingWindowPresence? Intent` | stored/request/response field | +| `bool ContextOpen` | computed | +| `bool IntentOpen` | computed | + +## PlotLine/Models/ManuscriptScanModels.cs + +### ManuscriptScanCommand + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L25) + +| Property declaration | Kind | +|---|---| +| `Guid ScanID` | stored/request/response field | +| `int UserID` | stored/request/response field | +| `int OnboardingID` | stored/request/response field | +| `int ProjectID` | stored/request/response field | +| `int BookID` | stored/request/response field | +| `DateTime RequestedUtc` | stored/request/response field | + +### ManuscriptScanProgress + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L35) + +| Property declaration | Kind | +|---|---| +| `int? UserID` | stored/request/response field | +| `int OnboardingID` | stored/request/response field | +| `string Message` | stored/request/response field | +| `int? PercentComplete` | stored/request/response field | +| `int ChapterCount` | stored/request/response field | +| `int SceneCount` | stored/request/response field | +| `int CharacterCandidateCount` | stored/request/response field | +| `int TotalWordCount` | stored/request/response field | + +### ManuscriptScanFailure + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L47) + +| Property declaration | Kind | +|---|---| +| `int? UserID` | stored/request/response field | +| `int OnboardingID` | stored/request/response field | +| `string Message` | stored/request/response field | + +### ManuscriptScanChunk + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L54) + +| Property declaration | Kind | +|---|---| +| `Guid ScanID` | stored/request/response field | +| `int? UserID` | stored/request/response field | +| `int OnboardingID` | stored/request/response field | +| `int ChunkIndex` | stored/request/response field | +| `int TotalChunks` | stored/request/response field | +| `int TotalLength` | stored/request/response field | +| `string Payload` | stored/request/response field | + +### ManuscriptScanPreview + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L65) + +| Property declaration | Kind | +|---|---| +| `Guid PreviewID` | stored/request/response field | +| `int UserID` | stored/request/response field | +| `int OnboardingID` | stored/request/response field | +| `int ProjectID` | stored/request/response field | +| `int BookID` | stored/request/response field | +| `string Source` | stored/request/response field | +| `string? DocumentTitle` | stored/request/response field | +| `string? CompanionDocumentIdentifier` | stored/request/response field | +| `int TotalWordCount` | stored/request/response field | +| `int ChapterCount` | stored/request/response field | +| `int SceneCount` | stored/request/response field | +| `int CharacterCandidateCount` | stored/request/response field | +| `DateTime CreatedUtc` | stored/request/response field | +| `IReadOnlyList Chapters` | stored/request/response field | +| `IReadOnlyList Scenes` | stored/request/response field | +| `IReadOnlyList CharacterCandidates` | stored/request/response field | + +### ManuscriptScanChapterPreview + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L85) + +| Property declaration | Kind | +|---|---| +| `string TemporaryChapterKey` | stored/request/response field | +| `int ChapterNumber` | stored/request/response field | +| `string Title` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `string? ChapterText` | stored/request/response field | +| `int? StartPosition` | stored/request/response field | +| `int? ExistingChapterID` | stored/request/response field | +| `IReadOnlyList ParagraphMap` | stored/request/response field | +| `IReadOnlyList SourceParagraphs` | stored/request/response field | + +### ManuscriptScanParagraphMap + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L98) + +| Property declaration | Kind | +|---|---| +| `int StructuralParagraphOrdinal` | stored/request/response field | +| `int WordParagraphIndex` | stored/request/response field | +| `string Text` | stored/request/response field | + +### ManuscriptScanSourceParagraph + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L105) + +| Property declaration | Kind | +|---|---| +| `int WordParagraphIndex` | stored/request/response field | +| `string Text` | stored/request/response field | +| `bool IsBlank` | stored/request/response field | +| `bool IsChapterHeading` | stored/request/response field | +| `bool IsSceneHeading` | stored/request/response field | +| `bool IsSceneSeparator` | stored/request/response field | +| `bool IncludeInSourceText` | stored/request/response field | + +### ManuscriptScanScenePreview + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L116) + +| Property declaration | Kind | +|---|---| +| `string TemporarySceneKey` | stored/request/response field | +| `string TemporaryChapterKey` | stored/request/response field | +| `int SceneNumberWithinChapter` | stored/request/response field | +| `string? Title` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `string? OpeningTextPreview` | stored/request/response field | +| `int? StartPosition` | stored/request/response field | +| `int? ExistingSceneID` | stored/request/response field | + +### ManuscriptScanCharacterCandidatePreview + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L128) + +| Property declaration | Kind | +|---|---| +| `string TemporaryCharacterKey` | stored/request/response field | +| `string Name` | stored/request/response field | +| `int MentionCount` | stored/request/response field | +| `int QualityScore` | stored/request/response field | +| `string Category` | stored/request/response field | +| `string? Reason` | stored/request/response field | +| `int? ExistingCharacterID` | stored/request/response field | +| `bool IsExistingCharacterMatch` | stored/request/response field | +| `bool IsAutoResolvedExistingCharacter` | stored/request/response field | +| `string? SuggestedImportance` | stored/request/response field | +| `IReadOnlyList EvidenceScenes` | stored/request/response field | + +### ManuscriptScanCharacterEvidenceScene + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L143) + +| Property declaration | Kind | +|---|---| +| `int SceneID` | stored/request/response field | +| `int ChapterID` | stored/request/response field | +| `int ChapterNumber` | stored/request/response field | +| `int SceneNumber` | stored/request/response field | +| `int MentionCount` | stored/request/response field | +| `string? StructuralSummary` | stored/request/response field | + +### CoreImportBasicLocationReview + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L167) + +| Property declaration | Kind | +|---|---| +| `int CoreImportBasicLocationReviewID` | stored/request/response field | +| `Guid PreviewID` | stored/request/response field | +| `int UserID` | stored/request/response field | +| `int ProjectID` | stored/request/response field | +| `int BookID` | stored/request/response field | +| `int? BuildID` | stored/request/response field | +| `string Status` | stored/request/response field | +| `int RawObservationCount` | stored/request/response field | +| `int CandidateCount` | stored/request/response field | +| `DateTime CreatedUtc` | stored/request/response field | +| `DateTime UpdatedUtc` | stored/request/response field | +| `DateTime? CompletedUtc` | stored/request/response field | + +### CoreImportBasicLocationCandidate + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L183) + +| Property declaration | Kind | +|---|---| +| `int CoreImportBasicLocationCandidateID` | stored/request/response field | +| `int CoreImportBasicLocationReviewID` | stored/request/response field | +| `string StableKey` | stored/request/response field | +| `string ProposedName` | stored/request/response field | +| `string PreferredName` | stored/request/response field | +| `string KnownNamesJson` | stored/request/response field | +| `int? ParentLocationID` | stored/request/response field | +| `string? ParentCandidateKey` | stored/request/response field | +| `int? ExistingLocationID` | stored/request/response field | +| `string Action` | stored/request/response field | +| `int? SameAsLocationID` | stored/request/response field | +| `string? SameAsCandidateKey` | stored/request/response field | +| `int? ResultLocationID` | stored/request/response field | +| `int FirstChapterNumber` | stored/request/response field | +| `int FirstSceneNumber` | stored/request/response field | +| `int FirstOccurrenceIndex` | stored/request/response field | +| `int ObservationCount` | stored/request/response field | +| `int SortOrder` | stored/request/response field | +| `DateTime CreatedUtc` | stored/request/response field | +| `DateTime UpdatedUtc` | stored/request/response field | +| `IReadOnlyList Evidence` | stored/request/response field | + +### CoreImportBasicLocationEvidence + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L208) + +| Property declaration | Kind | +|---|---| +| `int CoreImportBasicLocationEvidenceID` | stored/request/response field | +| `int CoreImportBasicLocationCandidateID` | stored/request/response field | +| `int SceneID` | stored/request/response field | +| `int ChapterID` | stored/request/response field | +| `int ChapterNumber` | stored/request/response field | +| `int SceneNumber` | stored/request/response field | +| `int OccurrenceIndex` | stored/request/response field | +| `string EvidenceText` | stored/request/response field | +| `int SortOrder` | stored/request/response field | + +### CoreImportBasicLocationDecision + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L221) + +| Property declaration | Kind | +|---|---| +| `string StableKey` | stored/request/response field | +| `string PreferredName` | stored/request/response field | +| `string Action` | stored/request/response field | +| `int? ParentLocationID` | stored/request/response field | +| `string? ParentCandidateKey` | stored/request/response field | +| `int? SameAsLocationID` | stored/request/response field | +| `string? SameAsCandidateKey` | stored/request/response field | + +### CoreImportBasicLocationDiscoveryResult + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L232) + +| Property declaration | Kind | +|---|---| +| `int RawObservationCount` | stored/request/response field | +| `int ExcludedObservationCount` | stored/request/response field | +| `IReadOnlyList Candidates` | stored/request/response field | + +### ManuscriptScanState + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L239) + +| Property declaration | Kind | +|---|---| +| `Guid? ScanID` | stored/request/response field | +| `string Status` | stored/request/response field | +| `string ReviewStatus` | stored/request/response field | +| `string Message` | stored/request/response field | +| `int? PercentComplete` | stored/request/response field | +| `int ChapterCount` | stored/request/response field | +| `int SceneCount` | stored/request/response field | +| `int CharacterCandidateCount` | stored/request/response field | +| `int TotalWordCount` | stored/request/response field | +| `Guid? PreviewID` | stored/request/response field | +| `DateTime? UpdatedUtc` | stored/request/response field | + +### ManuscriptScanReviewDecision + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L254) + +| Property declaration | Kind | +|---|---| +| `Guid PreviewID` | stored/request/response field | +| `string Status` | stored/request/response field | +| `bool GenerateSceneTitles` | stored/request/response field | +| `DateTime UpdatedUtc` | stored/request/response field | +| `IReadOnlyList Chapters` | stored/request/response field | +| `IReadOnlyList Scenes` | stored/request/response field | +| `IReadOnlyList Characters` | stored/request/response field | + +### ManuscriptScanChapterReviewDecision + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L265) + +| Property declaration | Kind | +|---|---| +| `string TemporaryChapterKey` | stored/request/response field | +| `bool Include` | stored/request/response field | +| `string Title` | stored/request/response field | +| `int ChapterNumber` | stored/request/response field | + +### ManuscriptScanSceneReviewDecision + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L273) + +| Property declaration | Kind | +|---|---| +| `string TemporarySceneKey` | stored/request/response field | +| `string TemporaryChapterKey` | stored/request/response field | +| `bool Include` | stored/request/response field | +| `string? Title` | stored/request/response field | +| `int SceneNumberWithinChapter` | stored/request/response field | +| `bool AllowZeroWords` | stored/request/response field | + +### ManuscriptScanCharacterReviewDecision + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L283) + +| Property declaration | Kind | +|---|---| +| `string TemporaryCharacterKey` | stored/request/response field | +| `bool Include` | stored/request/response field | +| `string Name` | stored/request/response field | +| `string Category` | stored/request/response field | +| `int? ExistingCharacterID` | stored/request/response field | +| `string? AliasTargetTemporaryCharacterKey` | stored/request/response field | +| `string? SexHint` | stored/request/response field | + +### OnboardingManuscriptBuildResult + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L294) + +| Property declaration | Kind | +|---|---| +| `int BuildID` | stored/request/response field | +| `Guid PreviewID` | stored/request/response field | +| `int ProjectID` | stored/request/response field | +| `int BookID` | stored/request/response field | +| `int? ManuscriptDocumentID` | stored/request/response field | +| `string Status` | stored/request/response field | +| `string MarkerStatus` | stored/request/response field | +| `int ChaptersCreated` | stored/request/response field | +| `int ScenesCreated` | stored/request/response field | +| `int CharactersCreated` | stored/request/response field | +| `int CharactersReused` | stored/request/response field | +| `int SceneAppearancesCreated` | stored/request/response field | +| `bool AlreadyBuilt` | stored/request/response field | +| `string Message` | stored/request/response field | +| `IReadOnlyList ChapterMappings` | stored/request/response field | +| `IReadOnlyList SceneMappings` | stored/request/response field | +| `IReadOnlyList CharacterMappings` | stored/request/response field | +| `IReadOnlyList ChapterMarkerInstructions` | stored/request/response field | +| `IReadOnlyList SceneMarkerInstructions` | stored/request/response field | +| `IReadOnlyList SceneStructure` | stored/request/response field | +| `string? MarkerWarning` | stored/request/response field | + +### OnboardingSceneStructureSummary + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L319) + +| Property declaration | Kind | +|---|---| +| `string TemporaryChapterKey` | stored/request/response field | +| `int ChapterNumber` | stored/request/response field | +| `string ChapterTitle` | stored/request/response field | +| `int SceneCount` | stored/request/response field | +| `int WordCount` | stored/request/response field | +| `IReadOnlyList Scenes` | stored/request/response field | + +### OnboardingSceneStructureDetail + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L329) + +| Property declaration | Kind | +|---|---| +| `int SceneNumberWithinChapter` | stored/request/response field | +| `string Title` | stored/request/response field | +| `string DisplayTitle` | computed | +| `int WordCount` | stored/request/response field | +| `string? StructuralSummary` | stored/request/response field | +| `int StartParagraph` | stored/request/response field | +| `int EndParagraph` | stored/request/response field | + +### OnboardingBuildChapterMap + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L340) + +| Property declaration | Kind | +|---|---| +| `string TemporaryChapterKey` | stored/request/response field | +| `int ChapterID` | stored/request/response field | + +### OnboardingBuildSceneMap + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L346) + +| Property declaration | Kind | +|---|---| +| `string TemporarySceneKey` | stored/request/response field | +| `int SceneID` | stored/request/response field | +| `string? SceneTitle` | stored/request/response field | +| `string? SceneTitleSource` | stored/request/response field | + +### OnboardingBuildCharacterMap + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L354) + +| Property declaration | Kind | +|---|---| +| `string TemporaryCharacterKey` | stored/request/response field | +| `int CharacterID` | stored/request/response field | +| `bool Created` | stored/request/response field | + +### OnboardingBuildMarkerInstruction + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L361) + +| Property declaration | Kind | +|---|---| +| `string TemporaryKey` | stored/request/response field | +| `int EntityID` | stored/request/response field | +| `int WordParagraphIndex` | stored/request/response field | +| `string MarkerTag` | stored/request/response field | +| `string MarkerTitle` | stored/request/response field | +| `string MarkerPrefix` | stored/request/response field | + +### OnboardingBuildProgress + +[Declaration](../../PlotLine/Models/ManuscriptScanModels.cs#L371) + +| Property declaration | Kind | +|---|---| +| `string Status` | stored/request/response field | +| `string Message` | stored/request/response field | +| `int? PercentComplete` | stored/request/response field | +| `int ChaptersCreated` | stored/request/response field | +| `int ScenesCreated` | stored/request/response field | +| `int CharactersCreated` | stored/request/response field | +| `int SceneAppearancesCreated` | stored/request/response field | +| `Guid? PreviewID` | stored/request/response field | +| `int? BuildID` | stored/request/response field | +| `string? MarkerStatus` | stored/request/response field | diff --git a/Docs/Investigations/2026-11-04-word-companion-database-evidence.json b/Docs/Investigations/2026-11-04-word-companion-database-evidence.json new file mode 100644 index 00000000..108af3c2 --- /dev/null +++ b/Docs/Investigations/2026-11-04-word-companion-database-evidence.json @@ -0,0 +1,554 @@ +{ + "database": "PlotDirector_Development", + "access": "read-only sys.procedures/sys.sql_modules/sys.sql_expression_dependencies SELECTs", + "authorDataRead": false, + "procedures": [ + { + "procedure": "ManuscriptDocument_GetByBook", + "definitionSha256": "4fff8c8f101b220c2c029ca7b5a9636f323e1b0ef247f0d389554b1a40d17106", + "latestDirectSource": "PlotLine/Sql/094_Phase16B_ManuscriptBindingLinkedStructures.sql", + "sourceLine": 87, + "directReferencedEntities": [ + "Books", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "ManuscriptDocument_GetByGuid", + "definitionSha256": "4dac77a1eea03100e6fa7c36e3a9bdefb799aa394b4320bd3e221240b639c72d", + "latestDirectSource": "PlotLine/Sql/094_Phase16B_ManuscriptBindingLinkedStructures.sql", + "sourceLine": 109, + "directReferencedEntities": [ + "Books", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "ManuscriptDocument_Save", + "definitionSha256": "e3b386fad5b804367578a06995c4268d080e9c0dba821a29544c2fce142d94ca", + "latestDirectSource": "PlotLine/Sql/094_Phase16B_ManuscriptBindingLinkedStructures.sql", + "sourceLine": 131, + "directReferencedEntities": [ + "Books", + "ManuscriptDocument_GetByBook", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "ManuscriptDocument_UnlinkBook", + "definitionSha256": "dc021845a41abc62fc19e126af9194ee0d961ec258dc46e56b72598cbbc6d673", + "latestDirectSource": "PlotLine/Sql/108_Phase16Q_ManuscriptUnlink.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "Books", + "Chapters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "Scenes" + ] + }, + { + "procedure": "ManuscriptDocument_UpdateLastOpened", + "definitionSha256": "e745b1f87c565218921587af1a823e4f63e0ecdad42d6c842d1fc3630351c0cf", + "latestDirectSource": "PlotLine/Sql/094_Phase16B_ManuscriptBindingLinkedStructures.sql", + "sourceLine": 206, + "directReferencedEntities": [ + "ManuscriptDocuments", + "ProjectUserAccess" + ] + }, + { + "procedure": "ManuscriptDocument_UpdateLastSync", + "definitionSha256": "8e4acb989910d3d89f5a1770bcb8870a5a9dfbf6c317690c29cadc2bedcebde4", + "latestDirectSource": "PlotLine/Sql/094_Phase16B_ManuscriptBindingLinkedStructures.sql", + "sourceLine": 188, + "directReferencedEntities": [ + "ManuscriptDocuments", + "ProjectUserAccess" + ] + }, + { + "procedure": "ManuscriptStructuralChapterSource_Save", + "definitionSha256": "85ea7ee2945eea4c684a600560c4e7f2efa1e2e7d83c92278b0b461b2b6922d0", + "latestDirectSource": "PlotLine/Sql/166_Phase26B_StructuralPovAudit.sql", + "sourceLine": 18, + "directReferencedEntities": [], + "dependencyMetadata": "Not requested for these two supplementary source writers; source path inspected." + }, + { + "procedure": "Onboarding_ManuscriptBuild_Create", + "definitionSha256": "0abfdf21345b8a4e3489b8f0b01f105ad6107f909256d49deb15c877517a88a3", + "latestDirectSource": "PlotLine/Sql/162_Phase25G_CoreImportSceneTitles.sql", + "sourceLine": 71, + "directReferencedEntities": [ + "Books", + "Chapters", + "Characters", + "ManuscriptDocuments", + "OnboardingManuscriptBuildChapterMap", + "OnboardingManuscriptBuildCharacterMap", + "OnboardingManuscriptBuildSceneMap", + "OnboardingManuscriptBuilds", + "ProjectUserAccess", + "Projects", + "RevisionStatuses", + "SceneWorkflow", + "Scenes", + "TimeConfidences", + "TimeModes" + ] + }, + { + "procedure": "Onboarding_ManuscriptBuild_GetByPreview", + "definitionSha256": "756c8fe193c23405e31471f2db91816c40ef08978e98514a53e7708171999825", + "latestDirectSource": "PlotLine/Sql/158_Phase25C_OnboardingMarkerSaveStates.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "OnboardingManuscriptBuildChapterMap", + "OnboardingManuscriptBuildCharacterMap", + "OnboardingManuscriptBuildSceneMap", + "OnboardingManuscriptBuilds" + ] + }, + { + "procedure": "Onboarding_ManuscriptBuild_MarkerSyncCompleted", + "definitionSha256": "33a289443a0f523b04af5e954c882d100d353cb23216e0218bdc4cc7a8209fd0", + "latestDirectSource": "PlotLine/Sql/158_Phase25C_OnboardingMarkerSaveStates.sql", + "sourceLine": 52, + "directReferencedEntities": [ + "OnboardingManuscriptBuilds" + ] + }, + { + "procedure": "Onboarding_ManuscriptBuild_MarkerSyncFailed", + "definitionSha256": "0dc3239f6cff24d3e4b3590165f7f7bb4babaa22eb0d36ac5f326344ac975c5e", + "latestDirectSource": "PlotLine/Sql/158_Phase25C_OnboardingMarkerSaveStates.sql", + "sourceLine": 95, + "directReferencedEntities": [ + "OnboardingManuscriptBuilds" + ] + }, + { + "procedure": "Onboarding_ManuscriptBuild_MarkerSyncSent", + "definitionSha256": "699a7433d1389ff3039f96a5ef8096455f32ff036aefccdd94e64893017e9b7c", + "latestDirectSource": "PlotLine/Sql/149_Phase24_StructuralImportMarkerSync.sql", + "sourceLine": 63, + "directReferencedEntities": [ + "OnboardingManuscriptBuilds" + ] + }, + { + "procedure": "Onboarding_ManuscriptBuild_MarkerSyncUserSaveRequired", + "definitionSha256": "4aa790e55758f9cf2b5e3da374eec22eeff19e6c43acc28a799b023a74a769d5", + "latestDirectSource": "PlotLine/Sql/158_Phase25C_OnboardingMarkerSaveStates.sql", + "sourceLine": 78, + "directReferencedEntities": [ + "OnboardingManuscriptBuilds" + ] + }, + { + "procedure": "SceneManuscriptSource_GetByScene", + "definitionSha256": "16a7be303dbcc2f8750946f3d350070e33066e1f7d9e5ba471ebb9dd83d95443", + "latestDirectSource": "PlotLine/Sql/150_Phase24B_SceneManuscriptSources.sql", + "sourceLine": 83, + "directReferencedEntities": [] + }, + { + "procedure": "SceneManuscriptSource_ListByBook", + "definitionSha256": "9f186fbd3764dc41792b7dccfc2ff929b297d26b5d82df216b3bb2907751b823", + "latestDirectSource": "PlotLine/Sql/167_Phase26C_CanonicalStoryIntelligenceContext.sql", + "sourceLine": 113, + "directReferencedEntities": [] + }, + { + "procedure": "SceneManuscriptSource_ListByChapter", + "definitionSha256": "5d43db5dd371b6a819c0cbebf82581ec5a0cf1759568dc7552923aea5769b47a", + "latestDirectSource": "PlotLine/Sql/167_Phase26C_CanonicalStoryIntelligenceContext.sql", + "sourceLine": 94, + "directReferencedEntities": [] + }, + { + "procedure": "SceneManuscriptSource_Save", + "definitionSha256": "4aed700cee173b7901399e48359d2eb7ec0dfe17ebf688ecf3b26e4b133af317", + "latestDirectSource": "PlotLine/Sql/150_Phase24B_SceneManuscriptSources.sql", + "sourceLine": 36, + "directReferencedEntities": [] + }, + { + "procedure": "SceneStructuralSummary_Save", + "definitionSha256": "d659d76acb54801b5e1fe5b67a8fb265b422e349cf07ebe43b23724b87ce5119", + "latestDirectSource": "PlotLine/Sql/167_Phase26C_CanonicalStoryIntelligenceContext.sql", + "sourceLine": 10, + "directReferencedEntities": [], + "dependencyMetadata": "Not requested for these two supplementary source writers; source path inspected." + }, + { + "procedure": "WordCompanion_Book_Create", + "definitionSha256": "b1f1a1f8419cb879ed6e36b6c36a4fe3a6ee1af0d8bebb7d6979c87986862947", + "latestDirectSource": "PlotLine/Sql/095_Phase16C_WordCompanionFirstRunImport.sql", + "sourceLine": 30, + "directReferencedEntities": [ + "Books", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Book_ListByProject", + "definitionSha256": "b5ac863078d631d4dbbfa690aa5f9990d0f31957ef06d67089f079d19ca3953e", + "latestDirectSource": "PlotLine/Sql/109_DropdownListOrderingConsistency.sql", + "sourceLine": 140, + "directReferencedEntities": [ + "Books", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Book_Structure", + "definitionSha256": "d941472b2fcc82a19d566a7cfe4b5ed6b3ef3b043d8a66ebc0b829c511b857bb", + "latestDirectSource": "PlotLine/Sql/109_DropdownListOrderingConsistency.sql", + "sourceLine": 171, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "RevisionStatuses", + "SceneWorkflow", + "Scenes" + ] + }, + { + "procedure": "WordCompanion_Chapter_Create", + "definitionSha256": "2ac072e2a516db1cc8efbd0be65db05a098aaf25c0656dabcd05fdf0c769b078", + "latestDirectSource": "PlotLine/Sql/064_Phase10K_WordCompanionChapterCreateLink.sql", + "sourceLine": 37, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "RevisionStatuses" + ] + }, + { + "procedure": "WordCompanion_Chapter_List", + "definitionSha256": "e6863453597b1a1e933bcd62037539b88f7c7928302b73243d552e295f8f626e", + "latestDirectSource": "PlotLine/Sql/109_DropdownListOrderingConsistency.sql", + "sourceLine": 215, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Character_CreateDiscovered", + "definitionSha256": "3489f823497e3af23d0726ea0dcbc71807465d30024cbe1239824a7919a3b742", + "latestDirectSource": "PlotLine/Sql/096_Phase16D_WordCompanionCharacterDiscovery.sql", + "sourceLine": 27, + "directReferencedEntities": [ + "Characters", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Manuscript_Analyse", + "definitionSha256": "e4a9d6951dbb5d5e9f6f459a42441596825202607afd336cbddc65fa0fec3b36", + "latestDirectSource": "PlotLine/Sql/095_Phase16C_WordCompanionFirstRunImport.sql", + "sourceLine": 72, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "Scenes" + ] + }, + { + "procedure": "WordCompanion_Manuscript_Import", + "definitionSha256": "3b4fe8af9741365a1fd39fdb2157565c850565f439ef818248735d63d77600c3", + "latestDirectSource": "PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql", + "sourceLine": 5, + "directReferencedEntities": [ + "Books", + "Chapters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "RevisionStatuses", + "SceneWorkflow", + "Scenes", + "TimeConfidences", + "TimeModes" + ] + }, + { + "procedure": "WordCompanion_Manuscript_Sync", + "definitionSha256": "7c2ef7111ae024d65d5c38111b7fe560fc77493b728584070d5ae87646c95bbf", + "latestDirectSource": "PlotLine/Sql/057_Phase10A_WordCompanionApiFoundation.sql", + "sourceLine": 378, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "RevisionStatuses", + "WordCompanion_Scene_Sync" + ] + }, + { + "procedure": "WordCompanion_Project_HasAccess", + "definitionSha256": "96c4ff5e10756f2212306add419aae4ce7ce288d96612dd9fef23b01aea75352", + "latestDirectSource": "PlotLine/Sql/096_Phase16D_WordCompanionCharacterDiscovery.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Project_List", + "definitionSha256": "c01a7b00ec465b899f8a0ae39949afca730ef15f881ba87e1a8275cd090aa4fc", + "latestDirectSource": "PlotLine/Sql/057_Phase10A_WordCompanionApiFoundation.sql", + "sourceLine": 38, + "directReferencedEntities": [ + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Runtime_AssetAlias_List", + "definitionSha256": "4b24c1fcef8efb440c78707de7de027a77f119a196732a632b7b1c506cbdecef", + "latestDirectSource": "PlotLine/Sql/103_Phase16K_WordCompanionAssetSuggestions.sql", + "sourceLine": 34, + "directReferencedEntities": [ + "AssetAliases", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "StoryAssets" + ] + }, + { + "procedure": "WordCompanion_Runtime_AssetSuggestions_Create", + "definitionSha256": "97d57a68e6d6c7efbb393a60024f5a551fa9d95d2e47dcb02648b79d642272e7", + "latestDirectSource": "PlotLine/Sql/103_Phase16K_WordCompanionAssetSuggestions.sql", + "sourceLine": 86, + "directReferencedEntities": [ + "AssetCustodyEvents", + "AssetEvents", + "Books", + "Chapters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "SceneAssetLocations", + "SceneAssetSuggestions", + "Scenes", + "StoryAssets" + ] + }, + { + "procedure": "WordCompanion_Runtime_CharacterAlias_List", + "definitionSha256": "93f0efe53bc1965e44f3e446c0c35bae71404ce61c5ade901af2d96c7011d989", + "latestDirectSource": "PlotLine/Sql/098_Phase16H_WordCompanionCharacterSuggestions.sql", + "sourceLine": 34, + "directReferencedEntities": [ + "CharacterAliases", + "Characters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Runtime_CharacterSuggestions_Create", + "definitionSha256": "8b4ed2a93c672e403638e9cd53b49c63662f3be5be69a4476d28077003ab6803", + "latestDirectSource": "PlotLine/Sql/100_Phase16I_WordCompanionCharacterSuggestionReview.sql", + "sourceLine": 182, + "directReferencedEntities": [ + "Books", + "Chapters", + "Characters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "SceneCharacterSuggestions", + "SceneCharacters", + "Scenes" + ] + }, + { + "procedure": "WordCompanion_Runtime_CurrentScene_Validate", + "definitionSha256": "80515bd99d2a9d49a071df4b99e889739c305fd9dc6e3d5215de21cd5e945ab2", + "latestDirectSource": "PlotLine/Sql/102_Phase16J_FixFollowSceneEditUrl.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "Books", + "Chapters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "Scenes" + ] + }, + { + "procedure": "WordCompanion_Runtime_LocationAlias_List", + "definitionSha256": "990705099d881a65840141c2aca2a647de3deb574642ced1fd039e9cadfba3b6", + "latestDirectSource": "PlotLine/Sql/105_Phase16M_LocationDetectionMetadata.sql", + "sourceLine": 116, + "directReferencedEntities": [ + "LocationAliases", + "LocationPaths", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects" + ] + }, + { + "procedure": "WordCompanion_Runtime_LocationSuggestions_Create", + "definitionSha256": "d147ab64069c2e14a53b430d39e3559883121a2a8053ed742f2abfbaf500d011", + "latestDirectSource": "PlotLine/Sql/106_Phase16N_WordCompanionLocationSuggestions.sql", + "sourceLine": 39, + "directReferencedEntities": [ + "Books", + "Chapters", + "Locations", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "SceneLocationSuggestions", + "Scenes", + "WordCompanionSceneLocations" + ] + }, + { + "procedure": "WordCompanion_Runtime_SceneWordCount_Update", + "definitionSha256": "efa29edec164079f630d4a279ba1be554e3c97b96197d1958e6c8f192fac24da", + "latestDirectSource": "PlotLine/Sql/097_Phase16F_WordCompanionRuntimeSceneWordCountSync.sql", + "sourceLine": 1, + "directReferencedEntities": [ + "Books", + "Chapters", + "ManuscriptDocuments", + "ProjectUserAccess", + "Projects", + "SceneWorkflow", + "Scenes" + ] + }, + { + "procedure": "WordCompanion_SceneLinks_Update", + "definitionSha256": "639a0a3ff12c83272173633bc5aca0828242dec9ce6e0e32f23a2b7a959bda87", + "latestDirectSource": "PlotLine/Sql/061_Phase10H2_WordCompanionSceneLinksRealSceneData.sql", + "sourceLine": 70, + "directReferencedEntities": [ + "AssetEventTypes", + "AssetEvents", + "Books", + "Chapters", + "Characters", + "Locations", + "ProjectUserAccess", + "Projects", + "SceneAssetLocations", + "SceneCharacters", + "Scenes", + "StoryAssets" + ] + }, + { + "procedure": "WordCompanion_Scene_Companion", + "definitionSha256": "f951b46cc0e85af6ccebb935b98b5494a133fa11e30f5a52a676e8841f45e5e8", + "latestDirectSource": "PlotLine/Sql/061_Phase10H2_WordCompanionSceneLinksRealSceneData.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "AssetEvents", + "Books", + "Chapters", + "Characters", + "Locations", + "ProjectUserAccess", + "Projects", + "SceneAssetLocations", + "SceneCharacters", + "SceneWorkflow", + "Scenes", + "StoryAssets" + ] + }, + { + "procedure": "WordCompanion_Scene_Create", + "definitionSha256": "8096e7d655129fec11d9c5da919399970fe545ba3e0837bff38115e47901c890", + "latestDirectSource": "PlotLine/Sql/062_Phase10J_WordCompanionSceneCreateLink.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "RevisionStatuses", + "SceneWorkflow", + "Scenes", + "TimeConfidences", + "TimeModes" + ] + }, + { + "procedure": "WordCompanion_Scene_Resolve", + "definitionSha256": "b8a84526ac3eabf2ca7e04ca298fed7dc2453f2deeb383e556f037583517d84d", + "latestDirectSource": "PlotLine/Sql/063_Phase10J_UnmatchedSceneChapterDiagnostics.sql", + "sourceLine": 6, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "Scenes" + ] + }, + { + "procedure": "WordCompanion_Scene_Sync", + "definitionSha256": "980446d95b750d57f01c5e7041aa09867fae20c2f178c60305083dcd2be709fb", + "latestDirectSource": "PlotLine/Sql/057_Phase10A_WordCompanionApiFoundation.sql", + "sourceLine": 287, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "RevisionStatuses", + "SceneWorkflow", + "Scenes", + "TimeConfidences", + "TimeModes" + ] + }, + { + "procedure": "WordCompanion_Scene_UpdateWordCount", + "definitionSha256": "a07aa6f5cd896ba215caada9c4bf7b010d5c94c3203f8f648ea6eb7424461546", + "latestDirectSource": "PlotLine/Sql/059_Phase10F_WordCompanionSceneProgressSync.sql", + "sourceLine": 1, + "directReferencedEntities": [ + "Books", + "Chapters", + "ProjectUserAccess", + "Projects", + "SceneWorkflow", + "Scenes" + ] + } + ], + "caveat": "Latest direct source definitions may be superseded by dynamic SQL patches; live definition hash is authoritative for this inspection. Dependency metadata does not expand dynamic SQL or application-mediated calls." +} diff --git a/Docs/Investigations/2026-11-04-word-companion-http-api.csv b/Docs/Investigations/2026-11-04-word-companion-http-api.csv new file mode 100644 index 00000000..61c51130 --- /dev/null +++ b/Docs/Investigations/2026-11-04-word-companion-http-api.csv @@ -0,0 +1,30 @@ +Verb,Route,ControllerAction,Parameters,ServiceMethod,ControllerLine +GET,/api/word-companion/projects,GetProjects,,ListProjectsAsync,21 +GET,/api/word-companion/projects/{projectId:int}/books,GetBooks,int projectId,ListBooksAsync,24 +POST,/api/word-companion/projects/{projectId:int}/books,CreateBook,"int projectId, WordCompanionCreateBookRequest request",CreateBookAsync,31 +GET,/api/word-companion/books/{bookId:int}/structure,GetBookStructure,int bookId,GetBookStructureAsync,38 +GET,/api/word-companion/books/{bookId:int}/chapters,GetChapters,int bookId,ListChaptersAsync,45 +POST,/api/word-companion/books/{bookId:int}/resolve-scene,ResolveScene,"int bookId, WordCompanionResolveSceneRequest request",ResolveSceneAsync,52 +GET,/api/word-companion/scenes/{sceneId:int}/companion,GetSceneCompanion,int sceneId,GetSceneCompanionAsync,64 +POST,/api/word-companion/books/{bookId:int}/chapters,CreateChapter,"int bookId, WordCompanionCreateChapterRequest request",CreateChapterAsync,71 +POST,/api/word-companion/books/{bookId:int}/chapters/{chapterId:int}/scenes,CreateScene,"int bookId, int chapterId, WordCompanionCreateSceneRequest request",CreateSceneAsync,78 +POST,/api/word-companion/books/{bookId:int}/sync-scene,SyncScene,"int bookId, WordCompanionSyncSceneRequest request",SyncSceneAsync,85 +POST,/api/word-companion/books/{bookId:int}/sync-manuscript,SyncManuscript,"int bookId, WordCompanionSyncManuscriptRequest request",SyncManuscriptAsync,92 +PUT,/api/word-companion/scenes/{sceneId:int}/links,UpdateSceneLinks,"int sceneId, WordCompanionUpdateSceneLinksRequest request",UpdateSceneLinksAsync,99 +PATCH,/api/word-companion/scenes/{sceneId:int}/word-count,UpdateWordCount,"int sceneId, WordCompanionUpdateWordCountRequest request",UpdateWordCountAsync,106 +GET,/api/word-companion/runtime/book/{bookId:int},GetRuntimeBook,"int bookId, [FromQuery] Guid documentGuid",GetRuntimeBookAsync,113 +POST,/api/word-companion/runtime/scene-word-count,UpdateRuntimeSceneWordCount,WordCompanionRuntimeSceneWordCountRequest request,UpdateRuntimeSceneWordCountAsync,120 +POST,/api/word-companion/runtime/current-scene,UpdateRuntimeCurrentScene,WordCompanionRuntimeCurrentSceneRequest request,ValidateRuntimeCurrentSceneAsync,127 +GET,/api/word-companion/runtime/characters,GetRuntimeCharacters,"[FromQuery] int projectId, [FromQuery] Guid documentGuid",ListRuntimeCharacterAliasesAsync,173 +POST,/api/word-companion/runtime/character-suggestions,CreateRuntimeCharacterSuggestions,WordCompanionRuntimeCharacterSuggestionsRequest request,CreateRuntimeCharacterSuggestionsAsync,180 +GET,/api/word-companion/runtime/assets,GetRuntimeAssets,"[FromQuery] int projectId, [FromQuery] Guid documentGuid",ListRuntimeAssetAliasesAsync,187 +POST,/api/word-companion/runtime/asset-suggestions,CreateRuntimeAssetSuggestions,WordCompanionRuntimeAssetSuggestionsRequest request,CreateRuntimeAssetSuggestionsAsync,194 +GET,/api/word-companion/runtime/locations,GetRuntimeLocations,"[FromQuery] int projectId, [FromQuery] Guid documentGuid",ListRuntimeLocationAliasesAsync,201 +POST,/api/word-companion/runtime/location-suggestions,CreateRuntimeLocationSuggestions,WordCompanionRuntimeLocationSuggestionsRequest request,CreateRuntimeLocationSuggestionsAsync,208 +GET,/api/word-companion/manuscript/book/{bookId:int},GetManuscriptForBook,int bookId,GetManuscriptForBookAsync,215 +POST,/api/word-companion/manuscript/link,LinkManuscript,WordCompanionManuscriptLinkRequest request,LinkManuscriptAsync,222 +POST,/api/word-companion/manuscript/unlink,UnlinkManuscript,WordCompanionManuscriptUnlinkRequest request,UnlinkManuscriptAsync,229 +POST,/api/word-companion/manuscript/analyse,AnalyseManuscript,WordCompanionManuscriptAnalyseRequest request,AnalyseManuscriptAsync,236 +POST,/api/word-companion/manuscript/import,ImportManuscript,WordCompanionManuscriptImportRequest request,ImportManuscriptAsync,243 +POST,/api/word-companion/manuscript/discover-characters,DiscoverCharacters,WordCompanionDiscoverCharactersRequest request,DiscoverCharacterCandidatesAsync,257 +POST,/api/word-companion/manuscript/create-discovered-characters,CreateDiscoveredCharacters,WordCompanionCreateDiscoveredCharactersRequest request,CreateDiscoveredCharactersAsync,264 diff --git a/Docs/Investigations/2026-11-04-word-companion-investigation.md b/Docs/Investigations/2026-11-04-word-companion-investigation.md new file mode 100644 index 00000000..379fd25d --- /dev/null +++ b/Docs/Investigations/2026-11-04-word-companion-investigation.md @@ -0,0 +1,582 @@ +# PlotDirector Word Companion: technical investigation + +Investigation date: 4 November 2026. Source baseline: `d0ed7d7c3b6c5f58f34bfaf64043dded5b486e90`, `/srv/repos/PlotDirector`. Investigation only: application code, database data/schema and deployment were not changed. New documentation is the sole repository change. + +## 1. Executive summary + +The current Companion is an Office.js task pane, not a native desktop process. The separate `PlotDirector.WordCompanion/` directory supplies its manifest and manifest renderer; nearly all behaviour runs in PlotDirector's hosted `word-companion-host.js` (6,635 lines). It uses same-origin cookie-authenticated HTTP for project data and runtime scene notifications, and one ASP.NET Core SignalR hub for presence, browser-window coordination and browser-led manuscript onboarding. + +**Preserve Context and Intent as independent browser/PWA windows.** They combine canonical scene/chapter data with live Word position, per-window roles, per-book named windows, focus requests and display preferences. They are not mere task-pane tabs. They can remain server-rendered screens under a VSTO migration. The native component should not need to duplicate their rendering or story-domain logic. + +**Word owns prose, but current “sync” does not continuously upload prose.** Older task-pane first-run import uploads structure/counts; browser-led Core Import uploads chapter text and paragraph provenance and then persists scene sources. Routine scene sync updates a word count and timestamps; runtime entity detection sends matched IDs, not prose. No implemented general server-to-Word prose writer or cursor-navigation command was found. Server-initiated Word writes are structural marker instructions. Browser manual selection updates the current browser's story-position event, not Word's selection. + +**A native port alone will not resolve protocol weaknesses.** Presence has one effective Word connection per user; follow messages omit document/session identity and ordering; marker completion methods lack build ownership validation; paragraph-index mapping can become stale; delayed browser responses can display an older scene. These must be design inputs rather than compatibility requirements to preserve unchanged. + +**Architecture recommendation:** retain the server/domain/browser system, replace the Word adapter, and design the transport behind an interface. Prefer the simpler in-process asynchronous design unless a measured prototype establishes a need for an agent. An agent has a strong possible justification for a modern .NET runtime, durable offline work and independent restart; it does not make Word COM extraction thread-safe or inherently faster. Classic VSTO remains a .NET Framework component, so the proposed all-C# solution crosses a runtime boundary if the agent uses modern .NET. This is a proposed direction, not an existing capability. See sections 10–13. + +### Evidence and deliverable index + +- [HTTP API inventory: all 29 controller actions](2026-11-04-word-companion-http-api.csv). +- [Public DTO/property inventory](2026-11-04-word-companion-contracts.md): API, presence, workspace and scan models; exact source declarations remain authoritative. +- [Development metadata evidence](2026-11-04-word-companion-database-evidence.json): 43 live procedure definition hashes, source candidates and dependency metadata; no author/manuscript rows. +- [Feature-by-feature migration matrix](2026-11-04-word-companion-migration.csv). +- This report contains architecture, live-follow, Context, Intent, multi-screen and onboarding sequence diagrams. + +Evidence labels: **source-confirmed** means reachable implementation was inspected; **isolated reproduction** executes the actual JavaScript with local deterministic substitutes and no network/Word/DB writes; **platform documentation** is externally verified Microsoft guidance; **inference/proposal** is explicitly identified. Source inspection establishes code behaviour, not successful operation on every Word host. Existing tests were inspected, not rerun against live data. No Windows Word/VSTO runtime, real signed-in Office task pane or author manuscript was available. No production host/database was accessed. Only Development schema/procedure metadata was queried, after `DB_NAME()` verification. + +## 2. Current architecture and responsibility boundaries + +```mermaid +flowchart LR + subgraph Word[Microsoft Word and its document] + Manifest[Office manifest: Home ribbon button] + Pane[Hosted task pane: Office.js adapter and UI] + Document[Body paragraphs, controls/bookmarks, add-in settings] + Manifest -->|ShowTaskpane: /word-companion| Pane + Pane <-->|Word.run, context.sync, selection event; marker/settings writes| Document + end + subgraph Browser[Browser / PWA windows] + Onboarding[Import setup, review and save confirmation] + Launcher[Writer launcher and display preferences] + Context[Context screen] + Intent[Intent screen] + end + subgraph Server[ASP.NET Core PlotDirector] + Account[Account login and PlotLine.Auth cookie] + API[WordCompanionController: 29 HTTP actions] + Hub[WordCompanionFollowHub] + Presence[Singleton Word/window presence and scan store] + Core[WordCompanionService / OnboardingService] + Screens[WritingController and story/workflow/map services] + SQL[Dapper repositories and stored procedures] + AI[Chapter structure / Core Import processing] + end + DB[(SQL Server)] + Pane -->|same-origin cookie HTTP| API + Pane <-->|SignalR: registration, scans, marker commands| Hub + Pane -.->|window.open: scoped URLs| Launcher + Pane -.->|window.open| Context + Pane -.->|window.open| Intent + Onboarding <-->|SignalR scan/build/progress| Hub + Onboarding -->|review HTTP forms| Core + Launcher <-->|window roles, heartbeats, focus| Hub + Context <-->|follow connection + role connection| Hub + Intent <-->|follow connection + role connection| Hub + Context -->|GET full page / scene fragment| Screens + Intent -->|GET full page / chapter or scene fragment| Screens + API --> Core + API -->|validated position; user-group event| Hub + API --> Presence + Hub --> Presence + Hub --> Core + Core --> AI + Core --> SQL + Screens --> SQL + SQL --> DB + Account -.->|separate browser/webview cookie contexts may apply| Pane + Account -.-> Browser +``` + +Dashed opening/authentication edges describe the code's browser calls and session dependency; native Word-to-browser activation is not proven by a desktop run. There is no existing local agent, IPC service, token broker or VSTO project in the inspected source. The only other similarly named checkout found was `PlotDirector-seo-verification`, not a separate Companion implementation. No additional Companion repository was supplied; externally installed manifests, Office tenant deployment settings, Windows registry/install state and production configuration are evidence gaps. + +| Component | Actual responsibility and source | +|---|---| +| Add-in shell | [manifest.template.xml](../../PlotDirector.WordCompanion/manifest.template.xml), generated [manifest.xml](../../PlotDirector.WordCompanion/manifest.xml): fixed add-in ID `7e97f8e8-49ce-4a5d-99cc-5447a460a27f`, version `1.0.0.0`, host `Document`, Home-tab PlotDirector group, one **Open PlotDirector Companion** button using ShowTaskpane. ReadWriteDocument permission. FunctionFile is the same hosted URL; no separate ExecuteFunction command implementation. No explicit Word requirement-set minimum in this manifest. | +| Manifest tooling | [render-manifest.js](../../PlotDirector.WordCompanion/scripts/render-manifest.js) substitutes escaped config; package has only manifest build/validation tooling, `office-addin-manifest` dev dependency. Do not run `npm run validate` in a strict read-only inspection: it regenerates the manifest. | +| Environment selection | [config/development.json](../../PlotDirector.WordCompanion/config/development.json) and checked-in manifest actually name `https://plotdirector.com`, **not** `https://dev.plotdirector.com`. This is confirmed configuration, not proof of the currently installed add-in's target. A Development deployment does not prove that Word's installed manifest uses it. | +| Hosted task pane | [WordCompanionHostController.Index](../../PlotLine/Controllers/WordCompanionHostController.cs#L16), [Index.cshtml](../../PlotLine/Views/WordCompanionHost/Index.cshtml): anonymous shell/sign-in link, authenticated feature UI, no main application layout; Office.js hosted CDN and SignalR JS 8.0.7 CDN. Host version label is `20C`, independent of manifest/package versions. | +| Word adapter and task-pane state | [word-companion-host.js](../../PlotLine/wwwroot/js/word-companion-host.js): Word access, parsers, marker maintenance, matching, imports, UI, runtime snapshots, entity detection and network orchestration in one closure. Tabs: Scene, Review, Maintenance, Diagnostics. | +| HTTP service boundary | [WordCompanionController](../../PlotLine/Controllers/WordCompanionController.cs), [WordCompanionService](../../PlotLine/Services/WordCompanionService.cs), [WordCompanionRepository](../../PlotLine/Data/WordCompanionRepository.cs); structured DTOs in [WordCompanionApiModels](../../PlotLine/Models/WordCompanionApiModels.cs). Services enforce positive IDs/limits and subscriptions; SQL checks project access and document linkage. | +| SignalR | [WordCompanionFollowHub](../../PlotLine/Hubs/WordCompanionFollowHub.cs); registration in [Program.cs](../../PlotLine/Program.cs#L346), one route `/hubs/word-companion-follow`, `[Authorize]`. Relevant web clients: host, `word-companion-presence.js`, `writing-workspace.js`, `writing-follow.js`. Other product hubs are not in this Word path. | +| Volatile server state | [WordCompanionPresenceService](../../PlotLine/Services/WordCompanionPresenceService.cs), [WritingWorkspacePresenceService](../../PlotLine/Services/WritingWorkspacePresenceService.cs), [ManuscriptScanPreviewStore](../../PlotLine/Services/ManuscriptScanPreviewStore.cs) are singleton in-process stores. Restart loses presence/scans/review previews; no backplane/durable replay is configured in this path. | +| Background work | [WordCompanionPresenceMonitor](../../PlotLine/Services/WordCompanionPresenceMonitor.cs) periodically expires presence. Browser-led build calls OnboardingService and chapter analysis on the server; it is not an existing client background process or a durable desktop job queue. | +| Browser/PWA display | [WritingController](../../PlotLine/Controllers/WritingController.cs), [Writing views](../../PlotLine/Views/Writing/Context.cshtml), [writing-follow.js](../../PlotLine/wwwroot/js/writing-follow.js), [writing-workspace.js](../../PlotLine/wwwroot/js/writing-workspace.js), [writing-workspace-launcher.js](../../PlotLine/wwwroot/js/writing-workspace-launcher.js). Canonical browser event helper is [site.js](../../PlotLine/wwwroot/js/site.js#L66). | +| Core Import and source custody | [OnboardingService.BuildApprovedStructureAsync](../../PlotLine/Services/OnboardingService.cs#L309), [ManuscriptStructureAnalysisService](../../PlotLine/Services/ManuscriptStructureAnalysisService.cs), [OnboardingBuildRepository](../../PlotLine/Data/OnboardingBuildRepository.cs), source/statistics/character/location services. Core Import produces canonical scene sources consumed by the existing Story Intelligence pipeline; see [runtime contract](../../docs/story-intelligence/single-system-runtime.md). | + +### Authentication, authorization and session handling + +`WordCompanionHostController` is anonymous so it can show sign-in. Sign-in navigates `_top` to Account/Login with a local return URL. The normal login pipeline handles password checks, optional two-factor flow and cookie issuance. There is no Office SSO API, OAuth access-token exchange or desktop-device authorization endpoint in this path. + +[Program.cs](../../PlotLine/Program.cs#L57) uses `PlotLine.Auth`, HttpOnly/Secure/SameSite=Lax, 14-day sliding expiration, identity/security-stamp and lockout validation. The separate ASP.NET session cookie has a 10-minute idle timeout; it is not the 14-day authentication lifetime. The host's `fetchJson` uses `credentials: same-origin`; SignalR uses the site's authentication. A native agent cannot assume it inherits the task-pane/browser cookie container. WebView/browser cookie isolation, embedded cookie policy and sign-in expiry require real Office testing. + +MVC globally applies ProjectAccessFilter and SubscriptionEnforcementFilter. The Companion controller is `[ApiController]` and `[Authorize]`; ordinary HTTP writes are also subscription-gated. Repository procedures receive authenticated UserID; runtime operations validate active document binding plus book/chapter/scene membership. The hub uses NameIdentifier claims and ignores an asserted different registration UserID. Hub calls do **not** pass through MVC action filters. The inspected host/API has no antiforgery attributes or global automatic antiforgery filter; JSON, same-origin use and Lax cookies provide some barriers, but are not a substitute for a documented CSRF/origin policy. No unauthenticated exploit was attempted. The existing account form itself is antiforgery-protected. + +## 3. Feature inventory and complete execution paths + +Notation: **H** = `wwwroot/js/word-companion-host.js`; **C/S/R** = WordCompanionController/Service/Repository; procedure names below have `dbo.` prefix. Detailed routes/signatures: [HTTP CSV](2026-11-04-word-companion-http-api.csv). Features marked “API only” are public operations even though the current host does not call them. + +| ID | Trigger / feature | Complete path, Word use and transferred/persisted state | Success, failure and limitations | +|---|---|---|---| +| F01 | Open Companion | Manifest Home button → `/word-companion` → host Index → Office.onReady, Word-host check. | Anonymous sign-in UI or authenticated pane. No desktop agent startup. Host availability is not an API capability/version negotiation. | +| F02 | Sign in/out, reconnect account | Account/Login → AuthService/cookie; C/S RequireUserId; fetch/SignalR credentials. Browser account logout/security stamp changes invalidate later requests. | Host has sign-in affordance; no desktop token lifecycle or offline login. Generic HTTP errors do not distinguish expired login from network/subscription errors well. | +| F03 | Choose project/book, create book | H `loadProjects`, `loadBooks`, first-run selectors → C GetProjects/GetBooks/CreateBook → S validation/entitlements → R project/book SPs. | Accessible active projects/books; optional new title. Browser localStorage remembers selection/tab. UI storage does not grant access. | +| F04 | Bind an existing manuscript | H `linkFirstRunManuscript` → manuscript/link → S `LinkManuscriptAsync` → `ManuscriptDocument_Save`; H `writeDocumentBinding` settings.saveAsync. | GUID generated if absent, metadata written locally after server success. One active binding conflict is rejected. Server and document writes are separate failure boundaries. | +| F05 | Resume a bound document | H `initialiseFirstRunBinding` reads four settings → runtime/book + documentGuid → S validates document/active book/access and updates LastOpened → H loads structure/alias caches. | Matches GUID/book/project before entering runtime. Failures fall back to unbound UI; no distinction between a transient request failure and a definitively invalid binding. | +| F06 | Task-pane first-run scan/preview | H `analyseFirstRunManuscript` → Word.run reads body paragraphs/styles → `buildFirstRunImportStructure` → manuscript/analyse; sends counts and IDs. | Heading 1 chapters; each gets a scene; `***`/`###` separators when UsesExplicitScenes. Preview/replace confirmation; pre-chapter text not represented in structure. Not a prose archive. | +| F07 | Task-pane first-run import | H `importFirstRunManuscript` → manuscript/import → S/R → `WordCompanion_Manuscript_Import` (migration 219); chapters/scenes/titles/order/counts, GUID, BindingVersion, ReplacePlanned. | Transactional linked structure creation, protected planned replacement/archive rules, repeat import refusal; settings saved after SQL. No chapter/scene prose fields in this request. Marker attachment is a separate operation; do not assume this path performs Core Import's marker round trip. | +| F08 | Discover/create characters at first run | H sends documentText to manuscript/discover-characters; S regex/name-intelligence decoration; selected names → create-discovered-characters → project access/limits → creation SP. | Heuristic candidates, selection/skip UI, existing-name handling; minimum mentions 2, max creation selection 250. English/capitalization-biased candidate regex is not universal named-entity recognition. This scan is not routine prose synchronization. | +| F09 | Browser-led scan request | Browser `word-companion-presence.js` → Hub StartOnboardingManuscriptScan → user onboarding/project/book + latest Word presence → targeted ScanCurrentDocument → H `runOnboardingDocumentScan`. | Requires connected Word/document and selected onboarding scope. Error if missing. Server selects one effective per-user Companion, not a requested document session. | +| F10 | Extract/upload full scan | H Word.run loads body text/styles, heading anchors → `buildOnboardingScanPreview` → JSON chunks through ReceiveOnboardingScanChunk. | Chapter text + paragraph map + source paragraphs/indexes/flags; progress, scan ID and length checks. Front matter ignored before manuscript; no readable chapter/body fails. Section 6 details normalization and limits. | +| F11 | Review scan / approve chapters | Browser onboarding scan-review → OnboardingController.SaveScanReview → OnboardingService → ManuscriptScanPreviewStore review. | Inclusion/title/order choices and status saved in memory; ready-to-import validation. Not durable across server restart. Review has no Word COM dependency. | +| F12 | Build canonical project scenes | Browser Hub StartOnboardingProjectBuild(previewId, generateSceneTitles) → OnboardingService.BuildApprovedStructureAsync → approved chapter analysis/validator → OnboardingBuildRepository.BuildAsync; sources/statistics/POV/chronology and location/character preparation. | SQL build mappings persist; completed build can resume using preview/mappings and missing source repair. Server chapter analysis uses configured AI client with one JSON repair retry. Multi-step post-build operations are not a single Word+SQL transaction. | +| F13 | Insert server-generated marker instructions | Hub targets UpdateOnboardingBuildMarkers → H reloads body paragraphs, indexes instructions, calls ensureAnchorControl → manual save request/ack. | DB IDs mapped to chapter/scene paragraph anchors; exact existing tags idempotent. No prose insertion. Old indexes can be wrong after edits; no document revision/text precondition. See section 8. | +| F14 | Confirm manuscript saved | Companion or browser “I've saved it” → CompleteOnboardingBuildMarkerSync → persistent build MarkerStatus/timestamp → progress/completion event → browser build-complete. | User confirmation, not independently verified disk-save proof. Existing-marker path reports SaveNotRequired. Changed-marker onboarding deliberately asks for manual save. | +| F15 | Current chapter/scene discovery | H runtime parser/cache + getSelection().paragraphs; `findSelectedParagraphIndex`, `applyRuntimeSelection`, `refreshPlotDirectorScene/Chapter`. | Canonical scene/chapter IDs first, title fallback, matched or create/link UI. Selection matching uses text/style and nearest cached index, not stable Word range identity. | +| F16 | Automatic change tracking | Common DocumentSelectionChanged → markRuntimeDirty → 1.2-second idle debounce → capture snapshot → refresh scene/count/suggestions. | Generation prevents stale local snapshot responses being adopted. No general paragraph-insert/delete/content-changed subscription; edits can invalidate cached boundaries until full refresh. | +| F17 | Manual current scene/document refresh | Refresh Current Scene / Read Document → H refreshCurrentScene/refreshDocumentStructure/loadRuntimeDocumentAwareness → full structure read + API resolution. | Rebuild/resolve fallback for unsupported events or changed structure; diagnostic/error messages. Does not silently change prose. | +| F18 | Read planning brief/status/links | Scene resolution → GetSceneCompanion → `WordCompanion_Scene_Companion` returns revision, estimated/actual words, blocked reason, writing brief, selected/available characters/assets/locations and primary location. | Read-only presentation. Missing/inaccessible scene resets UI; not a full scene editor. | +| F19 | Runtime scene word-count sync | H `syncSceneProgress` snapshot → runtime/scene-word-count → active-document/linked-scene validation → SceneWorkflow actual count + LastWorkedOn UTC date + ManuscriptDocuments.LastSyncUtc. | Automatic ~4-second timer after idle or manual button; count equality suppresses duplicates; in-flight coalescing and stale-snapshot checks. No prose/hash upload, persistent retry queue or conflict version. | +| F20 | Legacy direct word-count update (API only) | PATCH scenes/{id}/word-count → C/S/R → `WordCompanion_Scene_UpdateWordCount`, accepts ActualWords or ActualWordCount and optional LastWorkedOn. | Older access-controlled count API; lacks newer document-bound request identity. Host defines patchJson but current runtime uses POST above. | +| F21 | Legacy scene/manuscript structure sync (API only) | POST books/{id}/sync-scene or sync-manuscript → entitlement preflight → SPs create/match by titles and update counts. | Optional DocumentId/ContentHash are accepted but not used for reliable optimistic concurrency or prose transfer. No automatic deletion/rename reconciliation; cursor-based manuscript SP is not a durable batch queue. | +| F22 | Manually create or link missing chapter | H createPlotDirectorChapter / linkSelectedExistingChapter → chapters API or selection of existing structure → ensureAnchorControl PD-CHAPTER → refresh. | Confirm/create/search dialog, positive title/order validation and server entitlements. Linking changes Word metadata; Word failure can follow a successful SQL create. | +| F23 | Manually create or link missing scene | H createPlotDirectorScene / linkSelectedExistingScene → scenes API or existing choice → PD-SCENE and chapter marker attachment → refresh. | Chapter must resolve; duplicate/title ambiguity surfaced in preview/manual review. No atomic Word/DB rollback. | +| F24 | Attach/repair stored IDs | H attachPlotDirectorIds/attachResolvedPlotDirectorIds/attachResolvedChapterId → current Word paragraphs → ensureAnchorControl. | Tries content-control Content/Start/Whole ranges, then start bookmark; updates reusable tag/title. Existing IDs validated through book structure. Hidden appearance means hidden control chrome, not hidden/deleted prose. | +| F25 | Preview/apply structural maintenance | H analyseManuscriptStructure reads Word + GET book structure → comparison groups → confirmed applyStructureSync. Each create/link item calls existing APIs, queues anchor attachment, records success/failure/skipped. | Manual review/ambiguous items skipped; preview refreshed. Per-item partial failures reported; not atomic and no automatic server archive of disappeared Word items. | +| F26 | Detect existing entities while drafting | Snapshot text matched locally against cached character/asset/location aliases; suggestion APIs receive DocumentGuid, SceneId and matched IDs (max 50). | ~2.5-second suggestion debounce, signature dedup, generation checks. Whole-word regex; conservative location filtering. Empty matches do not revoke earlier suggestions. Alias caches refresh on explicit runtime reload, not an evidenced push invalidation. | +| F27 | Review/save canonical scene links | Pane Review chips/primary location → verifyCurrentWordSceneMatchesLinkedScene full read → PUT links → SQL canonical relationships/custody/location mappings. Browser Scenes suggestion accept/reject actions invoke domain services/SPs. | Guards stale selected scene before writes; user review changes planning data, not Word prose. Runtime suggestions are distinct persisted Pending/Accepted/Rejected observations. | +| F28 | Publish current Word location | Resolved H `notifyPlotDirectorCurrentScene` → runtime/current-scene → SQL validate → in-memory current story position → user SignalR storyPositionChanged. | Signature suppresses duplicate notifications; failure clears signature but no timed retry. Payload lacks document/session/revision/sequence; no clear-position command for unresolvable selection. | +| F29 | Open Writer / Context / Intent | H openWritingWindow → same-origin scoped URLs with project/book/chapter/scene/documentGuid where applicable; stable named browser window. | Blocked-popup message; direct Word task-pane → external browser activation/cookie sharing requires desktop evidence. Writer launcher additionally handles screen detection/role focus. | +| F30 | Context follow + manual display | WritingController.Context/ContextScene → StoryContextService → SceneService/canonical story state + relationship map/floor plan → Razor fragments; writing-follow loads on story-position event. | Scene-only display; local tab preference; manual dropdown publishes browser DOM event. No reverse Word command. See section 5. | +| F31 | Intent follow + manual display | WritingController.Intent/IntentScene → StoryContextService and WriterWorkspaceService chapter workflow/goals → Razor fragments. | Scene or chapter-only display, five tabs, independent window preference. No reverse Word command. See section 5. | +| F32 | Multi-screen layout / focus | Writer launcher + workspace JS → getScreenDetails/window-management permission, display preferences, window.open/stable names; Hub RegisterWritingWindow/heartbeats/focus. | Default Context-left/Intent-right with 3+ displays, configurable 2-screen primary role, fallback windows if unavailable. Word position itself is not moved between monitors by this JS. | +| F33 | Presence and reconnect | Host RegisterCompanion/25s heartbeat; browser WatchCompanionPresence; window role registration/15s heartbeat; monitor expires stale records. | Word timeout 55s, windows 45s, monitor 10s. Automatic reconnect where configured, differing initial/terminal retry handling. In-memory state and one Word record/user limit robustness. | +| F34 | Unlink without marker removal | H unlinkThisWordDocument → server unlink + settings removal → unbound onboarding; can explicitly offer local-only metadata removal on failure. BooksController.UnlinkManuscript is browser-side equivalent server operation. | Link flags/document active state cleared by server, planning data retained; markers deliberately remain for reuse. Distributed partial state is reported, not atomic. | +| F35 | Clean and unlink | H inspect → removePlotDirectorContentControlsPreservingContent → optional save helper → verify marker count → remove settings → server unlink. | Controls deleted with Office.js keepContent=true, tagged prefixes only. **Bookmark fallback anchors are not removed or counted.** save helper result ignored; read-only/unsupported/failed save can be misrepresented. | +| F36 | Diagnostics and recovery UI | H runDiagnostics, anchor/resolve/status/timing panels, console logs; server register/current-scene/build logs. | Shows host/platform, IDs, paragraph/heading counts, resolution method, last error, timings and save diagnostics. No single end-to-end correlation envelope, durable client log or support export. | + +## 4. SignalR: complete relevant contract and routing + +### Connections and identity + +All relevant traffic uses **one hub route**, not a dedicated Context hub and Intent hub. OnConnected adds any authenticated connection to `word-companion-presence:{UserID}`. The same group carries all that user's book/document presence, positions and onboarding events; there are no per-document/per-book hub groups. Some commands target a single connection selected from the in-memory stores. + +| Client | Establishment / re-establishment | Listening and scope | +|---|---|---| +| Word task pane (`startCompanionPresence`, H1459) | HubConnectionBuilder + automatic reconnect; start → RegisterCompanion; 25s heartbeat. Reconnected sends heartbeat, which can establish record again. Initial failure retains the non-null connection object; terminal close clears timer but does not null/restart connection. | ScanCurrentDocument and UpdateOnboardingBuildMarkers only. No navigate/replace-prose event listener. Registration has user/version/machine(empty)/document-open/name/project/book, **no document GUID/session ID**. | +| Shared browser header/onboarding (`word-companion-presence.js`) | start → WatchCompanionPresence; reconnected watches again; reconnecting shows Connecting. Initial failure caught for UI. | Presence + scan/build/save progress; commands scan/build/manual-save. Conditional layout inclusion for relevant authenticated users. | +| Writer/Context/Intent role client (`writing-workspace.js`) | Lazy shared-per-page connection; initial failure/terminal close clear promise so later actions retry. Reconnected registers window. 15s heartbeat. | storyPositionChanged, WritingWorkspacePresenceChanged, WordCompanionPresenceChanged, WritingWorkspaceFocusRequested. Window ID in sessionStorage with owner/opener-clone detection; stable within document without storage. | +| Context/Intent follow client (`writing-follow.js`) | **Another connection** per screen, start → WatchWritingWorkspace for replay. Automatic reconnect configured; no onreconnected replay/watch handler in this helper. | storyPositionChanged → normalized DOM event → fragment fetch. Local project/book filter; documentGuid displayed in root but not checked. | + +A Context/Intent page commonly has two connections; a relevant shared header can add a third. Both workspace and follow clients publish the same scene event into the same DOM; in-flight/current-scene dedup often hides duplicate delivery. This is duplicated responsibility, not a second source of authority. + +### Client → server invocations + +All methods below are public on WordCompanionFollowHub. Parameters are JSON hub arguments; methods return DTOs unless stated otherwise. + +| Method | Request / return and effects | +|---|---| +| WatchCompanionPresence() | Returns WordCompanionPresenceStatus; joins user group. | +| RegisterCompanion(registration) | Registration fields in connection table; rejects mismatched supplied UserID; replaces per-user presence → presence/workspace broadcasts. | +| CompanionHeartbeat(heartbeat) | Version/machine/document-open/name/project/book; updates effective connection/time; returns status and broadcasts. | +| WatchWritingWorkspace(scope) | Nullable ProjectID/BookID; returns WritingWorkspaceStatus with windows, Word state and cached StoryPosition. | +| RegisterWritingWindow(registration) | BrowserWindowID, ProjectID, BookID, CurrentRoute, WritingRole, DisplayLabel → register and broadcast scoped status. | +| WritingWindowHeartbeat(heartbeat) | Same identifying fields → latest route/role/scope/LastSeen, status broadcast. | +| RequestWritingWindowFocus(scope, role) | Finds newest active role window in user+scope → targeted focus event; returns status, not proof the browser OS foregrounded it. | +| StartOnboardingManuscriptScan() | Resolves user onboarding Project/Book and latest live Companion → starts ScanID/session, sends targeted scan command; returns state. | +| ReportOnboardingScanProgress(progress) | OnboardingID, optional UserID, message/percent/counts; updates scan store and sends progress. No ScanID on this progress DTO. | +| ReceiveOnboardingScanChunk(chunk) | ScanID, optional UserID, OnboardingID, ChunkIndex, TotalChunks, TotalLength, Payload. Sorts by index, validates metadata/duplicate content/assembled length → Complete preview; returns state. | +| CompleteOnboardingScan(preview) | Alternate unchunked path: explicit onboarding/project/book context validation then store; host currently uses chunks instead. | +| FailOnboardingScan(failure) | OnboardingID/message, optional UserID; marks user's session failed and broadcasts. No ScanID on this failure DTO. | +| StartOnboardingProjectBuild(previewId, generateSceneTitles=true) | Calls approved Core Import build, progress callback, then targets marker instructions at latest Companion; returns build result. | +| CompleteOnboardingBuildMarkerSync(buildId, result?) | MarkerSyncClientResult: PreviewID, MarkerStatus, Message, MarkersChanged, SaveState, SaveApi, Host, Platform, Version, DocumentGuid/Url, error name/code/message. Persists status and broadcasts completion. Does not validate build ownership/document/session here. | +| RequireOnboardingBuildManualSave(buildId, message, result?) | Persists UserSaveRequired and broadcasts manual-save progress. Same ownership gap. | +| FailOnboardingBuildMarkerSync(buildId, message, result?) | Persists Failed; diagnostics logged/passed to repository; broadcasts failure progress. Same ownership gap. | + +### Server → client events + +| Exact event | Recipient / payload / trigger | +|---|---| +| WordCompanionPresenceChanged | User group; WordCompanionPresenceStatus: user, connected/status, version/machine/document name/open, linked project/book, current position, connection/heartbeat times; register/heartbeat/disconnect/stale expiry. | +| WritingWorkspacePresenceChanged | User group; WritingWorkspaceStatus: user/project/book, Word connected/document flags, Word project/book/current position, Windows array + latest Launcher/Context/Intent; window/Word state changes. | +| WritingWorkspaceFocusRequested | Selected role connection; `{WritingRole, ProjectID, BookID}`; focus request. Client calls window.focus best-effort. | +| **storyPositionChanged** | User group; `{Source:"WordCompanion", ProjectId, BookId, ChapterId, SceneId, CanonicalUrl, Position}` from HTTP current-scene controller after DB validation. Position is project/book/chapter/scene, **not DocumentGuid**. | +| ScanCurrentDocument | Selected Word connection; ManuscriptScanCommand `{ScanID,UserID,OnboardingID,ProjectID,BookID,RequestedUtc}`. | +| OnboardingScanStateChanged | User group; initial scan state (ScanID, status/message/counts/progress/preview/timestamp). | +| OnboardingScanProgress / OnboardingScanCompleted / OnboardingScanFailed | User group; scan state after progress/chunk completion/failure/disconnect. | +| OnboardingBuildProgress | User group; status/message/percent/preview/build/count/marker fields according to phase. | +| UpdateOnboardingBuildMarkers | Selected Word connection; OnboardingManuscriptBuildResult includes build/preview/project/book/document IDs, chapter/scene/character mappings, paragraph-index/tag/title/prefix marker instructions and structure summary. | +| OnboardingBuildManualSaveRequired | User group; build progress with BuildID, PreviewID, UserSaveRequired. | +| OnboardingBuildMarkerSyncCompleted | User group; `{buildId,markerStatus,previewID}`; user-confirmed save or marker no-op. | +| OnboardingBuildCompleted | Browser listener exists, but **no emitter found** in inspected server/JS source. Actual build action also consumes method return; marker completion drives later redirect. Do not create a required event from this orphan listener. | + +Contract casing varies intentionally in the existing JavaScript (`field`, camel/Pascal fallback). Record exact endpoint DTOs before creating a new transport; do not port by guessing field casing from UI labels. + +### Existing live position flow + +```mermaid +sequenceDiagram + participant W as Word document + participant P as Task-pane host JS + participant A as HTTP current-scene API + participant D as SQL validation + participant M as In-memory presence + participant H as Follow hub/user group + participant B as Context/Intent browser + W->>P: DocumentSelectionChanged + P->>P: 1.2s idle, generation check, cache match, resolve IDs + P->>A: POST runtime/current-scene (GUID + project/book/chapter/scene) + A->>D: WordCompanion_Runtime_CurrentScene_Validate(UserID,...) + D-->>A: Authorized active linked position or no row + alt valid + A->>M: UpdateCurrentStoryPositionAsync + A->>H: storyPositionChanged (no GUID or sequence) + H-->>B: Broadcast to user's connections + B->>B: Normalize; local project/book filter; dedup + B->>A: Separate Writing/Context/Scene or Intent/Scene GET + else invalid + A-->>P: 400; existing cached browser position is not cleared + end +``` + +The final GET is routed to WritingController, not WordCompanionController. Diagram places it at the HTTP boundary to show transport; its services are detailed below. + +### Ordering, duplicates, disconnects and feedback loops + +- Word local generation checks protect scene snapshot/display/count/suggestion handling during new selection activity. They do not add a server revision: an already-sent stale write may still commit. HTTP positions can arrive out of order; there is no sequence/session compare in the controller or store. +- Chunk assembly accepts equal duplicate chunks while Running, rejects conflicting duplicates and metadata changes, concatenates in index order and checks total length. Completed sessions reject subsequent chunk retries; there is no resume/last-ack protocol exposed to the host. Progress/failure messages lack ScanID and can affect a replacement scan for the same onboarding ID. +- Word notification signature is project:book:scene only. A successful notification can remain suppressed across a reconnect/server restart when staying in the same scene, until context/signature reset. Reconnected presence carries no scene and cannot replay the lost cached position by itself. +- Server presence is one mutable record/UserID; registration replaces it and another document's heartbeat can replace the effective connection again. It is not robust multi-document/multi-machine arbitration. An old disconnect is guarded against taking a newer connection offline, which should be retained. +- Window presence is keyed user+BrowserWindowID, filtered by optional project/book, latest role selected by LastSeen. It supports several windows but no explicitly chosen active-document session. Native multi-instance Word must add that missing identity. +- Context/Intent dedup compares scene/chapter and pending IDs. It does **not** abort older requests or check response generation. Isolated real-helper reproduction loaded scene 12 then delayed scene 11 and ended displaying scene 11. +- Follow helper has no onreconnected watch/replay; workspace role re-registration provides status events but does not itself make `writing-follow` consume the returned current position. New future position events may recover; a stationary cursor after reconnect is not guaranteed to recover the display. +- Current Word position is not explicitly cleared when scene resolution fails/unlinks or cursor is outside recognized manuscript. Disconnect hides current position in status, but follow fragments may retain old content; a status label is not proof the displayed scene is current. +- There is no Word navigation feedback loop to suppress because Context/Intent do not command Word selection. They publish local DOM story-position events; hub events are not automatically re-posted to the current-scene API. Duplicate UI updates are partly suppressed by current/loading checks, not an end-to-end message identity. +- [workspace-bridge.js](../../PlotLine/wwwroot/js/workspace-bridge.js) is a **separate** paired map/detached-browser BroadcastChannel system: user/project/token/sender/sequence validation, scene-selected/open-scene/story-state messages and fallback navigation. It observes the DOM position bus but does not provide Context↔Intent↔Word bidirectional synchronization. Its token/session and ordering protections must not be attributed to the Word hub. + +## 5. Context, Intent and multi-screen operation + +### Context: content and sequence + +Context shows canonical scene **Overview, People, Relationships, Place, Story**. It uses StoryContextService.GetForSceneAsync → SceneService.GetEditAsync and validated project/book position, RelationshipMapService.GetAsync and optional FloorPlanService.GetEditorAsync. Content includes summary, POV/time/location/revision/purpose/outcome/continuity; character appearance/state/knowledge/attributes; relationship graph/state; place/floor plan; thread events/knowledge/dependencies. It consumes canonical materialized story data; merely receiving new Word text is not automatic reanalysis of those facts. + +```mermaid +sequenceDiagram + participant P as Companion + participant C as Context window + participant H as Follow hub + participant WC as WritingController + participant S as StoryContext/scene/map/floor-plan services + P->>C: window.open Context with project/book/chapter/scene/GUID + C->>WC: GET Writing/Context + WC->>S: BuildDisplayAsync(sceneId, scope) + S-->>C: Full Razor page and initial scene or waiting state + C->>H: Role connection: RegisterWritingWindow(Context) + C->>H: Follow connection: WatchWritingWorkspace(scope) + H-->>C: Cached current position when available + H-->>C: storyPositionChanged on later Word movement + C->>C: Normalize; scope/dedup; retain active tab + C->>WC: GET Writing/Context/Scene with IDs + WC->>S: Rebuild canonical context + WC-->>C: _WritingContextContent fragment + C->>C: Replace HTML, rewire tabs/role, restore tab + opt User manually selects another scene + C->>C: DOM story-position event; same fragment path + Note over C,P: No command to Word; no server broadcast of manual selection + end +``` + +### Intent: content and sequence + +Intent is not a duplicate Context screen. It combines scene context and chapter workflow/goals via WriterWorkspaceService.GetChapterWorkflowAsync. Tabs are **Plan, Must Include, Notes, Threads, Checklist**: chapter summary/purpose/goals, emotional goal/reader takeaway, scene expectations and outcome, planned inclusions/notes/thread/checklist data. It can render **chapter-only intent**, with chapter selector and scenes for that workflow, before a scene is chosen. Context requires a scene. + +```mermaid +sequenceDiagram + participant P as Companion + participant I as Intent window + participant H as Follow hub + participant WC as WritingController + participant SC as StoryContextService + participant WF as WriterWorkspaceService + P->>I: Open Intent with scope and resolved chapter/scene + I->>WC: GET Writing/Intent + opt Scene provided + WC->>SC: GetForSceneAsync; resolve authoritative chapter + end + WC->>WF: GetChapterWorkflowAsync(chapter) + WC->>WC: Verify chapter project/book against scope + WC-->>I: Full Intent or waiting/missing display + I->>H: RegisterWritingWindow(Intent) + separate WatchWritingWorkspace + H-->>I: Replay/current storyPositionChanged + I->>WC: GET Writing/Intent/Scene (scene or chapter) + WC->>SC: Scene context when present + WC->>WF: Chapter goals/workflow + WC-->>I: _WritingIntentContent fragment + I->>I: Replace and rewire, retain active tab + opt Manual chapter/scene dropdown + I->>I: Local canonical-position event; reload Intent + Note over I,P: Does not navigate Word or publish to other browser windows + end +``` + +Both screens store active tab in origin-localStorage under different keys, not database/user/document-specific preferences. Current scene is local fragment state plus server cached Word position; URL initial state and manual browsing are also supported. `data-document-guid` is present in markup but not used to route/filter follow updates. Return of a same-scene event does not reload changed planning data because scene-ID dedup is used; explicit reload/navigation may be needed. + +### Combined multi-screen responsibilities + +```mermaid +sequenceDiagram + participant W as Word document/task pane + participant L as Writer launcher (browser) + participant H as Hub and presence stores + participant C as Context display + participant I as Intent display + W->>H: RegisterCompanion; 25s heartbeat (user/book, not document session) + L->>H: Register Launcher; WatchWritingWorkspace + L->>L: Detect screens/permission; choose saved layout + L->>C: Open named Context_Book_N or reuse/focus + L->>I: Open named Intent_Book_N or reuse/focus + C->>H: Register Context window; 15s heartbeat + I->>H: Register Intent window; 15s heartbeat + W->>H: HTTP-validated story position broadcast through user group + par Independent views + H-->>C: storyPositionChanged; Context HTTP fragment + and + H-->>I: storyPositionChanged; Intent HTTP fragment + end + L->>H: RequestWritingWindowFocus(scope, role) if local focus fails + H-->>C: Targeted focus request (best effort) + Note over W,I: Browser layout does not move/focus Word via COM + Note over C,I: Manual browser selection stays local; no mutual or reverse Word command +``` + +Stable names are `PlotDirectorContext_Book_` / `PlotDirectorIntent_Book_` with project/general fallback. Popup sessionStorage clone protection creates distinct window IDs; reload preserves the owner identity. Multiple windows for a role are possible; server focus selects latest active one. `window.getScreenDetails` and window-management permission choose display bounds; unavailable/denied permission falls back to ordinary windows. Three displays default Context left, Intent right and nominal Word middle; two-display preference selects primary supplementary role. This is a browser layout suggestion, not an implemented native Word monitor manager. Focus and popup acceptance remain browser-policy dependent. + +**Observed launch defect:** `writing-workspace.js:361` reads undeclared `currentRole` when there is no existing Intent window. A no-network VM execution of the actual script reproduced ReferenceError after opening Context. Existing browser regression first attempts blocked launch without asserting its message, then opens Context/Intent individually before testing reapply; this allows the fresh-Intent branch to be missed. No repair was made. + +Migration acceptance must preserve independent/scoped windows, both opening paths, tab state, manual navigation, chapter-only Intent, window reuse/focus, blocked-popup fallbacks, reconnect replay, and several books/windows. Add explicit document/session choice and stale-response protection rather than preserving the current ambiguous routing. + +## 6. Manuscript synchronization, ownership and scale + +### Different meanings of “import” and “sync” + +| Path | Word → PlotDirector | PlotDirector → Word | Ownership implication | +|---|---|---|---| +| Older task-pane import | Chapter/scene titles, sort order, counts, document GUID/binding version; optional separate character discovery text. | Binding settings; author-invoked ID attachment is separate. | Does not preserve prose through its structure DTO. Do not equate imported structure with stored scene source. | +| Browser-led Core Import | Plain chapter text, structural paragraph map, source paragraph text/flags/Word indexes, chapter IDs if present; reviewed structure and server analysis produce SceneManuscriptSources. | Marker instruction list with DB chapter/scene IDs at Word paragraph indexes; manual save handshake. | Word supplies prose; server derives scene boundaries/title suggestions and planning metadata without rewriting Word prose. | +| Runtime scene follow | Document GUID and IDs → validated scene position; local scene text used for detection. | No Word cursor instruction. | Browser follows resolved Word location. | +| Runtime count/suggestions | Actual word count/date; matched entity IDs. | Planning brief/available entities/status for pane display. | Prose edits do not refresh canonical source text or trigger Story Intelligence automatically. | +| Legacy sync API | Titles/order/counts plus optional DocumentId/ContentHash. | IDs/results only. | No strong text-hash conflict check, no general structural diff/archive propagation. | +| Maintenance create/link/apply | Explicit accepted structure additions/matches. | Controls/bookmarks attach IDs; no body text writer. | Partial operations can leave server and document temporarily inconsistent. | + +### Structural extraction and identifier semantics + +There are **three parsers**, with materially different rules: + +1. `buildDocumentStructure` (H2084): Heading 1 chapters; Heading 2 or canonical scene markers; also supports scene marker at chapter heading; used by legacy/full-document/manual operations. Text/style selection matching finds the first matching paragraph. +2. `buildFirstRunImportStructure` (H2170): Heading 1 chapters; initial scene per chapter; optional exact `***` / `###` scene breaks. Heading 2 is not the general splitting rule in this path. Structure/counts and a separate joined documentText for discovery are built; heading counting differs from runtime. +3. `buildRuntimeDocumentStructure` (H2264): snapshots paragraph indexes/styles/IDs; Heading 1 chapters; canonical PD-SCENE markers and optional separator scenes; bounded start/end index cache. Presence of any canonical scene anchor changes fallback behaviour. Raw body text is reread later using these cached boundaries. + +The browser-led scan (H2378) is another extraction projection: ignore front matter before first real Heading 1; retain included chapters, normalize each paragraph's internal whitespace/line separators; omit chapter headings, Heading 2 headings and separators from prose source flags. `ParagraphMap` links structural ordinal back to original Word paragraph index; `SourceParagraphs` retains blank/heading/separator/inclusion flags. This is **plain-text source custody, not rich-text/OOXML fidelity**: inline formatting, comments, tracked-change semantics, headers/footers/footnotes and other stories are not captured by body paragraph text extraction. Word remains authoritative for those. Localized/custom heading styles, repeated headings, tables and protected/track-changes documents need host-specific qualification. + +Marker tags are `PD-CHAPTER-` and `PD-SCENE-`. Exact tag first, same-prefix control reuse next; title/tag/appearance are assigned. Office.js insert tries Content, Start, Whole ranges with sync at each attempt. Fallback bookmark name is uppercased underscore form `_PD_CHAPTER_` / `_PD_SCENE_`, max 40 characters, at paragraph start. Readers load controls and hidden/adjacent bookmarks and use first usable matching marker. No general document-wide duplicate-ID repair/unique occurrence registry was found. Copy/paste or Save As can duplicate both markers and the document's GUID metadata; current code does not establish a new instance identity automatically. + +Binding settings are four keys: `plotdirector.word.documentGuid`, `.boundBookId`, `.boundProjectId`, `.bindingVersion`. These are **Office add-in settings**, not proven Word CustomDocumentProperties. Their add-in-scoped persistence must be understood before native migration; changing the add-in ID or simply reading a similarly named custom property is not an evidence-backed migration. Microsoft describes the per-document/add-in settings property bag and saveAsync semantics in [Persist add-in state and settings](https://learn.microsoft.com/en-us/office/dev/add-ins/develop/persisting-add-in-state-and-settings). A real DOCX package and native read-back test are required to determine the bridge. + +### Full scan/build/save flow + +```mermaid +sequenceDiagram + participant B as Onboarding browser + participant H as Hub + participant P as Word task pane + participant W as Word document + participant S as Scan store / OnboardingService + participant A as Chapter analysis / SQL sources + B->>H: StartOnboardingManuscriptScan + H->>P: ScanCurrentDocument (ScanID + scope) + P->>W: Read body paragraphs/styles/heading anchors + W-->>P: Plain text and paragraph indexes + loop 128 KiB JavaScript-character slices, sequential acknowledgement + P->>H: ReceiveOnboardingScanChunk + H->>S: Validate and assemble in memory + H-->>B: Progress / Completed + end + B->>S: Review chapters; ready-to-import + B->>H: StartOnboardingProjectBuild(previewID) + H->>S: BuildApprovedStructureAsync + S->>A: Analyze approved chapters, create canonical structure/mappings + S->>A: Persist chapter/scene source, statistics, derived context + H->>P: UpdateOnboardingBuildMarkers + P->>W: Attach markers at indexed paragraphs + P->>H: RequireOnboardingBuildManualSave + H-->>B: UserSaveRequired (90%) + W->>W: Author saves manuscript + B->>H: CompleteOnboardingBuildMarkerSync(UserConfirmedSave) + H->>A: Persist build marker status/timestamp + H-->>B: Marker sync completed; proceed +``` + +Server analysis is not prose authoring. `ManuscriptStructureAnalysisService` loads `Chapter-Structure-Prompt-V2.md`, numbers structural paragraphs, validates returned boundaries against reversible source mappings and retries malformed AI JSON once. `OnboardingService.AnalyseApprovedChaptersAsync` processes included chapters sequentially; its latency includes provider/validation work. It creates canonical DB scenes and retained source. Later Story Intelligence review must obey the existing persisted candidate/materialisation contract; the replacement should reuse it rather than create a second interpretation pipeline. + +### Change detection, batching, retry and offline behaviour + +- Only DocumentSelectionChanged is registered by the host. “Typing idle” is inferred from that event, not a complete text-change journal. `runtimeGeneration` and pending flags coalesce local work; no Office paragraph-change subscription is implemented here. +- `findSelectedParagraphIndex` matches trimmed text/style against cached paragraphs and chooses the match nearest the previous index. A new/edited paragraph that no longer matches falls back to the old current index; blank selection can do the same. Insertion/deletion can shift cached scene boundaries. A full manual structure refresh is the available recovery path. +- A “current scene” snapshot loads **all body paragraph text**, then slices the selected scene in JavaScript (H3384); it is not an incremental Word range read. Runtime model calls may be reduced by debounce/cache, but COM bridge work still scales with manuscript size. +- Onboarding chunks are 128×1024 **JavaScript characters**, not compressed bytes. Hub receive limit is 1 MiB. The full preview is assembled and JSON-parsed in memory; the host retains full paragraphs/preview/serialized payload. There is no streaming Word extraction, durable resumable upload or bounded total chunk/payload allocation policy in ScanPreviewStore. Equal duplicate chunks are handled only while scan is Running. +- Existing `WordCompanionScanChunksAssembleFullNovelPayloads` test constructs 42×58×82-word synthetic data (200k+ words) plus a single 200k-word paragraph, passes it through the store and checks retained chapter/source data. This proves the **in-memory assembly algorithm** for that fixture, not Office extraction latency, HTTP/SignalR network delivery, editor responsiveness or 190k-word end-to-end performance. Compressed size is measured by that test; live upload is not gzip because of that measurement. +- HTTP fetch has no per-request timeout/AbortController/exponential backoff/idempotency key. Generic errors show HTTP status; structured server message bodies can be lost. A successful server create followed by local Word failure can leave a retry/relink situation. SQL first-run import is transactional; maintenance apply is intentionally per-item, and Core Import has persisted-build resume logic but volatile preview dependencies. +- No persistent local outbox, offline delta queue, revision acknowledgement or conflict-resolution UI exists. Word editing remains usable offline; pane/network tasks fail or await reconnect. The PWA [service-worker.js](../../PlotLine/wwwroot/service-worker.js) explicitly has no fetch caching, offline page or background sync. +- A text edit preserving word count produces no runtime server prose update. ContentHash in old DTOs does not establish conflict detection; the inspected live scene-sync procedure accepts it without using it for concurrency. No reliable document dirty/revision/hash handshake is used before applying marker instructions. + +### Every identified Word-mutating operation + +| Operation and initiator | Mutation | Prose authority / risks | +|---|---|---| +| Bind/resume import or unlink, user/task-pane driven | settings.set/remove + settings.saveAsync | Changes add-in metadata; no text assignment. Save As/copy identity and partial server/local failure need a migration policy. | +| Attach IDs, create/link chapter/scene, apply structural maintenance, user initiated | Control tag/title/appearance updates; control insertion; fallback bookmark insertion/deletion | No insertText/insertHtml/OOXML/prose writer found. Wrapping ranges changes document structure and can affect nesting/undo/protection. Per-operation sync/failure can leave partial markers. | +| Core Import build, browser initiated and server-commanded | Same marker helper using server paragraph indexes | **Server can modify metadata in Word.** No revision/document-instance precondition; silently skips unavailable indexes. Does not intentionally modify prose but can annotate wrong text if manuscript moved. | +| Clean/unlink, explicit user confirmation | Tagged controls `delete(true)` in Office.js; settings removal; feature-detected document.saveAsync helper | keepContent=true preserves content in Office.js; formatting/comments/tracked-change preservation not desktop-proven. Does not remove fallback bookmarks; ignores save result. | +| Manual Word save confirmation / user editing | Author saves/edits in Word | Browser/Companion acknowledgement is self-report, not disk verification. Marker change and setting persistence should be qualified separately. | + +No Word selection `.select()`, document body text replacement, generated manuscript skeleton writer, merge-back edits, automatic Word scene deletion or bidirectional prose reconciliation was found in the current host. Those may appear as ambitions in the v2 specification; they are **not confirmed existing functionality**. Word-linked archive/delete protections exist server-side (migration 094 guards), but the current runtime does not implement the specification's automatic “delete in Word → archive in PlotDirector” loop. + +## 7. Persistence and related server functionality + +All inspected application data access is Dapper/stored-procedure based. [Database evidence](2026-11-04-word-companion-database-evidence.json) records live Development definitions and direct dependency metadata; dynamic SQL/application-mediated dependencies need the additional sources below. It intentionally contains no connection strings or author data. + +| State | Durable storage / writer / reader | +|---|---| +| Manuscript identity and binding | `ManuscriptDocuments`: document GUID, book/project, binding version, created user/date, LastOpenedUtc/LastSyncUtc, active flag. ManuscriptDocument_Save/GetByGuid/GetByBook/UpdateLastOpened/UpdateLastSync/UnlinkBook; [ManuscriptDocumentRepository](../../PlotLine/Data/Repositories.cs#L2423). | +| Structure and link metadata | `Books`, `Chapters`, `Scenes`: manuscript-linked flags, ManuscriptDocumentID, ExternalReference, LinkedUtc plus canonical titles/order/archive. SQL 094 introduces ownership fields; 095/219 import; legacy create/sync API has different linkage semantics. | +| Draft progress / planning | `SceneWorkflow` actual count/last-worked/revision/planning fields; `ChapterGoals` and chapter workflow used by Intent/Writer. Count sync does not write scene prose. | +| Canonical source | `ManuscriptStructuralChapterSources`, `SceneManuscriptSources`: text/counts, paragraph/source boundaries/provenance, structural parsed JSON. OnboardingBuildRepository's dedicated source SPs; consumed by statistics, Core Import/Story Intelligence. Not updated by routine count sync. | +| Build recovery | `OnboardingManuscriptBuilds`, ChapterMap/SceneMap/CharacterMap: preview/project/book/document mappings, created/reused counts/status/marker-save timestamps. Build/GetByPreview and MarkerSync* SPs. SQL build can resume; scan/review preview dictionaries do not survive restart. | +| Scene associations | `SceneCharacters`, canonical `SceneAssetLocations`, asset events/custody and `WordCompanionSceneLocations`/primary scene location are read/written through current scene companion/link procedures. Historical `WordCompanionSceneAssets` exists in migrations; do not assume it is the current asset source—live dependency metadata points at canonical asset tables. | +| Runtime suggestions | `SceneCharacterSuggestions`, `SceneAssetSuggestions`, `SceneLocationSuggestions`; alias tables and entity canonical names used for detection. API records suggestions; ScenesController accept/reject actions (lines 974–1116) invoke existing character/asset/location services and canonical materialisation SPs. Preserve settled user decisions/idempotency. | +| Core Import downstream | UserOnboardingStates and CoreImportBasicLocation review tables, source/statistics, persisted Story Intelligence runs/results/candidates, canonical knowledge/relationships/threads/metrics. These are server-owned domain functionality, not an Office implementation to duplicate. | +| Permissions/subscriptions | `ProjectUserAccess`, user/security stamp and subscription state; source of authorization/entitlement. Client metadata cannot bypass them. | +| Transient state | Word presence, window presence, current position, scan chunks/previews/reviews/progress in process memory; task-pane caches/snapshot/generation and browser preferences in their stated scopes. No durable per-document live session ledger. | + +Runtime current-scene validation confirms GUID/active manuscript, owning project/book/chapter/scene, linked scene and access/archive conditions; do not drop it merely because a future agent is local. MarkerSyncCompleted/UserSaveRequired/Failed procedures instead accept BuildID without UserID/ownership: that difference is material (finding D01). + +The [v2 specification](../../PlotLine/Docs/Features/PlotDirector_Word_Companion_v2_Specification.md) and [archived API design](../../PlotLine/Docs/Archive/WordCompanionAddInAndSyncAPI.md) are intent/history. “Invisible sync,” linked deletion, skeleton generation and broadly bidirectional planning should not be assumed implemented from those documents. Conversely, Core Import's AI scene detection, paragraph provenance and manual-save handshake are real code beyond the older small-add-in description. + +## 8. Office.js → VSTO / Interop mapping + +All native equivalents in this table are **design feasibility mappings**, not tested replacement behaviour. Every Word COM access should be owned and scheduled through Word's UI/STA context; sending RCWs/Word objects to an agent or Task.Run is not a safe boundary. Only immutable text/ID/index/version DTOs should cross it. + +| Existing API/mechanism | Current purpose | Native equivalent / difference and risk | UI/STA access | +|---|---|---|---| +| Manifest ShowTaskpane/Home ribbon | Launch one hosted UI | VSTO Ribbon XML/designer + task pane/native minimal status UI. Preserve all existing commands somewhere, even if ribbon stays small. Windows desktop only; no automatic Mac/web replacement. | Ribbon/task pane creation and Word state: yes | +| Office.onReady, HostType.Word, context.diagnostics | Readiness/host/version diagnostic | ThisAddIn Startup/Shutdown + Application.Version/host/process/session diagnostics. Native availability is not a guarantee the document permits writes. | Word properties: yes | +| Word.run, context.sync, proxy load | Batched Word reads/writes | Direct Interop calls/COM proxies; there is no context.sync transaction/equivalent. Extract in bounded UI-thread work, then process immutable DTOs off-thread. Fewer bridge calls can help, but no measured performance promise. | Yes | +| document.body.paragraphs.load text/style/styleBuiltIn | Discover body structure/prose | Document.Content/Paragraphs and Style/built-in heading identities. Interop text has paragraph/end-of-cell markers, different range coordinates and stories; preserve intended scope/normalization explicitly. | Yes | +| getSelection().paragraphs | Cursor context | Application.WindowSelectionChange/Selection.Range with Word range start/end. Better positional evidence than text matching, but document/window identity and stale ranges must be handled. | Yes | +| Office.EventType.DocumentSelectionChanged add/removeHandlerAsync | Idle-triggered tracking | Application WindowSelectionChange plus DocumentOpen/NewDocument/DocumentChange/BeforeClose/BeforeSave and selected content-control events as appropriate. There is no universal reliable “all prose changed” event simply by porting this one handler. | Event handling/Word reads: yes | +| paragraph.contentControls / document.contentControls | Read PD IDs/cleanup count | Document/Range ContentControls, Tag/Title; hierarchical controls, nesting and protected content differ. Do not use control numeric runtime ID as replacement for persisted Tag. | Yes | +| getRange(Content/Start/Whole).insertContentControl | Attach markers without writing prose | ContentControls.Add over explicit Range; collapsed vs noncollapsed range, allowed content types, nesting/protection/undo need real tests. | Yes | +| control.tag/title/appearance=Hidden | Hidden control chrome + identity | ContentControl.Tag/Title/Appearance where supported. “Hidden” is not Font.Hidden and does not mean hide prose. Minimum Word versions must be established. | Yes | +| **control.delete(true)** | **Office.js: keepContent=true** | **Interop ContentControl.Delete(DeleteContents): preserve with false, not true. Copying the Boolean would delete manuscript content.** This is a critical semantic migration hazard. [Office.js reference](https://learn.microsoft.com/en-us/javascript/api/word/word.contentcontrol?view=word-js-preview) and [Interop reference](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.contentcontrol.delete?view=word-pia). | Yes | +| getBookmarks(true,true), insertBookmark, deleteBookmark | Hidden/adjacent fallback anchors | Range.Bookmarks/Document.Bookmarks, ShowHidden, Add/Delete; preserve underscore naming and bookmark endpoint semantics. Reader/writer/cleanup must support both marker families. | Yes | +| Office.context.document.settings get/set/remove/saveAsync | Add-in-scoped document binding | No established one-to-one mapping to CustomDocumentProperties. Inspect OOXML/add-in settings and implement a reviewed one-time adapter or migration; CustomXMLParts/properties could be a new format only with explicit versioning. | Word/package access on adapter boundary; no live RCW off-thread | +| Office.context.document.url | Display document name / diagnostics | Document.FullName/Name plus unsaved-document identity; distinguish cloud URL, file path, Save As and separate process/window. Avoid leaking paths to logs. | Yes | +| Feature-detected document.saveAsync helper | Cleanup save attempt; onboarding instead asks user | Document.Save/BeforeSave/SaveAs lifecycle. Handle read-only/cloud/AutoSave/unsaved path, cancellation and actual save completion; never silently save unrelated prose edits as a metadata side effect. | Yes | +| JSON.fetch + same-origin cookie | HTTP project/runtime operations | HttpClient async with explicitly designed client authentication. Browser cookie inheritance does not occur automatically. API authorization remains server-owned. | No Word access; network off UI thread | +| JS SignalR 8.0.7 | Presence/scans/follow routing | Microsoft.AspNetCore.SignalR.Client; qualify a compatible version/target for .NET Framework or put network stack in modern agent. It must be **ASP.NET Core** SignalR, not legacy Microsoft.AspNet.SignalR. | Network off UI thread; Word commands marshalled back | +| localStorage/sessionStorage/tab state | Pane UI choices and browser IDs | Native per-user preferences may replace pane choices; browser window identities/preferences should remain in browser. Distinguish durable document binding from local convenience. | Usually no; UI binding through UI thread | +| window.open/focus/getScreenDetails | Independent browser windows and placement | Preserve browser launcher or carefully approved shell activation. VSTO can coordinate Word windows, but cannot assume control of browser permission/focus. | Word placement yes; shell/browser paths separate | + +Microsoft documents Office's non-thread-safe object model, STA marshaling and busy-call failures in [Threading support in Office](https://learn.microsoft.com/en-us/visualstudio/vsto/threading-support-in-office?view=visualstudio). Rejecting/busy COM calls need bounded UI-aware retry/cancellation; a second process does not remove that constraint. Selection-event behaviour has its own limitations, including embedded documents ([WindowSelectionChange](https://learn.microsoft.com/en-us/office/vba/api/word.application.windowselectionchange)). + +VSTO remains .NET Framework rather than modern .NET ([Microsoft runtime policy](https://learn.microsoft.com/en-us/visualstudio/vsto/visual-studio-tools-for-office-runtime?view=visualstudio)). Shared server code targets .NET 10 and cannot simply be referenced wholesale by VSTO. Reuse protocol schemas/pure portable logic selectively; verify library/package compatibility. Office.js currently offers cross-platform Word integration ([Word add-ins overview](https://learn.microsoft.com/en-us/office/dev/add-ins/word/word-add-ins-programming-overview)); choosing native Windows VSTO requires a product decision about Mac/web users. + +## 9. Technical debt and reliability findings + +No fixes were applied. “Confirmed” below refers to inspected code paths or isolated reproductions, not a destructive live reproduction. Risk prioritization is an engineering assessment. + +| ID | Finding / evidence | Classification and implication | +|---|---|---| +| D01 | Hub Complete/RequireManualSave/Fail marker methods derive authenticated user but pass arbitrary BuildID to repository. Repository/SPs accept no UserID and update only WHERE BuildID. Confirmed in live Development procedure definition and source SQL 158. | **Confirmed authorization defect, high priority.** An authenticated caller can address another build if its ID is known. Did not invoke it. Require ownership and command/session association before any native reuse. Normal MVC filters do not protect hub methods. | +| D02 | Presence keyed by user, last registration/heartbeat wins; no document/session GUID in presence command routing. | **Confirmed design limitation, high multi-document risk.** Scan/marker commands can target an unintended open Word session. Current multiple browser-window support must not be mistaken for multiple-document safety. | +| D03 | Marker instructions index current paragraphs but do not verify preview revision, expected text or bound document GUID; missing indexes silently skipped. | **Confirmed unsafe precondition gap.** Wrong/partial markers possible after manuscript edits/switch; no Word+SQL atomic rollback. Treat mutation authorization as document/session/revision-scoped. | +| D04 | writing-follow allows concurrent fetches without latest-request check; isolated actual-script test displayed old scene after newer response. | **Reproduced race.** Add ordering/cancellation in eventual design; avoid silently showing stale context. | +| D05 | writing-workspace startWorkspace references undeclared currentRole when opening missing Intent. | **Reproduced ReferenceError** in isolated actual script. Existing test sequencing misses the fresh launch branch. This affects launcher Start, not every direct Open Intent path. | +| D06 | Runtime paragraph selection matches cached text/style; edited/duplicate/blank paragraphs can retain/choose wrong index. Body insert/delete doesn't rebuild boundaries automatically. | **Confirmed algorithmic limitation**, concrete cases evident in code; not desktop-measured. Incorrect scene/count attribution risk; native positional APIs help only with revision invalidation too. | +| D07 | Local generation checks do not prevent server accepting already-sent stale position/count requests; follow payload has no sequence/session/document ID. | **Confirmed protocol omission.** Late messages can change server/UI state; no conflict rejection. | +| D08 | Host initial/terminal SignalR failure retains connection object and/or drops heartbeat; follow reconnect does not request replay; scene signature suppresses repeats across cache loss. | **Confirmed recovery gaps.** Do not claim automatic reconnect fully restores live position. ASP.NET Core SignalR automatic reconnect does not retry initial start failures by itself ([client guidance](https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-8.0)). | +| D09 | Marker inspection/clean operate only on contentControls although reader/writer supports bookmarks. | **Confirmed cleanup omission.** Clean/unlink may report no remaining markers while fallback bookmarks survive. | +| D10 | Cleanup awaits save helper but ignores Saved/Failed/Unsupported; onboarding completion is self-reported, and absent marker indexes can still yield no-op completion. | **Confirmed save/ack reliability gaps.** Separate marker-applied, settings-persisted and document-saved states. Do not equate user acknowledgement with independent disk proof. | +| D11 | Current-scene notification requires valid scene; no server clear event on unknown/outside/unlink; cached browser display can remain. | **Confirmed stale-state gap.** Show freshness/source explicitly; do not silently retain authority. | +| D12 | H full-body text read for current-scene snapshot; per-marker context.sync; full JSON memory copies and sequential upload; multiple UI/hub connections. | **Confirmed cost drivers; performance impact unmeasured.** Profile 190k+ words before deciding process split or claiming VSTO acceleration. | +| D13 | Scan/review chunks/previews/build progress in singleton dictionaries, no durable outbox/resumable protocol/TTL cleanup of all retained previews; nested mutable state. | **Confirmed recovery/memory limitations; concurrency impact inferred.** Restart loses unfinished source/review, accumulated memory can grow; concurrent same-user clients require stress qualification. | +| D14 | Chunk path checks active session/ScanID but completion payload scope is not rechecked like alternate CompleteOnboardingScan; progress/failure lack ScanID. | **Confirmed validation inconsistency.** A new protocol should validate envelope/payload scope and command identity consistently; no cross-user data-write attempt made. | +| D15 | 6,635-line closure mixes Office, parsing, network, suggestions, UI and recovery; several structural parsers and duplicated hub connections. Legacy APIs/unused helpers and orphan build-completed listener coexist. | **Simplification opportunity**, not inherently a defect. Preserve capability/contracts, not the file's internal organization. | +| D16 | Manifest “development” config targets public domain; package 0.1.0, manifest 1.0.0.0, host 20C, server informational version are unrelated. | **Confirmed configuration/version ambiguity.** Need explicit environment/capability/version handshake; installed manifest environment remains unknown. | +| D17 | Count-only “sync” leaves SceneManuscriptSources unchanged; title deletion/rename reconciliation not a complete pipeline. | **Confirmed functionality gap relative to broader sync expectations**, not a hidden existing two-way prose feature. Decide required source freshness and structural authority before designing replacement. | +| D18 | Body-text extraction/regex detection/word splitting normalizes/omits formatting and nonbody content; English-style heading/name heuristics. | **Known scope/quality limitations.** No evidence for arbitrary-language/format-rich fidelity; do not promise Word's exact word-count semantics. | +| D19 | Cookie-authenticated JSON writes lack explicit CSRF policy; client auth cannot be transplanted to native agent; local paths/names/IDs appear in diagnostics. | **Security design work**, distinct from proved D01. Verify origin/CSRF, privacy, credential storage/revocation and native login; no speculative exploit claim. | +| D20 | Browser-led scan sends currentDocumentGuid (empty for an unbound document); server generates a GUID in BuildApprovedStructureAsync. UpdateOnboardingBuildMarkers writes anchors but not document settings; build result has ManuscriptDocumentID, not a binding payload. Only task-pane link/import calls writeDocumentBinding. | **Confirmed missing binding write-back on the initially unbound Core Import path.** If a separate binding step has not occurred, newly created server linkage is not persisted into Word by that handler; later runtime requires it. Do not assume marker success proves a resumable bound document. Actual affected-user frequency was not measured. | + +Existing tests provide useful but mixed-strength evidence. `PlotLine.Tests/Program.cs` includes many source-string assertions (routes/events/markers/tabs) and real in-memory presence/chunk assembly tests; source strings do not prove Word host operations. Browser writer-workspace/goals scripts exercise compiled Razor/real hub but emulate PWA and do not automate desktop Word. `WordTransferDatabaseTests` exercises real isolated HTTP/SQL structure/count/import/access/retry semantics, explicitly excluding desktop prose transfer. Core transfer tests exercise retained source/provenance. None is a measured Windows Office 190k-word qualification, native process-lifecycle/COM test, or proof that installed manifests use the expected environment. This investigation did not rerun mutation-capable SQL tests. + +## 10. Architecture comparison: in-process vs separate agent + +These are proposed designs, not existing implementations. Both must keep Word object-model ownership inside VSTO and leave canonical planning/domain rules on the server. + +| Concern | VSTO with in-process asynchronous components | Thin VSTO + local C# agent | +|---|---|---| +| Responsibility | Adapter + pure processing/network queues in one add-in process; explicit UI dispatcher. | Adapter handles COM/ribbon; immutable snapshots/commands over IPC; agent handles pure processing, HTTP/SignalR, outbox/retry. | +| Word extraction | UI/STA bounded work; background cannot safely read arbitrary Word objects. | **Same limitation.** Agent cannot make live COM extraction free; avoid agent automating Word out-of-process as a workaround. | +| Runtime/library options | .NET Framework compatibility limits; portable DTO/pure library reuse requires verification. | Modern .NET agent can use newer supported libraries while VSTO stays Framework. Strong potential reason for split, independent of performance. | +| Crash containment | Faults/heavy allocations can harm Word; good cancellation/error discipline essential. | Agent crash/heavy parsing separated; VSTO failure can still affect Word. IPC failure must leave editing functional. | +| Lifecycle/offline | Simplest lifecycle follows Word; durable outbox possible but worker stops with Word. | Can persist/retry after Word closes, if source snapshot is complete and authorized. Cannot apply Word changes after its document closes. | +| Multiple documents/instances | Per-Application/window/document registry and server session IDs needed. | Same registry plus per-Word-process/agent session routing; broker avoids multiple worker connections only with explicit design. | +| Installation/update | One add-in/signing/trust/version chain. | Two binaries/runtime prerequisites/autostart/repair/update coordination; partial updates and orphan agents are new failure modes. | +| Authentication | Native login/token model still required; not solved by being in Word. | Agent may centralize per-user login, encrypted token storage/revocation, but server needs a supported native authentication protocol. | +| Diagnostics | One process/log correlation; Word user impact needs care. | Cross-process correlation IDs and health states essential; richer support export possible but not automatic. | +| Engineering cost | Lower initial operational/protocol complexity. | Higher: IPC security/framing/flow control, compatible protocol rollout, lifecycle recovery, duplicate-worker avoidance. | + +**Provisional recommendation:** design a transport-independent Word adapter and protocol first. Start evaluation with a small, reviewed in-process prototype unless the approved requirements demand modern-runtime-only dependencies, offline/background continuation or demonstrated fault/memory isolation that warrants the agent. If those requirements are confirmed, the proposed split is reasonable and Windows named pipes are the leading IPC candidate. Do not make extraction/synchronization reliability conditional on a process split; D01–D11 are protocol/adapter issues in either architecture. + +### Agent feasibility and proposed IPC + +- Prefer a **per-user interactive agent**, not a Windows service controlling Word. One agent per Windows logon session may broker multiple Word processes; identify environment, account, Word process/application instance, document instance, persistent DocumentGuid and browser-follow session separately. Persisted document GUID is not a process/document-instance ID. +- Named pipes with framed, bounded, versioned DTO messages are a good Windows-local candidate: explicit pipe ACL to current user, local-only intent, peer/session validation, handshake and size/time/cancellation limits. Modern .NET `PipeOptions.CurrentUserOnly` checks user/elevation ([Microsoft API](https://learn.microsoft.com/en-us/dotnet/api/system.io.pipes.pipeoptions?view=net-10.0)); older VSTO Framework availability differs, so qualify explicit PipeSecurity/compatible APIs rather than assuming the same enum is usable everywhere. +- Loopback HTTP/gRPC is possible, but requires port discovery, browser-origin/CSRF protection, local authentication and firewall/URL policy. gRPC-over-pipes is an option only after validating the Framework client's HTTP/2/handler/library support; it is not a free drop-in. Direct COM IPC couples lifetimes/threading; memory-mapped files add synchronization complexity without evidence of need. Start with a simple authenticated pipe protocol unless measurement dictates otherwise. +- The agent must not receive or hold Word COM proxies. VSTO creates immutable snapshots on STA, with document revision/paragraph identities and cancellation. Pure parsing/hashing/serialization/compression/local detection/network IO can run in the agent or in-process background components. +- Launch-on-demand, per-session single-instance ownership, version handshake, crash backoff and idle shutdown need explicit policy. Agent startup after Word crash must not replay marker writes into a different document. Queued work must carry environment/account/document/revision/idempotency keys and expire or be superseded safely. +- Authentication proposal: supported native browser-assisted login/token issuance, revocable scoped credentials, per-user encrypted storage and logout/account-switch propagation. Existing server supplies cookie login only; OAuth/device-code endpoints must not be invented as currently available. Never scrape browser cookies/store account passwords to avoid designing auth. +- Installer design must qualify supported Office/Windows/bitness, VSTO Runtime/.NET Framework, signing/trust and per-user/per-machine scope. VSTO ClickOnce and Windows Installer are documented deployment paths ([ClickOnce guidance](https://learn.microsoft.com/en-us/visualstudio/vsto/deploying-an-office-solution-by-using-clickonce?view=visualstudio)); choose one and explicitly coordinate agent prerequisites/updates. A newer independently updated agent needs backward-compatible protocol negotiation, not a forced identical server build. +- Logging proposal: correlation envelope, redacted document identifiers, event/revision/operation IDs, timings, retries/ack state and bounded rotation. Exclude manuscript bodies/tokens/paths by default; deliberate diagnostic export needs author consent. Crash recovery must distinguish “not sent,” “server committed,” “markers applied” and “save confirmed.” + +## 11. Migration capability matrix + +The [complete CSV matrix](2026-11-04-word-companion-migration.csv) assigns a disposition, complexity, risk, dependencies and testing to **every F01–F36 feature**. It explicitly covers Context, Intent, multiple screens, presence/SignalR, imports and manuscript sync. Classifications are recommendations: + +- **Retain:** canonical domain, authorization, planning/review/source database and browser display functionality; no Office-specific rewrite required, though defects called out here still need separately authorized repair. +- **Reuse:** current validated DTO concepts, stored-procedure boundaries, source custody rules, idempotent build/mapping logic and tested matching concepts after qualification. +- **Replace:** Office.js host/manifest, document access, settings bridge, marker operations, selection adapter and native diagnostics/lifecycle. +- **Redesign:** native authentication, multi-document/session routing, revision/ordering/idempotency, durable work/retry and mutation acknowledgement; current internals are unsuitable to carry forward unchanged. +- **Investigate:** installed manifest environment, real Office marker/settings package compatibility, rich/protected/track-changes behaviour and large-document performance. + +“Retain Context/Intent” means preserve their capabilities and browser ownership, not ignore D04/D08. “Reuse SignalR contracts” means compatible/adapted server semantics, not immutable propagation of user-only routing. Some features have one primary disposition and explicitly named supporting changes in the CSV. + +## 12. Risks, unknowns and decisions required + +| Decision / unknown | Evidence needed before implementation | +|---|---| +| Windows-only scope | Supported Windows/Office versions, 32/64-bit, enterprise policy; number of Mac/web users and whether Office.js remains supported. | +| Agent justification | Representative measured STA extraction, memory/CPU, UI latency and supported network-library matrix; requirements for work continuing after Word closes. | +| Native authentication | Approved server/client flow, scopes, expiry/revocation/2FA/account switching, allowed environment endpoints and credential-storage policy. No native auth exists in this path today. | +| Settings/marker migration | Real linked DOCX files containing Office add-in settings, controls, hidden bookmarks, mixed/nested markers, Save As copies; read-only package inspection followed by later authorized round-trip tests. No actual manuscript file was provided. | +| Authoritative document/session | Policy for two documents for the same book, Save As/duplicate GUID, two Windows machines, multiple Word processes, multiple accounts/environments and which browser screens follow each. | +| Meaning of manuscript sync | Counts-only parity versus incremental canonical prose refresh, structural rename/reorder/archive, conflict policy and whether analysis reruns require explicit author approval/cost. Do not silently turn a transport migration into a prose replication feature. | +| Mutations allowed back to Word | Identifiers/metadata only; whether future explicit navigation is wanted. Any prose/skeleton write would be a new approved capability, not necessary parity. | +| Save/protection/undo | Cloud/AutoSave/coauthoring/track changes/protected documents and read-only files; whether metadata operations must create one undo step and how cancellation is handled. | +| Existing deployed Office behaviour | Installed manifest URL/version, actual Word host capabilities, cookie/webview navigation and monitor/popup behaviour. Source config targets public domain, but this inspection made no Production requests. | +| Server recovery/security | Ownership defect, scan lifetime/TTL, mutation authorization, version/feature negotiation, stale-position clearing and reconnect snapshot/replay strategy. | +| Performance threshold | Real 190k–250k+ word manuscripts, many short paragraphs vs huge paragraphs, repeated text, tables/blank lines and all editing scenarios. Define quantitative UI pause/memory/upload/recovery budgets before comparing architectures. | + +No inaccessible dependency was silently treated as verified. Microsoft Word desktop/VSTO/tenant installation and real documents were unavailable. The single supplied repository and its SQL metadata were accessible. Microsoft Range reference retrieval failed during external browsing; API minimum-version qualification remains explicitly open rather than asserting an unsupported requirement-set number. Microsoft documentation above supports platform constraints, not PlotDirector-specific runtime correctness. + +## 13. Recommended implementation phases — review first + +1. **Approve contracts and product boundaries.** Review this report and matrix; decide platform support, counts vs prose sync, document/session authority and native authentication. Record compatibility requirements and error/save states. Do not start with a broad rewrite. +2. **Define acceptance fixtures and capture existing Word packages.** Later, with authorization, capture representative linked/unlinked/mixed-marker documents and testable end-to-end scenarios. Establish no-prose-change/format/comment/track-change/undo invariants and quantitative 190k+ performance baseline. +3. **Separately authorize server reliability/security repairs.** Ownership checks, document-session/revision envelopes, ordered latest position, snapshot/replay/clear and idempotent marker acknowledgements. Maintain legacy clients through capability negotiation. These changes are not implemented by this investigation. +4. **Prototype only the Word adapter and compare architectures.** STA scheduling, positional selection, settings read-back, dual-marker read/write/cleanup and bounded snapshots. Measure in-process async and agent alternatives using the same manuscripts before selecting packaging. +5. **Port feature slices without duplicating domain logic.** Native ribbon/binding → read-only context/follow → count/suggestion sync → both import flows/markers/save/recovery → maintenance/unlink. Keep existing browser Context/Intent and canonical services; ensure parity for all matrix rows. +6. **Add agent only if decision gate supports it.** Implement reviewed IPC/auth/version/lifecycle/outbox policy; test crash/restart/account switch/parallel Word instances and stale command refusal. A process split must retain fast no-network Word editing. +7. **Qualify migration and controlled rollout.** Desktop STA/COM tests; real SignalR/API/SQL authorization tests; multi-window and multi-document reconnect/out-of-order tests; no-data-loss DOCX comparisons; signed installer/update/rollback matrix. Retain original client until native parity and source/marker migration are proved. + +This investigation ends at documentation and evidence. No replacement code, migration, refactor, deployment, new native project or application repair has been started. Await review before implementation. diff --git a/Docs/Investigations/2026-11-04-word-companion-migration.csv b/Docs/Investigations/2026-11-04-word-companion-migration.csv new file mode 100644 index 00000000..0221a50b --- /dev/null +++ b/Docs/Investigations/2026-11-04-word-companion-migration.csv @@ -0,0 +1,37 @@ +FeatureID,Capability,PrimaryDisposition,Complexity,Risk,DependenciesAndSupportingChanges,RequiredTesting +F01,Ribbon and task-pane launch,Replace,Low,Medium,VSTO ribbon/startup; supported Office builds,Load/unload; disabled add-in; Windows/Office bitness; retain all command entry points +F02,Authentication and account session,Redesign,High,High,Native authentication server decision; token/cookie separation,"2FA, expiry, lockout, logout/revocation, account/environment switching; no password/cookie scraping" +F03,Project/book listing and book creation,Reuse,Low,Medium,"Existing authorized APIs, entitlements and DTOs",Owner/collaborator/foreign author; empty/archived projects; subscription denials +F04,Document binding,Replace,High,High,Office settings read-back; ManuscriptDocument_Save; identity policy,Existing linked DOCX; GUID conflict; Save As/copy; server-success/local-failure recovery +F05,Bound-document resume,Redesign,Medium,High,Document binding; runtime/book; session handshake,Offline vs invalid binding; two documents same book; reopened files; stale/inactive link +F06,Older pane first-run analysis,Replace,Medium,Medium,Heading/separator adapter; existing analyse DTO/SP,Explicit/nonexplicit scenes; empty content/front matter; localized/custom headings +F07,Older pane first-run import,Reuse,Medium,High,Existing transactional import and validation; new Word adapter,"Planned replacement confirmation, archival protection, repeat import, SQL/local metadata partial failure" +F08,Character discovery and selected creation,Reuse,Medium,Medium,Existing heuristic/name intelligence/API; source extraction,Unicode/name variants; false positives; count/selection limits; existing names and skip +F09,Browser-to-Word scan dispatch,Redesign,High,High,Document/process/session selection; hub contract,Wrong-document/machine routing; concurrent scans; account scope; disconnection +F10,Full scan extraction/chunk transport,Replace,High,High,STA snapshots; source mapping; reviewed upload protocol,190k+ measured Word extraction; long/short paragraphs; partial/out-of-order/duplicate chunks; memory budget +F11,Browser chapter review,Retain,Medium,Medium,Existing Onboarding UI/store; durability redesign separate,Review/inclusion/title/order; restart loss/recovery; cancellation; author scope +F12,Core Import canonical build/source custody,Reuse,High,High,OnboardingService; analysis/validator; source/build SPs,"Approved structure, reversible source boundaries, retry/resume, provider failure, canonical source/POV/chronology" +F13,Server-issued Word marker application,Redesign,High,Critical,Revision/document preconditions; STA adapter; build ownership,"Changed/switching document, stale indexes, missing marker instruction, partial writes, idempotent retry" +F14,Manual save/marker acknowledgement,Redesign,High,High,Owned build commands; actual Word save state; persistent statuses,"Manual/cancelled/read-only/cloud save, missing instructions, stale ack, another user build; no false completion" +F15,Current chapter/scene resolution,Replace,High,High,Word Range identity + existing DB ID/title resolution,"Repeated/edited/blank text, anchored/unanchored/nested markers, chapter-only positions" +F16,Edit and selection detection,Redesign,High,High,Word UI event model; revision invalidation and coalescing,Typing/paste/undo/reorder/delete; in-flight edits; focus/window changes; no blocking UI +F17,Explicit document/current-scene refresh,Replace,Medium,Medium,STA extraction; cache invalidation; existing API,Full rebuild after edits; event unsupported; interruption/cancel; meaningful errors +F18,Companion planning brief and status,Reuse,Low,Medium,Scene_Companion DTO/SP and canonical data,"Correct current scene, blocked reasons, nullable fields, revoked access; stale display indication" +F19,Runtime count synchronization,Redesign,Medium,High,Runtime count SP reused; revision/outbox/freshness contract,"Same-count prose edits, duplicate/late writes, last-worked date, offline retry, stale scene rejection" +F20,Legacy word-count API compatibility,Investigate,Low,Medium,Consumer/deprecation inventory; existing endpoint retained initially,"Known clients/version scope, authorization, compatibility; do not silently remove public operation" +F21,Legacy scene/manuscript sync APIs,Investigate,High,High,External consumer evidence; title matching and concurrency redesign,"Duplicate titles, create/partial retry, ordering, quotas; document/hash semantics; explicit retirement decision" +F22,Create/link chapter,Reuse,Medium,High,Existing API/entitlements; replace marker adapter,"Duplicate title/search, SQL create then Word failure, foreign chapter, manual confirmation" +F23,Create/link scene,Reuse,Medium,High,Existing API/entitlements; chapter resolution; native markers,"Wrong chapter, duplicate/empty title, foreign scene, partial create/link and repeat" +F24,Anchor attachment/repair,Replace,High,Critical,Interop controls/bookmarks; existing tag grammar,"Mixed/nested controls, fallback bookmarks, duplicate IDs, protection, byte/prose/format/undo invariants" +F25,Structural maintenance preview/apply,Redesign,High,High,Diff policy; existing create/link APIs; native markers,Ambiguous/missing/duplicate IDs; no implicit deletion; per-item recovery; revised document before apply +F26,Runtime entity suggestions,Reuse,Medium,Medium,Alias APIs/limits; pure detection qualified; snapshot revision,"Whole-word/Unicode aliases, conservative locations, cache refresh, stale responses, settled decision preservation" +F27,Scene links and suggestion review,Retain,Medium,High,Existing scene/review services + ownership; native pane integration,Characters/assets/primary/multiple locations; accept/reject idempotence; stale-scene write and author separation +F28,Live current position / SignalR routing,Redesign,High,High,Existing validation + extended document/session/sequence/replay,"Out-of-order/duplicate/clear/replay; multiple Word instances, documents, machines and accounts" +F29,Open browser Writer/Context/Intent,Replace,Medium,Medium,Shell/browser activation; scoped URLs and named browser roles,Real external browser vs webview; sign-in separation; popup denial; scope propagation +F30,Context screen and live follow,Retain,Medium,High,Existing canonical services/views; follow race/reconnect repair required,"All five tabs, scoped manual selection, snapshot replay, delayed fragments, multi-document filtering; no reverse Word command assumed" +F31,Intent screen and live follow,Retain,Medium,High,Existing workflow/goals/views; follow race/reconnect repair required,All five tabs; chapter-only and scene paths; manual chapter choice; state retention and ownership +F32,Multi-screen layout/window focus,Retain,Medium,High,Browser workspace roles/display preferences; launch defect separately addressed,"Fresh Start without Intent, reuse/focus, 1/2/3+ displays, denied permission, several books/windows; no implied native Word monitor control" +F33,Presence/connection/reconnect management,Redesign,High,High,Agent/in-process network stack decision; session-scoped server presence,"Initial failure, terminal reconnect, stationary cursor after server restart, lost events, stale timeout, multiple users/docs" +F34,Unlink preserving markers,Replace,Medium,High,Native settings adapter; existing server unlink retained,"Server/local partial failure, offline local-only confirmation, preserved planning data and markers" +F35,Clean/unlink removing markers,Replace,High,Critical,Dual marker cleanup + semantic Interop Delete(false); save policy,Keep prose/format/comments/tracked changes; bookmark cleanup; cancel/failed save; foreign controls untouched +F36,Diagnostics/progress/error recovery,Redesign,Medium,Medium,Correlation/version/operation IDs; local logging and server progress,"Redaction, bounded log rotation, recovery phases, environment clarity, UI responsiveness and support export policy"