feat: add hierarchical chapter AI review and safe Windows developer workflow

This commit is contained in:
Nick Beckley 2026-11-05 11:06:54 +00:00
parent af243d3a9b
commit baa1326caa
28 changed files with 722 additions and 77 deletions

View File

@ -36,11 +36,11 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
job.Submitted=true;job.Chapter.Paragraphs=job.Paragraphs.ToArray();job.Result.State="analysing";
_=Task.Run(async()=>{
AiChapterResult result;
try{result=await cloud.Analyse(job.Chapter,job.Stop.Token);}
try{result=await cloud.Analyse(job.Chapter,job.Token);}
catch(OperationCanceledException){result=new(){RequestId=job.Chapter.RequestId,State="cancelled",Message="AI analysis cancelled."};}
catch(Exception e)when(e is HttpRequestException or IOException or InvalidOperationException or System.Text.Json.JsonException)
{result=new(){RequestId=job.Chapter.RequestId,State="failed",Message=e is InvalidOperationException?e.Message:"Connection failed. Outcome may be unknown; explicit retry may incur another AI charge."};}
lock(gate){job.Result=result;job.Chapter.Paragraphs=[];job.Paragraphs.Clear();}
lock(gate){job.Result=result;job.Chapter.Paragraphs=[];job.Paragraphs.Clear();job.Finished=true;job.Stop.Dispose();}
});break;
case "ai-cancel": Clear(descriptor.SessionId);answer.Status="ai-cancelled";return answer;
case "ai-status":break;
@ -53,14 +53,15 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable
}
public void Clear(Guid session)
{
lock(gate)if(jobs.Remove(session,out var job)){job.Stop.Cancel();if(job.Submitted)_=cloud.CancelRemote(job.Chapter.RequestId);job.Paragraphs.Clear();}
lock(gate)if(jobs.Remove(session,out var job)){if(!job.Finished)job.Stop.Cancel();if(!job.Submitted){job.Finished=true;job.Stop.Dispose();}if(job.Submitted)_=cloud.CancelRemote(job.Chapter.RequestId);job.Paragraphs.Clear();}
}
public void Dispose(){lock(gate)foreach(var session in jobs.Keys.ToArray())Clear(session);}
private sealed class Job(AiChapterRequest chapter)
private sealed class Job
{
public AiChapterRequest Chapter=chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public bool Submitted;
public int Characters;public int Position=chapter.ChapterStart,NextParagraph=1,ParagraphStart;
public Job(AiChapterRequest chapter){Chapter=chapter;Position=chapter.ChapterStart;Token=Stop.Token;Result.RequestId=chapter.RequestId;}
public AiChapterRequest Chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public CancellationToken Token {get;}public bool Submitted,Finished;
public int Characters;public int Position,NextParagraph=1,ParagraphStart;
public StringBuilder Text=new();public List<AiParagraph> Paragraphs=[];
public AiChapterResult Result=new(){RequestId=chapter.RequestId,State="reading"};
public AiChapterResult Result=new(){State="reading"};
}
}

View File

@ -75,7 +75,7 @@ public sealed class CloudGateway : IDisposable
using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)};
request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access);
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);
if(response.StatusCode==HttpStatusCode.Unauthorized){SignOut();throw new InvalidOperationException("Sign-in expired. Connect again.");}
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});
// Bound server response before deserializing; never log a body/provider message.
await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192];

View File

@ -0,0 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.5</ApplicationVersion></PropertyGroup></Project>

View File

@ -37,3 +37,12 @@ Protocol v1 exposes **no remote Word mutation operation** and no server integrat
Analysis uses the same bounded paragraph stream. `snapshot-fragment` acknowledgements include progress percentage. A successful requested `snapshot-end` replies `analysis-complete`, `Progress=100` and the first `AnalysisPage`. `analysis-page` requires exact session/revision/snapshot and uses `Start` as zero-based row offset; it returns at most 40 rows. Candidate rows are suggestions (kind, Word position, paragraph ordinal, bounded title, confidence, evidence), never authorization to import or navigate a server scene. Summary includes approximate words, paragraphs, candidate totals and truncation notice. See Phase 2 report for heuristics and limits.
Analysis is incremental in the agent; no COM object crosses IPC and no analysis operation mutates Word. Candidate counts are bounded to 8,192/document and 32,768 globally. Cancellation uses existing `snapshot-cancel`; late replies are refused by the review's session/revision/snapshot guard. Disconnect invalidates the cache: reanalyse after reconnect. Native Context/Intent/server authentication is still deferred.
## Optional Phase 3 chapter AI
`chapter-ai-v1` advertises the additive native feature. `cloud-connect` sends only an author-selected HTTPS root; `cloud-status` returns sign-in status and at most 200 authorized book choices; `cloud-signout` discards the agent's memory-only grant and cancels native AI jobs. Credentials never enter IPC. The agent performs verifier-bound browser pairing over HTTPS; the browser uses normal PlotDirector cookie login and antiforgery approval.
After explicit author upload confirmation, `ai-begin` specifies one chapter's Start/End, book and request SnapshotId under the exact existing document session/revision. `ai-fragment` reuses the bounded paragraph DTO and chapter-local paragraph ordinals. `ai-submit` starts asynchronous agent HTTP processing and returns promptly; duplicate submits do not create another call. `ai-status` polls that request and pages results using Start as zero-based result offset (40 rows). `ai-cancel` cancels the exact job and best-effort server request. Lifecycle/revision retirement also cancels the job. The live session ID must be unique across Word instances; a foreign duplicate is refused.
Chapter capture is limited to 120,000 positions/text characters and 10,000 paragraphs. The server returns at most 500 validated AI scenes per chapter; the agent frames only 40 at a time. Suggested boundaries retain actual Word positions, provenance `AI`, confidence and bounded reasoning. Local/marker suggestions remain separate; their chapter ranges provide the upload bounds. No API or IPC operation imports scenes, rewrites text or inserts markers. Network uncertainty is not auto-replayed; explicit author retry is required and may incur a charge. Server deduplication is bounded to its process lifetime and a 30-minute cache.

View File

@ -1,8 +1,10 @@
# Native Word Companion — Phase 1 foundation and Phase 2 analysis
# Native Word Companion — developer foundation, structure and AI review
Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See [Phase 3 Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following.
Phase 2 adds optional local structural analysis through the existing snapshot/pipe path, with a native modeless review, progress, cancellation and per-document results. See the [Phase 2 report](../Docs/WordCompanion/2026-11-04-phase2-document-analysis.md) and [Windows analysis checklist](WindowsValidation/Phase2-Analysis.md). The author's Phase 1 Windows smoke test is build `1.0.0.3` at `726a3d5`; the Linux limitations below describe the original foundation. New Phase 2 Word integration still requires Windows qualification.
Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native authentication/session-aware server integration deferred).
Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native browser-paired chapter preview implemented; session-aware SignalR deferred).
This is a development foundation, **not a publicly installable replacement**. Office.js, its manifest, onboarding, Context/Intent and multi-screen UI remain present. Nothing in this tree automatically deploys or installs a component. The .NET Framework VSTO host has not been built or run in Word on the Linux development host.
@ -41,11 +43,11 @@ Selection reads are prioritized and repeated events coalesced. A completed snaps
Under IPC backpressure the pending value is retained and the UI yields; it does not reread Word or wait for agent space. Disconnect cancels extraction and reconnect schedules new snapshots. Documents are not retained in an unbounded agent or UI queue. On shutdown the add-in requests worker cancellation without joining it. No HTTP/SignalR/authentication, database, AI, prose parser, entity detector or sync retry runs inside VSTO.
The ribbon has status, Connect / Sign In, Synchronise Now, Settings and Diagnostics. Native server sign-in and prose sync are explicitly unavailable; Synchronise Now means **local structure refresh only**. No large pane/embedded website. Native metadata/marker helpers do not expose a remote mutation operation in protocol v1; no Word prose writer exists. Interop marker removal uses `Delete(false)` to preserve text.
The ribbon has status, Connect / Sign In, Synchronise Now, Settings and Diagnostics. Native server sign-in is available through Connect; prose sync is unavailable; Synchronise Now means **local structure refresh only**. No large pane/embedded website. Native metadata/marker helpers do not expose a remote mutation operation in protocol v1; no Word prose writer exists. Interop marker removal uses `Delete(false)` to preserve text.
## Server and protocol boundaries
The agent is not connected to the old user-only Word presence hub. Authentication and document-session-aware routing must be added in a subsequent reviewed phase. Browser cookie scraping, password storage and forged authentication are not implemented. Do not claim Context/Intent/native live synchronization; existing Office.js/browser coordination stays intact.
The agent is not connected to the old user-only Word presence hub. Native chapter preview now uses browser-approved, verifier-bound four-hour Data Protection grants with current security-stamp and book/subscription checks. No token or cookie crosses IPC or is saved in a Word document. Session-aware SignalR routing remains a subsequent phase. Browser cookie scraping, password storage and forged authentication are not implemented. Do not claim Context/Intent/native live synchronization; existing Office.js/browser coordination stays intact.
Server fixes in this branch independently retain hub signatures and event names. Migration 230 adds an atomic owned-build acknowledgement procedure. Old browser/Office.js callers may omit preview/document fields; the server still verifies authenticated build ownership, current access and the exact active manuscript/book/project association. Supplied identifiers must match. Completed acknowledgements are idempotent and cannot be regressed by a late failure. Code depends on migration 230 before any future server deployment; no live migration/deployment is performed by this prototype.

View File

@ -0,0 +1,58 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Protocol;
internal static class ChapterAiTests
{
public static async Task Run(Action<bool,string> check)
{
foreach(var bad in new[]{"http://example.invalid/","file:///tmp/site","https://user:password@example.invalid/","https://example.invalid/path","https://example.invalid/?query=1"})
{try{CloudGateway.ValidateOrigin(bad);throw new Exception("Accepted unsafe origin");}catch(ArgumentException){check(true,"native connection rejects unsafe site root");}}
var handler=new Provider();string browser="";using var cloud=new CloudGateway(handler,url=>browser=url);
cloud.Connect("https://example.invalid/");
await Wait(()=>cloud.Status().Status.StartsWith("Signed in"));
check(browser.StartsWith("https://example.invalid/native-companion/authorize?code=")&&cloud.Status().Books.Single().BookId==11,"browser-approved sign-in loads only authorised book choices");
check(handler.Submissions==0,"sign-in and local work never upload chapter prose");
using var jobs=new ChapterAiWork(cloud);var descriptor=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=4};
var id=Guid.NewGuid();
Message Send(string kind,ParagraphFragment? f=null,int offset=0)=>jobs.Handle(descriptor,new(){Kind=kind,SnapshotId=id,BookId=11,Start=kind=="ai-begin"?100:offset,End=120,Fragment=f},new(){Status="ok"});
check(Send("ai-begin").Status=="ok","AI chapter capture starts only after an explicit command");
var progress=Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="One chapter paragraph.",CompletesParagraph=true});
check(progress.Progress==100&&handler.Submissions==0,"bounded chapter capture reports progress without submitting early");
Send("ai-submit");Send("ai-submit");
await Wait(()=>Send("ai-status").Ai?.State=="complete");var result=Send("ai-status").Ai!;
check(handler.Submissions==1&&result.Scenes.Single().Start==100&&handler.Last?.ChapterStart==100&&handler.Last.Paragraphs.Single().Index==1,"duplicate submit uses one HTTP call and preserves exact chapter mapping");
var alien=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid()};
check(jobs.Handle(alien,new(){Kind="ai-status",SnapshotId=id},new(){Status="ok"}).Status=="obsolete-ai-request","another document cannot retrieve an AI result");
id=Guid.NewGuid();handler.Stall=true;Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Another chapter paragraph.",CompletesParagraph=true});Send("ai-submit");
await Wait(()=>handler.Submissions==2);Send("ai-cancel");
check(Send("ai-status").Status=="obsolete-ai-request","cancelled network chapter cannot reappear in review");
handler.Stall=false;handler.Deny=true;id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Paragraph.",CompletesParagraph=true});Send("ai-submit");
await Wait(()=>Send("ai-status").Ai?.State=="failed");check(Send("ai-status").Ai!.Message.Contains("denied"),"authorisation failure is isolated and actionable");
cloud.SignOut();check(cloud.Status().Books.Length==0&&!cloud.Status().Status.StartsWith("Signed in"),"sign-out forgets credential and book list");
var analysis=new DocumentAnalysis();analysis.Add(new(){ParagraphIndex=1,Start=0,End=12,Text="Chapter One\r",OutlineLevel=1,CompletesParagraph=true});analysis.Add(new(){ParagraphIndex=2,Start=12,End=17,Text="Body\r",OutlineLevel=10,CompletesParagraph=true});analysis.Add(new(){ParagraphIndex=3,Start=17,End=29,Text="Chapter Two\r",OutlineLevel=1,CompletesParagraph=true});
var chapters=analysis.Page(0).Items.Where(i=>i.Kind=="Chapter").ToArray();check(chapters[0].End==17&&chapters[1].End==29,"local chapters supply explicit nonoverlapping AI extraction ranges");
var manager=new SessionManager();var a=Guid.NewGuid();var b=Guid.NewGuid();var la=Guid.NewGuid();var lb=Guid.NewGuid();manager.Attach(a,la);manager.Attach(b,lb);
manager.Apply(la,new(){Kind="document",WordInstanceId=a,Sequence=1,Documents=[descriptor]});
check(manager.Apply(lb,new(){Kind="document",WordInstanceId=b,Sequence=1,Documents=[descriptor]}).Status=="foreign-session-identity","duplicate live session identity cannot cross Word instances");
}
private static async Task Wait(Func<bool> ready){using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!ready())await Task.Delay(20,stop.Token);}
private sealed class Provider:HttpMessageHandler
{
public int Submissions;public AiChapterRequest? Last;public bool Stall,Deny;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{
var path=request.RequestUri!.AbsolutePath;
if(path.EndsWith("/pair"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{code=new string('A',24)})};
if(path.EndsWith("/token"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{accessToken="test-only-grant"})};
if(path.EndsWith("/books"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new[]{new CompanionBook{BookId=11,Title="Synthetic test book"}})};
if(path.EndsWith("/cancel"))return new(HttpStatusCode.NoContent);
Last=await request.Content!.ReadFromJsonAsync<AiChapterRequest>(cancellation);Interlocked.Increment(ref Submissions);
if(Stall)await Task.Delay(Timeout.Infinite,cancellation);
if(Deny)return new(HttpStatusCode.Forbidden);
return new(HttpStatusCode.OK){Content=JsonContent.Create(new AiChapterResult{RequestId=Last!.RequestId,State="complete",Scenes=[new(){Start=100,End=120,Kind="Scene",Origin="AI",Title="Narrative interpretation",Reason="A change in narrative focus."}]})};
}
}
}

View File

@ -161,4 +161,5 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true))
stalledClient.Dispose();await stalledClient.Completion.WaitAsync(TimeSpan.FromSeconds(5));
}
await AnalysisTests.Run(Check);
await ChapterAiTests.Run(Check);
Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");

View File

@ -1,40 +1,93 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.WordAddIn
{
// Small modeless review window. No Word references and no network activity.
// Modeless, DPI-aware value-only review. Rendering is bounded to two 40-row pages.
public sealed class AnalysisWindow : Form
{
private readonly Label status=new Label{Dock=DockStyle.Top,Height=76,Padding=new Padding(8)};
private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Top,Height=16};
private readonly ListView rows=new ListView{Dock=DockStyle.Fill,View=View.Details,FullRowSelect=true};
private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(1100,0),Margin=new Padding(8)};
private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Fill,Height=6,Maximum=100};
private readonly TreeView local=new TreeView{Dock=DockStyle.Fill,CheckBoxes=true,HideSelection=false,ShowNodeToolTips=true};
private readonly TreeView ai=new TreeView{Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true};
private readonly TextBox details=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly ComboBox books=new ComboBox{DropDownStyle=ComboBoxStyle.DropDownList,Width=300,DisplayMember="Title",ValueMember="BookId"};
private readonly Label pages=new Label{AutoSize=true,Margin=new Padding(8)};
private readonly Button cancel=new Button{Text="Cancel",AutoSize=true};
private readonly Button next=new Button{Text="Next results",AutoSize=true};
private readonly Button previous=new Button{Text="Previous results",AutoSize=true};
public AnalysisWindow(Action analyse,Action stop,Action<int> page)
private readonly Button next=new Button{Text="Next",AutoSize=true},previous=new Button{Text="Previous",AutoSize=true};
private readonly TabControl tabs=new TabControl{Dock=DockStyle.Fill};
private int aiOffset;private Guid session;private string renderKey="";private string bookKey="";private string aiRenderKey="";
private IList<StructureSuggestion> aiItems=new List<StructureSuggestion>();
public AnalysisWindow(Action analyse,Action stop,Action<int> page,Action<StructureSuggestion[]> submit,Action<StructureSuggestion> navigate)
{
Text="PlotDirector — Document structure review";Width=880;Height=500;ShowInTaskbar=false;
rows.Columns.Add("Type",70);rows.Columns.Add("Paragraph",75);rows.Columns.Add("Title / separator",240);rows.Columns.Add("Evidence",320);
var buttons=new FlowLayoutPanel{Dock=DockStyle.Bottom,Height=42,Padding=new Padding(5)};
var repeat=new Button{Text="Analyse again",AutoSize=true};repeat.Click+=(_,__)=>analyse();
cancel.Click+=(_,__)=>stop();next.Click+=(_,__)=>page(1);previous.Click+=(_,__)=>page(-1);
buttons.Controls.AddRange(new Control[]{repeat,cancel,previous,next});
Controls.Add(rows);Controls.Add(progress);Controls.Add(status);Controls.Add(buttons);
Text="PlotDirector — Manuscript review";AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false;
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=6,Padding=new Padding(10)};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));layout.RowStyles.Add(new RowStyle(SizeType.Absolute,8));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
layout.RowStyles.Add(new RowStyle(SizeType.Percent,70));layout.RowStyles.Add(new RowStyle(SizeType.Percent,30));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var actions=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true,Padding=new Padding(0,6,0,6)};
var repeat=new Button{Text="Detect structure",AutoSize=true};repeat.Click+=(_,__)=>analyse();
var ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};ask.Click+=(_,__)=>{
var chosen=local.Nodes.Cast<TreeNode>().Where(n=>n.Checked&&n.Tag is StructureSuggestion).Select(n=>(StructureSuggestion)n.Tag).ToArray();
if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;}
if(SelectedBook<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;}
if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(chosen);
};
cancel.Click+=(_,__)=>stop();actions.Controls.AddRange(new Control[]{repeat,books,ask,cancel});
var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);tabs.TabPages.AddRange(new[]{localTab,aiTab});
var footer=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};footer.Controls.AddRange(new Control[]{previous,next,pages});
previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else{aiOffset=Math.Max(0,aiOffset-40);RenderAi();}};
next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else{aiOffset+=40;RenderAi();}};
tabs.SelectedIndexChanged+=(_,__)=>{if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();};
local.AfterSelect+=(_,e)=>Inspect(e.Node);ai.AfterSelect+=(_,e)=>Inspect(e.Node);
local.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
ai.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
layout.Controls.Add(status,0,0);layout.Controls.Add(progress,0,1);layout.Controls.Add(actions,0,2);layout.Controls.Add(tabs,0,3);layout.Controls.Add(details,0,4);layout.Controls.Add(footer,0,5);Controls.Add(layout);
Resize+=(_,__)=>status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
}
public void Render(AnalysisReview review,string connection,Guid session)
public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0;
private AnalysisPage current;
public void Render(AnalysisReview review,string connection,Guid document,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running)
{
var page=review?.Page;
status.Text="Document session "+session.ToString("N").Substring(0,8)+" · Agent: "+connection+"\n"+(review?.Status??"No active document.");
if(page!=null)status.Text+="\n"+page.WordCount.ToString("N0")+" approximate words · "+page.ParagraphCount.ToString("N0")+" paragraphs · "+page.ChapterCount+" chapter / "+page.SceneCount+" scene suggestions. "+(page.Truncated?"Result limit reached. ":"")+page.Notice;
progress.Value=review?.Progress??0;cancel.Enabled=review?.Running==true;
previous.Enabled=page!=null&&page.Offset>0;next.Enabled=page!=null&&page.Offset+page.Items.Length<page.Total;
rows.BeginUpdate();rows.Items.Clear();
if(page!=null)foreach(var item in page.Items)rows.Items.Add(new ListViewItem(new[]{item.Kind,item.Paragraph.ToString(),item.Title,item.Confidence+": "+item.Reason}));
rows.EndUpdate();
if(session!=document){session=document;renderKey="";aiRenderKey="";books.SelectedIndex=-1;aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();}
current=review?.Page;aiItems=results??new List<StructureSuggestion>();
status.Text="Document "+document.ToString("N").Substring(0,8)+" · "+cloud+"\n"+(string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence.";
progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true;
var key=string.Join("|",available.Select(b=>b.BookId+":"+b.Title));
if(bookKey!=key){var selected=SelectedBook;bookKey=key;books.DataSource=available;books.SelectedIndex=-1;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;}
var newKey=(review?.SnapshotId.ToString()??"")+":"+(current?.Offset??-1);
if(renderKey!=newKey){renderKey=newKey;Fill(local,current?.Items??Array.Empty<StructureSuggestion>());}
if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();
}
private void Inspect(TreeNode node)
{if(node.Tag is StructureSuggestion item)details.Text=item.Title+Environment.NewLine+item.Origin+" · "+item.Confidence+Environment.NewLine+item.Reason+Environment.NewLine+"Word position "+item.Start+". Double-click to navigate without changing text.";}
private void Fill(TreeView tree,IEnumerable<StructureSuggestion> values)
{
tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary<int,TreeNode>();
foreach(var item in values)
{
var chapterStart=item.Kind=="Chapter"?item.Start:item.ChapterStart;
if(!parents.TryGetValue(chapterStart,out var parent))
{
var chapter=item.Kind=="Chapter"?item:new StructureSuggestion{Kind="Chapter",Start=chapterStart,End=item.ChapterEnd,Title=string.IsNullOrEmpty(item.ChapterTitle)?"Before first chapter / unassigned":item.ChapterTitle,Origin="Local structure",Reason="Chapter context for this results page."};
parent=new TreeNode("Chapter · "+chapter.Title){Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent);
}
if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Tag=item,ToolTipText=item.Title});
}
tree.ExpandAll();}finally{tree.EndUpdate();}
}
private void RenderAi(){if(aiOffset>=aiItems.Count)aiOffset=0;var key=aiOffset+":"+aiItems.Count+":"+session+string.Join("|",aiItems.Skip(aiOffset).Take(40).Select(s=>s.Start+":"+s.Title+":"+s.Reason));if(aiRenderKey!=key){aiRenderKey=key;Fill(ai,aiItems.Skip(aiOffset).Take(40));}UpdatePages();}
private void UpdatePages()
{
var offset=tabs.SelectedIndex==0?(current?.Offset??0):aiOffset;var total=tabs.SelectedIndex==0?(current?.Total??0):aiItems.Count;
pages.Text=total==0?"No results":"Showing "+(offset+1)+"–"+Math.Min(total,offset+40)+" of "+total;
previous.Enabled=offset>0;next.Enabled=offset+40<total;
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Windows.Forms;
namespace PlotDirector.WordAddIn
{
public sealed class ConnectWindow:Form
{
public ConnectWindow(WordAdapter adapter)
{
Text="Connect PlotDirector";Width=600;Height=210;AutoScaleMode=AutoScaleMode.Dpi;
var layout=new FlowLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(12),FlowDirection=FlowDirection.TopDown,WrapContents=false};
layout.Controls.Add(new Label{Text="PlotDirector HTTPS site address (no password or API key):",AutoSize=true});
var address=new TextBox{Width=540,Text=adapter.ServerUrl};layout.Controls.Add(address);
var connect=new Button{Text="Sign in in browser",AutoSize=true};connect.Click+=(_,__)=>{adapter.ConnectToServer(address.Text.Trim());Close();};
var signout=new Button{Text="Disconnect / forget sign-in",AutoSize=true};signout.Click+=(_,__)=>{adapter.SignOut();Close();};
layout.Controls.Add(connect);layout.Controls.Add(signout);Controls.Add(layout);
}
}
}

View File

@ -17,16 +17,16 @@ namespace PlotDirector.WordAddIn
{ using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml"))) return reader.ReadToEnd(); }
public void OnLoad(Office.IRibbonUI ribbonUI) { ui = ribbonUI; }
public void Invalidate() { try { ui?.Invalidate(); } catch(COMException) { } }
public string GetStatus(Office.IRibbonControl _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable") + " · Server: unavailable";
public string GetStatus(Office.IRibbonControl _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable")+" · "+(getAdapter()?.CloudState??"Not signed in");
public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true;
public void Connect(Office.IRibbonControl _) { getAdapter()?.Reconnect(); MessageBox.Show("The local agent reconnects in the background. Native server sign-in is not available yet; no browser credentials are reused.","PlotDirector — Nick Beckley"); }
public void Connect(Office.IRibbonControl _) { var adapter=getAdapter();if(adapter!=null)new ConnectWindow(adapter).Show(); }
public void Analyse(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); }
public void Cancel(Office.IRibbonControl _) { getAdapter()?.CancelAnalysis(); }
public void Synchronize(Office.IRibbonControl _) { getAdapter()?.RequestSnapshot(); }
public void Settings(Office.IRibbonControl _)
{
if (getAdapter() == null) return;
var choice = MessageBox.Show("Local analysis and Manual structural refresh are available. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo);
var choice = MessageBox.Show("Local analysis and Manual structural refresh are available. AI scene review requires explicit chapter upload. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo);
if (choice == DialogResult.Yes) getAdapter().PersistNativeIdentity();
}
public void Diagnostics(Office.IRibbonControl _) => MessageBox.Show(getAdapter()?.Diagnostics ?? "Companion did not initialize. Word remains usable. Check the Windows validation prerequisites.","PlotDirector Diagnostics — Nick Beckley");

View File

@ -1,5 +1,6 @@
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="..\DeveloperVersion.props" />
<PropertyGroup>
<ProjectGuid>{42996908-DB24-4A55-AFF1-1017A31D7206}</ProjectGuid>
<ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
@ -7,7 +8,7 @@
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects><OutputType>Library</OutputType><TargetFrameworkVersion>v4.8</TargetFrameworkVersion><LangVersion>latest</LangVersion>
<RootNamespace>PlotDirector.WordAddIn</RootNamespace><AssemblyName>PlotDirector.WordAddIn</AssemblyName>
<OfficeApplication>Word</OfficeApplication><OfficeVersion>15.0</OfficeVersion><VSTO_TrustAssembliesLocation>true</VSTO_TrustAssembliesLocation>
<LoadBehavior>3</LoadBehavior><FriendlyName>PlotDirector Word Companion (Phase 1)</FriendlyName><Description>PlotDirector by Nick Beckley — native prototype</Description>
<LoadBehavior>3</LoadBehavior><FriendlyName>PlotDirector Word Companion</FriendlyName><Description>PlotDirector by Nick Beckley — native prototype</Description>
<ProductName>PlotDirector Word Companion</ProductName><PublisherName>Nick Beckley</PublisherName><SignManifests>false</SignManifests><GenerateManifests>true</GenerateManifests>
<OutputPath>bin\$(Configuration)\</OutputPath><DebugSymbols>true</DebugSymbols>
<VSToolsPath Condition="'$(VSToolsPath)'==''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
@ -22,7 +23,7 @@
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
<Compile Include="WordAdapter.cs" /><Compile Include="AnalysisWindow.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WordAdapter.cs" /><Compile Include="AnalysisWindow.cs" /><Compile Include="ConnectWindow.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
<EmbeddedResource Include="Ribbon.xml" />
</ItemGroup>

View File

@ -1,7 +1,8 @@
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("PlotDirector Word Companion — Phase 1")]
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
[assembly: AssemblyCompany("Nick Beckley")]
[assembly: AssemblyProduct("PlotDirector")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("1.0.0.5")]
[assembly: ComVisible(false)]

View File

@ -2,8 +2,8 @@
<ribbon><tabs><tab id="PlotDirectorTab" label="PlotDirector">
<group id="PlotDirectorConnection" label="Word Companion">
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
<button id="PlotDirectorConnect" label="Connect / Sign In" imageMso="ConnectToExternalData" onAction="Connect" screentip="Reconnect local agent" supertip="Native server sign-in is not yet available. Existing Office.js sign-in remains unchanged." />
<button id="PlotDirectorAnalyse" label="Analyse Document" imageMso="ReviewShowMarkup" onAction="Analyse" getEnabled="CanSynchronize" supertip="Review local chapter and scene suggestions. No import or manuscript changes." />
<button id="PlotDirectorConnect" label="Connect / Sign In" imageMso="ConnectToExternalData" onAction="Connect" screentip="Reconnect local agent" supertip="Approve a short-lived native connection in your browser. No passwords are stored in Word." />
<button id="PlotDirectorAnalyse" label="Analyse" imageMso="ReviewShowMarkup" onAction="Analyse" getEnabled="CanSynchronize" supertip="Detect local structure, then explicitly select chapters for AI scene analysis. No import or manuscript changes." />
<button id="PlotDirectorCancelAnalysis" label="Cancel Analysis" imageMso="CancelRequest" onAction="Cancel" getEnabled="CanSynchronize" />
<button id="PlotDirectorSync" label="Synchronise Now" imageMso="RefreshAll" onAction="Synchronize" getEnabled="CanSynchronize" supertip="Refresh local structural snapshot only. Server/prose sync is not yet available." />
<button id="PlotDirectorSettings" label="Settings" imageMso="PropertySheet" onAction="Settings" />

View File

@ -49,7 +49,9 @@ namespace PlotDirector.WordAddIn
private int documentCollectionGeneration;
private double lastBatchMs;
private AnalysisWindow analysisWindow;
private bool analysisSupported;
private string cloudState="Not signed in",serverUrl="";
private CompanionBook[] cloudBooks=Array.Empty<CompanionBook>();
private bool analysisSupported,cloudSupported;
private readonly Stopwatch reviewClock=Stopwatch.StartNew();
private bool reviewDirty;
private readonly object reviewGate=new object();
@ -57,8 +59,8 @@ namespace PlotDirector.WordAddIn
private string lastResult = "Waiting for local structural snapshot";
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 2\nAgent: " + ConnectionState
+ "\nServer authentication / prose sync: unavailable\nOpen sessions: " + documents.Count
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 3\nAgent: " + ConnectionState
+ "\nServer: "+cloudState+" · Prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2")
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\n" + lastResult;
@ -74,8 +76,8 @@ namespace PlotDirector.WordAddIn
ConnectionState = state;
if(state!="connected")
{
analysisSupported=false;
foreach(var doc in documents.Values){scheduler.Cancel("analyse:"+doc.Session);if(doc.Review.Running||doc.Review.SnapshotId!=Guid.Empty)doc.Review.Stop("Agent disconnected. Reconnect and analyse again.");}
analysisSupported=false;cloudSupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");scheduler.Cancel("analyse:"+doc.Session);if(doc.Review.Running||doc.Review.SnapshotId!=Guid.Empty)doc.Review.Stop("Agent disconnected. Reconnect and analyse again.");}
}
reviewDirty=true;
if (state == "connected")
@ -86,7 +88,9 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);});
if(message.Kind=="cloud-status")
{PostToUi(()=>{cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;});return;}
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);});
// Bound/coalesce progress independently of the Word message pump.
// Never accumulate one BeginInvoke callback per manuscript fragment.
if(message.SessionId!=Guid.Empty&&message.SnapshotId!=Guid.Empty)
@ -204,6 +208,7 @@ namespace PlotDirector.WordAddIn
var documentEnd = DocumentEnd(document); var saved = Com(() => document.Saved);
if (documentEnd != state.End || (state.WasSaved && !saved))
{
StopAi(state,"Document changed. Detect structure again before AI analysis.");state.AiResults.Clear();
state.Review.Stop("Document changed. Analyse again to refresh suggestions.");reviewDirty=true;
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
CancelExtraction(state); link.Register(Descriptor(state));
@ -232,7 +237,7 @@ namespace PlotDirector.WordAddIn
{
if(active==null)return;
if(analysisWindow==null||analysisWindow.IsDisposed)
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage);
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage,StartAi,Navigate);
analysisWindow.Show();analysisWindow.BringToFront();
if(active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
RenderReview();
@ -243,7 +248,7 @@ namespace PlotDirector.WordAddIn
if(ConnectionState!="connected"||!analysisSupported)
{doc.Review.Stop("Connect an updated local agent to analyse this document.");RenderReview();return;}
if(!refresh&&doc.Review.Page!=null){RenderReview();return;}
CancelExtraction(doc);doc.Review.Prepare(doc.Session);reviewDirty=true;
StopAi(doc,"Detecting updated local structure.");doc.AiResults.Clear();CancelExtraction(doc);doc.Review.Prepare(doc.Session);reviewDirty=true;
// Refresh the descriptor on the Word scheduler, never from a background callback.
if(!scheduler.Post("analyse:"+doc.Session,()=>{
if(active!=doc||closing.Contains(doc.Document)){doc.Review.Stop("Document switched or closing. Analyse again when ready.");reviewDirty=true;return;}
@ -254,6 +259,7 @@ namespace PlotDirector.WordAddIn
public void CancelAnalysis()
{
var doc=active;if(doc==null)return;
if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0){StopAi(doc,"AI analysis cancelled. Successful chapter results retained.");RenderReview();return;}
scheduler.Cancel("analyse:"+doc.Session);CancelExtraction(doc);doc.NeedsSnapshot=false;
doc.Review.Stop("Analysis cancelled. Nothing was imported or changed.");RenderReview();
}
@ -267,10 +273,11 @@ namespace PlotDirector.WordAddIn
lastResult="Agent queue busy. Try the results page again.";
}
private void RenderReview()
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty);reviewDirty=false;}
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active?.AiJob!=Guid.Empty&&active!=null);reviewDirty=false;}
public void RequestSnapshot()
{
if (active == null) return;
StopAi(active,"Local structure refreshed.");active.AiResults.Clear();
scheduler.Cancel("analyse:"+active.Session);
active.Review.Stop("Structure refreshed. Analyse again to review updated suggestions.");reviewDirty=true;
lastResult = ConnectionState == "connected" ? "Refreshing local structure…" : "Waiting for the local agent";
@ -280,7 +287,7 @@ namespace PlotDirector.WordAddIn
private void ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
if (doc.Extraction != null || ConnectionState != "connected") return;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse };
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End };
if(analyse)doc.Review.Begin(doc.Session,doc.Revision,doc.Extraction.Snapshot);
if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc)))
{doc.Extraction=null;doc.Review.Stop("Word queue busy. Try analysis again.");}
@ -295,33 +302,33 @@ namespace PlotDirector.WordAddIn
{
if(!extraction.Begun)
{
if(!link.TryPost(new Message{Kind="snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,End=doc.End,RequestAnalysis=extraction.Analyse}))return;
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,RequestAnalysis=extraction.Analyse}))return;
extraction.Begun=true;
}
// At most four <=2048-character fragments and a cooperative ~20ms budget.
// A single COM call cannot be preempted; every call is measured separately.
for(var count=0;count<4 && watch.ElapsedMilliseconds<20;count++)
{
if(extraction.Pending == null && extraction.Position<doc.End)
if(extraction.Pending == null && extraction.Position<extraction.Limit)
extraction.Pending = ReadFragment(doc,extraction);
if(extraction.Pending != null)
{
if(!link.TryPost(extraction.Pending))return; // Keep this value; do not reread Word under backpressure.
extraction.Pending=null;
}
if(extraction.Position>=doc.End)
if(extraction.Position>=extraction.Limit)
{
if(!link.TryPost(new Message{Kind="snapshot-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot}))return;
doc.NeedsSnapshot=false;doc.Extraction=null;
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-submit":"snapshot-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot}))return;
if(!extraction.IsAi)doc.NeedsSnapshot=false;doc.Extraction=null;
// The committed snapshot resolves the current positional selection.
scheduler.Post("selection",CaptureSelection);return;
}
}
}
catch(COMException)
{ doc.Review.Stop("Word was busy. Try analysis again after editing stops.");reviewDirty=true;busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
{ if(extraction.IsAi)StopAi(doc,"Word was busy. AI upload stopped; try again.");doc.Review.Stop("Word was busy. Try analysis again after editing stops.");reviewDirty=true;busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
catch(InvalidOperationException error)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message;doc.Review.Stop(lastResult);reviewDirty=true; }
{ if(extraction.IsAi)StopAi(doc,"Word range unavailable. AI upload stopped.");CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message;doc.Review.Stop(lastResult);reviewDirty=true; }
catch(NullReferenceException)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";doc.Review.Stop(lastResult);reviewDirty=true;throw; }
finally
@ -348,13 +355,13 @@ namespace PlotDirector.WordAddIn
extraction.ParagraphIndex++;
tags=ReadMarkers(paragraphRange);
}
var start=extraction.Position;var end=Math.Min(doc.End,Math.Min(extraction.ParagraphEnd,start+ProtocolVersion.MaxParagraphCharacters));
var start=extraction.Position;var end=Math.Min(extraction.Limit,Math.Min(extraction.ParagraphEnd,start+ProtocolVersion.MaxParagraphCharacters));
if(end<=start)throw new InvalidOperationException("Non-advancing Word range.");
textRange=Com(()=>doc.Document.Range(start,end));
if (textRange == null) throw new InvalidOperationException("Word did not return the requested text range.");
var text=Com(()=>textRange.Text) ?? "";
extraction.Position=end;
return new Message{Kind="snapshot-fragment",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,
return new Message{Kind=extraction.IsAi?"ai-fragment":"snapshot-fragment",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,
Metrics=DrainMetrics(),QueueDepth=link.QueueDepth,Fragment=new ParagraphFragment{ParagraphIndex=extraction.ParagraphIndex,Start=start,End=end,OutlineLevel=extraction.OutlineLevel,
Text=text,MarkerTags=tags,CompletesParagraph=end>=extraction.ParagraphEnd}};
}
@ -412,20 +419,20 @@ namespace PlotDirector.WordAddIn
private void CancelExtraction(LocalDocument doc)
{
scheduler.Cancel("extract:"+doc.Session);
if(doc.Extraction!=null)link.TryPost(new Message{Kind="snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot});
if(doc.Extraction!=null)link.TryPost(new Message{Kind=doc.Extraction.IsAi?"ai-cancel":"snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot});
doc.Extraction=null;
}
private void BeforeSave(Word.Document document,ref bool saveAsUI,ref bool cancel)
{
// Never set Cancel, wait for IPC, read prose or force a document save.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(500));
if(documents.TryGetValue(document,out var state)){scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");reviewDirty=true;}
if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");reviewDirty=true;}
}
private void BeforeClose(Word.Document document,ref bool cancel)
{
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(250));
if(!documents.TryGetValue(document,out var state))return;
scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.Review.Stop("Document closing. Analyse again if close is cancelled.");reviewDirty=true;
StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.Review.Stop("Document closing. Analyse again if close is cancelled.");reviewDirty=true;
documentCollectionGeneration++;
closing.Add(document);
scheduler.Post("retire",ReconcileClosedDocuments);
@ -462,14 +469,89 @@ namespace PlotDirector.WordAddIn
Message[] responses;
lock(reviewGate){responses=reviewReplies.Values.Take(4).ToArray();foreach(var response in responses)reviewReplies.Remove(response.SessionId);}
foreach(var response in responses)
{var doc=documents.Values.FirstOrDefault(d=>d.Session==response.SessionId);if(doc!=null&&doc.Review.Accept(response))reviewDirty=true;}
{var doc=documents.Values.FirstOrDefault(d=>d.Session==response.SessionId);if(doc!=null){if(doc.AiJob==response.SnapshotId&&doc.AiJob!=Guid.Empty)AcceptAi(doc,response);else if(doc.Review.Accept(response))reviewDirty=true;}}
if(reviewDirty&&reviewClock.ElapsedMilliseconds>=250){reviewClock.Restart();RenderReview();}
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
metricClock.Restart();
if(cloudSupported)link.TryPost(new Message{Kind="cloud-status"});
foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty&&doc.Extraction==null)
link.TryPost(new Message{Kind="ai-status",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob,Start=doc.AiOffset});
link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
}
}
public void ConnectToServer(string address)
{if(!cloudSupported){MessageBox.Show("Connect the matching Phase 3 agent first.","PlotDirector");return;}link.TryPost(new Message{Kind="cloud-connect",ServerUrl=address});}
public string ServerUrl=>serverUrl;
public string CloudState=>cloudState;
public void SignOut(){foreach(var doc in documents.Values)StopAi(doc,"Signed out. Successful results retained.");link.TryPost(new Message{Kind="cloud-signout"});}
private void StartAi(StructureSuggestion[] chapters)
{
var doc=active;if(doc==null||doc.Review.Page==null||doc.Review.Running)return;
if(!cloudState.StartsWith("Signed in",StringComparison.Ordinal)){MessageBox.Show("Use Connect / Sign In first.","PlotDirector");return;}
if(doc.AiJob!=Guid.Empty){MessageBox.Show("Cancel the current chapter batch before starting another.","PlotDirector");return;}
doc.AiBook=analysisWindow.SelectedBook;doc.AiCompleted=0;doc.AiFailures.Clear();doc.AiQueue.Clear();
foreach(var chapter in chapters.Where(c=>c.Kind=="Chapter"&&c.Start>=0&&c.End>c.Start).GroupBy(c=>c.Start).Select(g=>g.First()).Take(256))doc.AiQueue.Enqueue(chapter);
doc.AiTotal=doc.AiQueue.Count;if(doc.AiTotal==0){doc.AiStatus="No valid chapter ranges selected. Detect structure again.";reviewDirty=true;return;}NextAi(doc);
}
private void NextAi(LocalDocument doc)
{
doc.AiJob=Guid.Empty;doc.AiOffset=0;doc.AiPartial.Clear();
if(doc.AiQueue.Count==0){doc.AiStatus="AI batch finished: "+doc.AiCompleted+" / "+doc.AiTotal+" chapters processed. Review AI suggestions; failed chapters can be explicitly retried."+(doc.AiFailures.Count>0?" "+doc.AiFailures.Count+" chapter(s) failed; inspect AI suggestions for details.":"");reviewDirty=true;return;}
var chapter=doc.AiQueue.Dequeue();doc.AiChapter=chapter;
if(chapter.End-chapter.Start>120000){AiFailure(doc,"Chapter exceeds the 120,000-character upload limit. Review its boundaries.");doc.AiCompleted++;NextAi(doc);return;}
doc.AiJob=Guid.NewGuid();
doc.AiStatus="Chapter "+(doc.AiCompleted+1)+" of "+doc.AiTotal+": reading "+chapter.Title;
if(!scheduler.Post("ai-read:"+doc.Session,()=>{
if(!documents.ContainsKey(doc.Document)||doc.AiJob==Guid.Empty)return;
if(DocumentEnd(doc.Document)!=doc.End){StopAi(doc,"Document length changed. Detect structure again.");return;}
CancelExtraction(doc);doc.Extraction=new Extraction{Snapshot=doc.AiJob,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc)))StopAi(doc,"Word queue is busy. Try again.");
}))StopAi(doc,"Word queue is busy. Try again.");
reviewDirty=true;
}
private void AcceptAi(LocalDocument doc,Message message)
{
if(message.Revision!=doc.Revision)return;
if(message.Status!="ok"){doc.AiStatus="Chapter failed: "+message.Status;doc.AiCompleted++;AiFailure(doc,message.Status);NextAi(doc);return;}
var result=message.Ai;
if(result==null)return;
if(result.State=="complete"&&result.Offset==doc.AiOffset)
{
foreach(var item in result.Scenes){item.ChapterStart=doc.AiChapter.Start;item.ChapterEnd=doc.AiChapter.End;item.ChapterTitle=doc.AiChapter.Title;doc.AiPartial.Add(item);}
doc.AiOffset=doc.AiPartial.Count;
if(doc.AiOffset>=result.Total)
{
doc.AiResults.RemoveAll(s=>s.ChapterStart==doc.AiChapter.Start);
doc.AiResults.AddRange(doc.AiPartial.Take(Math.Max(0,5000-doc.AiResults.Count)));
doc.AiCompleted++;NextAi(doc);
}
}
else if(result.State=="failed"||result.State=="cancelled")
{AiFailure(doc,result.Message);doc.AiCompleted++;NextAi(doc);}
else doc.AiStatus="Chapter "+(doc.AiCompleted+1)+" / "+doc.AiTotal+": "+(result.State=="reading"?"reading in short batches: "+message.Progress+"%":"AI interpreting scenes…");
reviewDirty=true;
}
private void AiFailure(LocalDocument doc,string reason)
{
doc.AiFailures.Add(doc.AiChapter.Title+": "+reason);
if(doc.AiResults.Count<5000)doc.AiResults.Add(new StructureSuggestion{Kind="Failure",Origin="AI error",Start=doc.AiChapter.Start,End=doc.AiChapter.End,ChapterStart=doc.AiChapter.Start,ChapterEnd=doc.AiChapter.End,ChapterTitle=doc.AiChapter.Title,Title="Analysis failed — "+doc.AiChapter.Title,Reason=reason});
}
private void StopAi(LocalDocument doc,string reason)
{
scheduler.Cancel("ai-read:"+doc.Session);
if(doc.AiJob!=Guid.Empty)link.TryPost(new Message{Kind="ai-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob});
if(doc.Extraction?.IsAi==true)CancelExtraction(doc);
doc.AiJob=Guid.Empty;doc.AiQueue.Clear();doc.AiPartial.Clear();doc.AiStatus=reason;reviewDirty=true;
}
private void Navigate(StructureSuggestion item)
{
var doc=active;if(doc==null||item.Start<0)return;var revision=doc.Revision;
scheduler.Post("navigate:"+doc.Session,()=>{
if(active!=doc||doc.Revision!=revision||DocumentEnd(doc.Document)!=doc.End||item.Start>doc.End)return;
Word.Range range=null;try{range=Com(()=>doc.Document.Range(item.Start,item.Start));Com(()=>{range.Select();return true;});}finally{Release(range);}
});
}
public void Reconnect() { link.Reset(); }
public void PersistNativeIdentity()
{
@ -545,10 +627,15 @@ namespace PlotDirector.WordAddIn
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public readonly AnalysisReview Review=new AnalysisReview();
public readonly Queue<StructureSuggestion> AiQueue=new Queue<StructureSuggestion>();
public readonly List<StructureSuggestion> AiResults=new List<StructureSuggestion>();
public readonly List<string> AiFailures=new List<string>();
public Guid AiJob;public int AiBook,AiOffset,AiCompleted,AiTotal;public string AiStatus;
public StructureSuggestion AiChapter;public readonly List<StructureSuggestion> AiPartial=new List<StructureSuggestion>();
public int? ProjectId,BookId;public long Revision;public int End;public bool WasSaved;public bool NeedsSnapshot=true;public Extraction Extraction;
public LocalDocument(Word.Document document){Document=document;}
}
private sealed class Extraction
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex;public int OutlineLevel;public bool Begun,Analyse;public Message Pending;}
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;}
}
}

View File

@ -0,0 +1,65 @@
Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
function Invoke-Checked([string]$Command,[string[]]$Arguments) {
& $Command @Arguments
if($LASTEXITCODE -ne 0){throw "$Command failed with exit code $LASTEXITCODE. No installation was changed."}
}
function Get-DownloadsFolder {
$entry=Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
$value=$entry.'{374DE290-123F-4565-9164-39C4925E467B}'
if(!$value){throw 'Cannot locate your Downloads known folder.'}
return [Environment]::ExpandEnvironmentVariables($value)
}
function Test-DeveloperPackage([string]$PackagePath) {
$root=(Resolve-Path -LiteralPath $PackagePath).Path
$manifest=Get-Content -Raw -LiteralPath (Join-Path $root 'package.json') | ConvertFrom-Json
if($manifest.publisher -ne 'Nick Beckley' -or $manifest.version -notmatch '^\d+\.\d+\.\d+\.\d+$' -or $manifest.commit -notmatch '^[0-9a-f]{40}$'){throw 'Invalid developer package metadata.'}
foreach($file in $manifest.files){
$path=[IO.Path]::GetFullPath((Join-Path $root $file.path))
if(!$path.StartsWith($root+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase)){throw 'Unsafe package path.'}
if(!(Test-Path -LiteralPath $path -PathType Leaf) -or (Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash -ne $file.sha256){throw "Package hash mismatch: $($file.path)"}
}
foreach($required in @('PlotDirector.WordAddIn.dll','PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.manifest','PlotDirector.Companion.Client.dll','PlotDirector.Companion.Protocol.dll','Agent/PlotDirector.Companion.Agent.exe')){
if(!($manifest.files | Where-Object { $_.path.Replace('\','/') -eq $required })){throw "Package missing $required"}
}
foreach($name in @('PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.manifest')){
[xml]$xml=Get-Content -Raw -LiteralPath (Join-Path $root $name)
if(!$xml.SelectSingleNode("//*[local-name()='Signature']")){throw "Unsigned VSTO manifest: $name"}
$identity=$xml.SelectSingleNode("/*/*[local-name()='assemblyIdentity']")
if(!$identity -or $identity.version -ne $manifest.version){throw 'Manifest/package version mismatch.'}
foreach($dependency in $xml.SelectNodes("//*[local-name()='dependentAssembly' and @dependencyType='install' and @codebase]")){
$relative=[uri]::UnescapeDataString([string]$dependency.codebase)
if([IO.Path]::IsPathRooted($relative) -or $relative -match '^[a-zA-Z]+:'){throw 'Manifest references an external build location; package was not installed.'}
$dependencyPath=[IO.Path]::GetFullPath((Join-Path $root $relative))
if(!$dependencyPath.StartsWith($root+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase) -or !(Test-Path -LiteralPath $dependencyPath -PathType Leaf)){throw "Missing/unsafe manifest dependency: $relative"}
}
}
# Hash inventory is integrity evidence; Office still validates signatures/trust on load.
return $manifest
}
function Get-WordCompanionRegistration {
$base='HKCU:\Software\Microsoft\Office\Word\Addins'
$registrations=@(if(Test-Path $base){Get-ChildItem $base | ForEach-Object {
$item=Get-ItemProperty $_.PSPath
if(($item.PSObject.Properties.Name -contains 'Manifest' -and $item.Manifest -like '*PlotDirector.WordAddIn.vsto*') -or ($item.PSObject.Properties.Name -contains 'FriendlyName' -and $item.FriendlyName -like '*PlotDirector*')){
[pscustomobject]@{Name=$_.PSChildName;Path=(Join-Path $base $_.PSChildName);Properties=$item}
}
}})
if($registrations.Count -gt 1){throw 'Multiple per-user PlotDirector Word registrations exist. Review them before installing; no registration was changed.'}
if($registrations.Count -eq 1){return $registrations[0]}
return $null
}
function Get-InstalledSigningThumbprint {
$registration=Get-WordCompanionRegistration
if(!$registration -or !($registration.Properties.PSObject.Properties.Name -contains 'Manifest')){return $null}
$location=([string]$registration.Properties.Manifest) -replace '\|vstolocal$',''
$uri=$null
if(![uri]::TryCreate($location,[UriKind]::Absolute,[ref]$uri) -or !$uri.IsFile -or !(Test-Path -LiteralPath $uri.LocalPath)){return $null}
[xml]$xml=Get-Content -Raw -LiteralPath $uri.LocalPath
foreach($entry in $xml.SelectNodes("//*[local-name()='X509Certificate']")){
$certificate=[Security.Cryptography.X509Certificates.X509Certificate2]::new([Convert]::FromBase64String($entry.InnerText))
$path="Cert:\CurrentUser\My\$($certificate.Thumbprint)"
if(Test-Path $path){$signer=Get-Item $path;if($signer.HasPrivateKey -and $signer.NotAfter -gt (Get-Date)){return $signer.Thumbprint}}
}
return $null
}

View File

@ -0,0 +1,53 @@
[CmdletBinding(SupportsShouldProcess=$true)]
param([string]$PackagePath,[switch]$Rollback,[switch]$StopAgent)
$ErrorActionPreference='Stop'
if($env:OS -ne 'Windows_NT'){throw 'This per-user developer registration command requires Windows.'}
. (Join-Path $PSScriptRoot 'DeveloperPackage.ps1')
if(Get-Process WINWORD -ErrorAction SilentlyContinue){throw 'Close Microsoft Word normally, including any save prompts, then rerun. Word was not terminated.'}
$root=Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'PlotDirector\WordCompanionDeveloper'
$registration=Get-WordCompanionRegistration
$keyName=if($registration){$registration.Name}else{'PlotDirector.WordAddIn'}
$registry=Join-Path 'HKCU:\Software\Microsoft\Office\Word\Addins' $keyName
$backup=Join-Path $root 'previous-registration.json'
function Stop-DeveloperAgent {
foreach($agent in @(Get-Process 'PlotDirector.Companion.Agent' -ErrorAction SilentlyContinue)){
if(!$StopAgent){throw 'The companion agent is running. Rerun with -StopAgent to explicitly stop this user-session agent. Word must already be closed.'}
if($agent.SessionId -ne (Get-Process -Id $PID).SessionId){throw 'Agent belongs to a different session; it was not stopped.'}
if(!$agent.Path -or !$agent.Path.StartsWith([Environment]::GetFolderPath('UserProfile'),[StringComparison]::OrdinalIgnoreCase)){throw 'Agent path is outside this user profile; stop it explicitly after inspection.'}
if($PSCmdlet.ShouldProcess("Agent PID $($agent.Id)",'Stop for explicit developer installation')){Stop-Process -Id $agent.Id -ErrorAction Stop;$agent.WaitForExit(5000)|Out-Null}
}
}
if($Rollback){
if(!(Test-Path -LiteralPath $backup)){throw 'No previous per-user registration backup exists.'}
$saved=Get-Content -Raw $backup|ConvertFrom-Json
if($saved.PSObject.Properties.Name -contains 'registryKey'){if($saved.registryKey -notmatch '^[a-zA-Z0-9._ -]+$'){throw 'Invalid saved registration key.'};$registry=Join-Path 'HKCU:\Software\Microsoft\Office\Word\Addins' $saved.registryKey}
if($PSCmdlet.ShouldProcess($registry,'Restore previous per-user Word registration')){
Stop-DeveloperAgent
if($saved.existed){New-Item -Path $registry -Force|Out-Null;foreach($property in $saved.values.PSObject.Properties){$type=if($property.Name -eq "LoadBehavior"){"DWord"}else{"String"};New-ItemProperty -Path $registry -Name $property.Name -Value $property.Value -PropertyType $type -Force|Out-Null}}
elseif(Test-Path $registry){Remove-Item -LiteralPath $registry -Recurse}
Write-Output 'Previous registration restored. Signed packages were retained. Open Word to verify.'
}
return
}
if(!$PackagePath){throw 'Provide -PackagePath from Update-WordCompanion.ps1, or use -Rollback.'}
$package=Test-DeveloperPackage $PackagePath
$destination=Join-Path $root "versions\$($package.version)-$($package.commit.Substring(0,8))"
if($PSCmdlet.ShouldProcess($destination,'Stage signed package and register VSTO for this user only')){
Stop-DeveloperAgent
New-Item -ItemType Directory -Path $root -Force|Out-Null
if(!(Test-Path -LiteralPath $destination)){New-Item -ItemType Directory -Path $destination -Force|Out-Null;Copy-Item -Path (Join-Path $PackagePath '*') -Destination $destination -Recurse}
$null=Test-DeveloperPackage $destination
$manifest=([uri](Join-Path $destination 'PlotDirector.WordAddIn.vsto')).AbsoluteUri+'|vstolocal'
$current=Get-ItemProperty -Path $registry -ErrorAction SilentlyContinue
if($current -and $current.Manifest -eq $manifest){Write-Output "Version $($package.version) is already registered. No backup replaced.";return}
$values=@{};if($current){foreach($name in @('Manifest','LoadBehavior','FriendlyName','Description')){if($current.PSObject.Properties.Name -contains $name){$values[$name]=$current.$name}}}
@{registryKey=$keyName;existed=[bool]$current;values=$values} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $backup -Encoding UTF8
try{
New-Item -Path $registry -Force|Out-Null
New-ItemProperty -Path $registry -Name Manifest -PropertyType String -Value $manifest -Force|Out-Null
New-ItemProperty -Path $registry -Name FriendlyName -PropertyType String -Value 'PlotDirector Word Companion' -Force|Out-Null
New-ItemProperty -Path $registry -Name Description -PropertyType String -Value 'PlotDirector by Nick Beckley' -Force|Out-Null
New-ItemProperty -Path $registry -Name LoadBehavior -PropertyType DWord -Value 3 -Force|Out-Null
}catch{throw "Registration failed; backup retained at $backup. Run this script with -Rollback. $($_.Exception.Message)"}
Write-Output "Registered version $($package.version), SHA $($package.commit), for this user. Previous installation files were preserved. Office still validates manifest signatures/trust; no trust store was changed. Open Word and qualify this build."
}

View File

@ -0,0 +1,69 @@
# Phase 3: update, build, install and test
Use only `codex/word-companion-native-phase1-20261104`. Phase 2's working developer installation `1.0.0.4` is preserved by preparation. The new developer build identifier is `1.0.0.5`; it is not Windows-qualified until the steps below pass.
## Update and prepare (no installation)
For the initial bootstrap, in the existing PlotDirector repository, fetch the new script safely:
```powershell
if ((git branch --show-current).Trim() -ne 'codex/word-companion-native-phase1-20261104') { throw 'Wrong branch; do not switch automatically.' }
if (git status --porcelain=v1) { throw 'Preserve local changes before updating.' }
git pull --ff-only origin codex/word-companion-native-phase1-20261104
if ($LASTEXITCODE -eq 0) { & .\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1 }
```
Thereafter the single update/build command is:
```powershell
& .\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1
```
It checks the branch/clean worktree, fetches and fast-forwards, refuses unpublished/divergent local history, finds existing Office-equipped command-line MSBuild, builds managed Release, runs native/server authentication/HTTP tests, builds signed VSTO manifests without Office registration, publishes the .NET 10 win-x64 agent and verifies a complete hash-inventoried package. If the script itself changed on fetch it re-enters the updated script. It never launches Visual Studio or its installer, changes workloads/PATH/IDE settings, closes Word, registers the add-in or alters the current installation.
The package is placed in your Windows Downloads known folder under `PlotDirectorWordCompanion\1.0.0.5-<short SHA>`. A successful rerun verifies/reports the existing package rather than overwriting it. A failed preparation can leave a clearly named `.preparing-<GUID>` directory; it is not installed or reported as ready.
The helper first reuses a remembered certificate thumbprint, then tries the signing certificate in the existing per-user PlotDirector manifest, then a single valid current-user code-signing certificate. If selection is ambiguous, run once with `-CertificateThumbprint <existing certificate thumbprint>`; that nonsecret choice is remembered outside Git. It never creates/trusts a certificate or exports a private key. Missing prerequisites stop with diagnostics rather than invoking Visual Studio Installer/Repair. Office still validates the manifest signatures/trust on load.
## Explicit installation and rollback
Close Word normally, dealing with its save prompts. Use the exact package path printed by the update command:
```powershell
& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -PackagePath '<printed package path>' -StopAgent
```
`-StopAgent` explicitly permits stopping only the named Companion agent in this Windows session/user profile after Word is closed. Visual Studio is not stopped. Without this switch a running agent causes a diagnostic stop. The installer detects/reuses the existing per-user PlotDirector Word add-in registry key instead of introducing a second registration. Multiple existing registrations cause a diagnostic stop.
Packages are copied to versioned `%LOCALAPPDATA%\PlotDirector\WordCompanionDeveloper\versions\` directories and verified before registration. The former registry values/manifest location are backed up; existing Phase 2 files remain untouched. A repeated install of the same package does not replace that rollback backup. No machine-wide registry, trust store, ClickOnce updater or production distribution channel is changed. Use `-WhatIf` to preview the explicit install.
To restore the immediately previous per-user registration, with Word closed:
```powershell
& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -Rollback -StopAgent
```
If a previous registration did not exist, rollback removes the new registration. Packages are retained. Signature/trust failures must be diagnosed; do not disable VSTO security or run IDE Repair. Preparing a package does not prove Windows build/installation acceptance; those operations remain unexecuted on Atlas.
## Sign in and AI use
1. Open Word. Check the native ribbon/Diagnostics and agent connection. Use **Connect / Sign In** and enter the HTTPS PlotDirector site root, for example the Development site provided in the repository guide. Site addresses are author-configured, not embedded in the add-in. The agent remembers only this address; credentials are memory-only.
2. Approve the browser connection using the normal PlotDirector login/2FA. Approve only a request you initiated; compare the request-code suffix shown by the Companion and browser. Grants expire in four hours; password/security-stamp changes and lockout revoke access. **Disconnect / forget sign-in** clears the local grant. Agent restart requires sign-in again.
3. Choose **Analyse** to detect local structure. No manuscript is uploaded. Existing markers are labelled as existing; other structural candidates are labelled local. Expand/collapse chapter nodes and select a result to inspect its bounded title, source, confidence and reasoning. Double-click navigates by Word position, without rewriting text.
4. Select an authorised PlotDirector book in the review window, check one or more chapter nodes on the displayed local-results page, then choose **AI: analyse checked chapters**. An explicit confirmation identifies the book and warns about uploading/costs. No automatic upload occurs on opening, sign-in or local detection.
5. Chapters are read in bounded Word-thread batches and uploaded individually by the agent. Review progress across the selected chapter batch. AI results appear in the separate **AI scene suggestions** tab, grouped by chapter. Errors are inspectable rows. Successful chapters remain available when another fails. Retry is another explicit selection/upload action, not silent replay.
6. Cancel stops queued/reading work and requests server cancellation for the active chapter; already completed results remain. Server timeouts, configuration failures, invalid AI boundaries, authorisation expiry and quota failures appear as errors. If a network failure makes the outcome unknown, retry may incur another provider charge. No manuscript text, markers, imports or canonical scenes are changed.
The server must have this native API deployed, normal account/Story Intelligence entitlement, available configured OpenAI credentials/model/prompt, and migration 230 for the independently shipped marker-security fix. The final Phase 3 report states the actual Development deployment status. Production is not changed.
## Windows qualification checklist
Build/install the new matching add-in and agent using the scripts; record exact Git SHA, version, tools, Office build and bitness. A Linux parse pass does not establish that Office MSBuild generates the expected portable signed manifest paths. If the package verifier refuses a manifest dependency/version, capture that diagnostic and correct the build, not the verifier's safety checks.
Test normal login/2FA, browser refusal, expiry/sign-out, authorised and unauthorised books, unavailable server/provider, quota error and reconnect. Use a small synthetic chapter for the first actual AI request. Confirm narrative boundary suggestions, confidence/reasoning and Word navigation; distinguish them from pre-existing markers. Do not accept a successful local detection as AI evidence.
Then test the author's manuscript and synthetic 190k/250k fixtures: three documents, repeated text, short/long paragraphs, rapid switching, edits, save/close/cancelled close, agent termination/restart and partial chapter failure. Check 100/150/200% DPI, resizing, modeless focus, full-title/evidence inspection, expansion state and both paginated tabs. Record COM/batch/tick timing, typing/scroll/save/close responsiveness, CPU/memory and queue depth versus add-in-disabled trials.
The current observed-revision model does not detect every same-length edit in an already dirty document. Results describe a captured snapshot; re-detect after editing. Chapter upload has a 120,000 Word-position/text-character bound, at most 10,000 paragraphs and 500 returned AI scenes; split/review an oversized chapter rather than uploading a whole novel. Up to 256 explicitly selected chapters can queue in one document; AI results are capped at 5,000 rows/document. No semantic editing, server-to-Word prose writing or Context/Intent migration is implemented.
Commit Windows fixes and qualification evidence to the same shared branch and push. Do not create a Windows feature branch or alter Production.

View File

@ -0,0 +1,21 @@
# Portable tests for package integrity and fail-closed platform guards. No registry/build tools touched.
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'DeveloperPackage.ps1')
$fixture=Join-Path ([IO.Path]::GetTempPath()) ('pd-package-test-'+[guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path (Join-Path $fixture 'Agent') -Force|Out-Null
try{
foreach($name in @('PlotDirector.WordAddIn.dll','PlotDirector.Companion.Client.dll','PlotDirector.Companion.Protocol.dll','Agent/PlotDirector.Companion.Agent.exe')){Set-Content -LiteralPath (Join-Path $fixture $name) -Value 'synthetic fixture, not an executable'}
foreach($name in @('PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.manifest')){Set-Content -LiteralPath (Join-Path $fixture $name) -Value '<assembly><assemblyIdentity version="1.0.0.5"/><Signature/></assembly>'}
$files=@(Get-ChildItem $fixture -Recurse -File|ForEach-Object{@{path=$_.FullName.Substring($fixture.Length+1);sha256=(Get-FileHash $_.FullName -Algorithm SHA256).Hash}})
@{version='1.0.0.5';publisher='Nick Beckley';commit=('a'*40);files=$files}|ConvertTo-Json -Depth 5|Set-Content (Join-Path $fixture 'package.json')
$null=Test-DeveloperPackage $fixture
Set-Content (Join-Path $fixture 'PlotDirector.WordAddIn.dll') 'tampered'
$rejected=$false;try{$null=Test-DeveloperPackage $fixture}catch{$rejected=$true};if(!$rejected){throw 'Tampered package was accepted.'}
if($env:OS -ne 'Windows_NT'){
foreach($script in @('Update-WordCompanion.ps1','Install-WordCompanion.ps1')){
$rejected=$false;try{& (Join-Path $PSScriptRoot $script)}catch{$rejected=$_.Exception.Message -match 'Windows'}
if(!$rejected){throw "Platform guard failed: $script"}
}
}
Write-Output 'PASS portable package validation, tamper refusal and non-Windows fail-closed guards. Fixture signatures are placeholders; no Office trust/Windows installation validation claimed.'
}finally{Remove-Item -LiteralPath $fixture -Recurse -Force}

View File

@ -0,0 +1,58 @@
[CmdletBinding()]
param([string]$CertificateThumbprint)
$ErrorActionPreference='Stop'
if($env:OS -ne 'Windows_NT'){throw 'Run this command on Windows. It never installs the add-in.'}
. (Join-Path $PSScriptRoot 'DeveloperPackage.ps1')
$repo=(Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
Push-Location $repo
try {
$sharedBranch='codex/word-companion-native-phase1-20261104'
$branch=(& git branch --show-current).Trim();if($LASTEXITCODE -ne 0 -or $branch -ne $sharedBranch){throw "Use the existing shared branch $sharedBranch. No branch was switched."}
$dirty=& git status --porcelain=v1;if($LASTEXITCODE -ne 0){throw 'Cannot inspect Git status.'}
if($dirty){throw 'Working tree has local changes. Preserve/commit them before updating; nothing was discarded.'}
$scriptHash=(Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash
Invoke-Checked git @('fetch','origin')
$ahead=(& git rev-list --left-right --count "HEAD...origin/$sharedBranch") -split '\s+'
if($LASTEXITCODE -ne 0 -or [int]$ahead[0] -gt 0){throw 'Local commits are not on the shared remote branch. Push/reconcile them safely before updating.'}
Invoke-Checked git @('merge','--ff-only',"origin/$sharedBranch")
if((Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash -ne $scriptHash){& $PSCommandPath @PSBoundParameters;return}
Invoke-Checked git @('merge-base','--is-ancestor','726a3d5','HEAD')
$commit=(& git rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read commit SHA.'}
$version=([xml](Get-Content -Raw 'PlotDirector.NativeCompanion\DeveloperVersion.props')).Project.PropertyGroup.ApplicationVersion
$output=Join-Path (Get-DownloadsFolder) "PlotDirectorWordCompanion\$version-$($commit.Substring(0,8))"
if(Test-Path -LiteralPath $output){$existing=Test-DeveloperPackage $output;Write-Output "Verified existing package $($existing.version), SHA $($existing.commit): $output";return}
$settings=Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'PlotDirector\CompanionDeveloper\build-settings.json'
if(!$CertificateThumbprint -and (Test-Path -LiteralPath $settings)){$CertificateThumbprint=(Get-Content -Raw $settings|ConvertFrom-Json).certificateThumbprint}
if(!$CertificateThumbprint){$CertificateThumbprint=Get-InstalledSigningThumbprint}
if(!$CertificateThumbprint){
$candidates=@(Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Where-Object {$_.HasPrivateKey -and $_.NotAfter -gt (Get-Date) -and $_.NotBefore -lt (Get-Date)})
if($candidates.Count -ne 1){throw 'Specify -CertificateThumbprint for your existing developer code-signing certificate. It is remembered for future builds; no new certificate or trust-store change is made.'}
$CertificateThumbprint=$candidates[0].Thumbprint
}
$cert=Get-Item "Cert:\CurrentUser\My\$CertificateThumbprint"
if(!$cert.HasPrivateKey -or $cert.NotAfter -le (Get-Date)){throw 'The signing certificate is missing its private key or is expired.'}
$vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
if(!(Test-Path -LiteralPath $vswhere)){throw 'vswhere is missing. Existing Visual Studio Office tools are required. No installer will be launched.'}
$msbuild=& $vswhere -latest -requires Microsoft.VisualStudio.Workload.Office -find 'MSBuild\**\Bin\amd64\MSBuild.exe' | Select-Object -First 1
if(!$msbuild){throw 'Office-equipped MSBuild was not found. No workloads or IDE settings were changed.'}
Invoke-Checked dotnet @('build','PlotLine.slnx','-c','Release','--disable-build-servers','-m:1','/p:UseSharedCompilation=false')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion-http')
# The qualified command-line target bypasses Office registration/F5 while generating signed manifests.
Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Clean;Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version")
$bin=Join-Path $repo 'PlotDirector.NativeCompanion\Vsto\bin\Release'
$staging=$output+'.preparing-'+[guid]::NewGuid().ToString('N')
New-Item -ItemType Directory -Path $staging -Force | Out-Null
Copy-Item -Path (Join-Path $bin '*') -Destination $staging -Recurse
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
if(& git status --porcelain=v1){throw 'Build generated source changes; review them before packaging. No installation was changed.'}
$files=@(Get-ChildItem -LiteralPath $staging -Recurse -File | ForEach-Object { @{path=$_.FullName.Substring($staging.Length+1).Replace('\','/');sha256=(Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash} })
@{version=$version;commit=$commit;publisher='Nick Beckley';certificateThumbprint=$CertificateThumbprint;createdUtc=[DateTime]::UtcNow.ToString('O');files=$files} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $staging 'package.json') -Encoding UTF8
$null=Test-DeveloperPackage $staging
Move-Item -LiteralPath $staging -Destination $output
New-Item -ItemType Directory -Path (Split-Path $settings) -Force | Out-Null
@{certificateThumbprint=$CertificateThumbprint} | ConvertTo-Json | Set-Content -LiteralPath $settings -Encoding UTF8
Write-Output "Build and tests passed. Version: $version; Git SHA: $commit; Package: $output"
Write-Output "Not installed. Close Word, then run: & '$PSScriptRoot\Install-WordCompanion.ps1' -PackagePath '$output' -StopAgent"
} finally {Pop-Location}

View File

@ -0,0 +1,85 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using PlotDirector.Companion.Protocol;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
internal static class NativeCompanionHttpTests
{
private static T Proxy<T>(Func<string,object?[]?,object?> handler)where T:class{var item=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)item).Handler=handler;return item;}
public static async Task Run()
{
void Check(bool condition,string message){if(!condition)throw new Exception(message);}
var user=new AppUser{UserID=7,SecurityStamp=Guid.NewGuid()};var allowed=true;
var users=Proxy<IUserRepository>((name,args)=>Task.FromResult<AppUser?>(user));
var repo=Proxy<IWordCompanionRepository>((name,args)=>name switch{
"ListProjectsAsync"=>Task.FromResult<IReadOnlyList<WordCompanionProjectDto>>([new(){ProjectId=1,Title="Fixture"}]),
"ListBooksAsync"=>Task.FromResult<IReadOnlyList<WordCompanionBookDto>>([new(){BookId=3,Title="Test book"}]),
"GetBookStructureAsync"=>Task.FromResult((int)args![0]! ==3?new WordCompanionBookStructureResponse{BookId=3}:null),
_=>throw new Exception(name)});
var subscriptions=Proxy<ISubscriptionService>((name,args)=>Task.FromResult(new EntitlementDecision{Allowed=allowed}));
var json="""{"schemaVersion":"1.0","chapterSummary":"A fictional chapter.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"A narrative scene","structuralSummary":"The characters encounter a new problem and make a decision to resolve the immediate situation.","confidence":0.8,"reason":"A coherent dramatic unit."}]}""";
var provider=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}}));
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture")));
builder.Services.AddAuthorization();builder.Services.AddControllersWithViews().AddApplicationPart(typeof(NativeCompanionController).Assembly);
builder.Services.AddSingleton<IManuscriptStructureAnalysisService>(new ManuscriptStructureAnalysisService(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),provider,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance));
await using var app=builder.Build();app.UseRouting();app.UseRateLimiter();app.UseAuthentication();app.UseAuthorization();
app.MapGet("/fixture-login",async (Microsoft.AspNetCore.Http.HttpContext context)=>{await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier,"7"),new("PlotLine.SecurityStamp",user.SecurityStamp.ToString())],CookieAuthenticationDefaults.AuthenticationScheme)));return "Fixture login";});
app.MapGet("/fixture-antiforgery",(IAntiforgery xsrf,Microsoft.AspNetCore.Http.HttpContext context)=>xsrf.GetAndStoreTokens(context).RequestToken);
app.MapControllers();await app.StartAsync();
try
{
var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
using var browser=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){BaseAddress=new Uri(address)};
using var agent=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=false}){BaseAddress=new Uri(address)};
Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Native API is not anonymous");
var verifier=new string('d',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
var paired=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge});Check(paired.IsSuccessStatusCode,"Pairing start accepts verifier challenge");
var code=(await paired.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("code").GetString()!;
Check((await browser.GetAsync("/native-companion/authorize?code="+code)).StatusCode==HttpStatusCode.Redirect,"Browser approval requires existing site sign-in");
await browser.GetAsync("/fixture-login");
var approval=await browser.GetAsync("/native-companion/authorize?code="+code);Check(approval.IsSuccessStatusCode&&(await approval.Content.ReadAsStringAsync()).Contains("Approve this Word Companion connection"),"Actual approval view renders before any upload");
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code}}))).StatusCode==HttpStatusCode.BadRequest,"Approval enforces antiforgery");
var antiforgery=await browser.GetStringAsync("/fixture-antiforgery");
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds");
var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing");
var token=(await redeemed.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token);
Check((await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
var request=new AiChapterRequest{BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),RequestId=Guid.NewGuid(),ChapterStart=20,ChapterEnd=40,Paragraphs=[new(){Index=1,Start=20,End=40,Text="A fictional narrative paragraph."}]};
var response=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(response.IsSuccessStatusCode,"Authenticated chapter API calls canonical service");
var result=await response.Content.ReadFromJsonAsync<AiChapterResult>();Check(result?.State=="complete"&&result.Scenes.Single().Start==20&&provider.Prompts.Count==1,"Actual HTTP response maps scene to Word position");
Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).IsSuccessStatusCode&&provider.Prompts.Count==1,"HTTP retry reuses successful provider result");
request.BookId=999;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden&&provider.Prompts.Count==1,"Foreign book rejected without provider charge");request.BookId=3;
allowed=false;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden,"Subscription access enforced on HTTP path");allowed=true;
user.SecurityStamp=Guid.NewGuid();Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Revoked grant rejected through HTTP handler");
}
finally{await app.StopAsync();}
Console.WriteLine("PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI and idempotency (synthetic provider, no database)");
}
}

View File

@ -1,3 +1,13 @@
using System.Reflection;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.DataProtection;
@ -43,6 +53,38 @@ internal static class NativeCompanionTests
var cancelId=Guid.NewGuid();var pending=cache.Run(7,cancelId,"cancel",async c=>{await Task.Delay(Timeout.Infinite,c);return new();});cache.Cancel(8,cancelId);Check(!pending.IsCompleted,"Other user's cancellation isolated");cache.Cancel(7,cancelId);Check((await pending).State=="cancelled","Cancellation isolated to owned chapter");
Check((await cache.Run(7,Guid.NewGuid(),"fail",_=>throw new IOException())).State=="failed","One failed chapter isolated");
Check((await cache.Run(7,id,"same",_=>throw new Exception())).State=="complete","Success survives another chapter's failure");
var limiter=new StoryIntelligenceRequestLimiter(Microsoft.Extensions.Options.Options.Create(new PlotLine.Models.StoryIntelligenceOptions{MaxGlobalConcurrentAiRequests=1}));
var lease=await limiter.EnterAsync(CancellationToken.None);var waiting=limiter.EnterAsync(CancellationToken.None);
Check(!waiting.IsCompleted,"Configured shared provider concurrency is enforced");lease.Dispose();(await waiting).Dispose();
using var stopped=new CancellationTokenSource();stopped.Cancel();try{using var cancelledLease=await limiter.EnterAsync(stopped.Token);throw new Exception("Ignored cancellation");}catch(OperationCanceledException){}
await Security();
}
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class
{var value=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)value).Handler=handler;return value;}
private static async Task Security()
{
void Check(bool value,string name){if(!value)throw new Exception(name);}
var pairing=new DesktopPairing(new EphemeralDataProtectionProvider(),TimeProvider.System);var stamp=Guid.NewGuid();var verifier=new string('c',64);
var code=pairing.Start(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))));pairing.Approve(code,7,stamp);var grant=pairing.Redeem(code,verifier)!;
var user=new AppUser{UserID=7,SecurityStamp=stamp};
var users=Proxy<IUserRepository>((name,args)=>name=="GetByIdAsync"?Task.FromResult<AppUser?>(user):throw new Exception(name));
var services=new ServiceCollection();services.AddLogging();services.AddSingleton(pairing);services.AddSingleton(users);
services.AddAuthentication(DesktopPairing.Scheme).AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
await using var provider=services.BuildServiceProvider();
async Task<AuthenticateResult> Auth(string? bearer)
{await using var scope=provider.CreateAsyncScope();var context=new DefaultHttpContext{RequestServices=scope.ServiceProvider};if(bearer!=null)context.Request.Headers.Authorization="Bearer "+bearer;return await context.AuthenticateAsync(DesktopPairing.Scheme);}
Check((await Auth(null)).None,"Native API requires an explicit bearer grant");
Check((await Auth(grant)).Principal?.FindFirstValue(ClaimTypes.NameIdentifier)=="7","Native handler authenticates protected grant");
user.SecurityStamp=Guid.NewGuid();Check(!(await Auth(grant)).Succeeded,"Password/security-stamp change revokes desktop access");user.SecurityStamp=stamp;user.IsLocked=true;Check(!(await Auth(grant)).Succeeded,"Locked account cannot use native API");
var access=false;var allowed=true;var accesses=0;
var repo=Proxy<IWordCompanionRepository>((name,args)=>{
if(name!="GetBookStructureAsync")throw new Exception(name);accesses++;Check((int)args![1]! == 7,"Book access uses authenticated subject");return Task.FromResult(access?new WordCompanionBookStructureResponse{BookId=(int)args[0]!}:null);
});
var subscriptions=Proxy<ISubscriptionService>((name,args)=>Task.FromResult(new EntitlementDecision{Allowed=allowed}));
var scopeFactory=provider.GetRequiredService<IServiceScopeFactory>();
var api=new NativeCompanionController(repo,new NativeAnalysisCache(TimeProvider.System),scopeFactory,new ConfigurationBuilder().Build(),subscriptions){ControllerContext=new ControllerContext{HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],DesktopPairing.Scheme))}}};
Check(await api.Analyse(new(){BookId=999}) is ForbidResult&&accesses==1,"Foreign book denied before constructing or charging an AI request");
allowed=false;Check(await api.Analyse(new(){BookId=999}) is ForbidResult&&accesses==1,"Story Intelligence entitlement enforced before AI work");
}
private sealed class Clock:TimeProvider{public DateTimeOffset Now=DateTimeOffset.UtcNow;public override DateTimeOffset GetUtcNow()=>Now;}
}

View File

@ -122,6 +122,7 @@ if (args.Contains("--plot-lines"))
return;
}
if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;}
if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console.WriteLine("PASS native desktop pairing, canonical chapter AI/mapping, idempotency and cancellation");return;}
var tests = new (string Name, Action Test)[]

View File

@ -36,7 +36,7 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor
await using var scope=scopes.CreateAsyncScope();
var result=await scope.ServiceProvider.GetRequiredService<IManuscriptStructureAnalysisService>().AnalyseChapterAsync(mapped,cancellation);
return NativeChapterMapping.Map(request,result);
});
},request.BookId);
Response.Headers.CacheControl="no-store";
return Ok(await task.WaitAsync(HttpContext.RequestAborted));
}

View File

@ -97,6 +97,7 @@ public class Program
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.DesktopPairing>();
builder.Services.AddAuthentication().AddScheme<Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions, PlotLine.Services.NativeCompanion.DesktopAuthentication>(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { });
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativeAnalysisCache>();
builder.Services.AddSingleton<StoryIntelligenceRequestLimiter>();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>

View File

@ -2,21 +2,21 @@ using PlotDirector.Companion.Protocol;
namespace PlotLine.Services.NativeCompanion;
// Bounded process-local idempotency. Restart loses cache: agent never auto-replays after restart.
public sealed class NativeAnalysisCache(TimeProvider clock)
public sealed class NativeAnalysisCache(TimeProvider clock,Microsoft.Extensions.Options.IOptions<PlotLine.Models.StoryIntelligenceOptions>? options=null)
{
private readonly object gate=new();
private readonly Dictionary<(int,Guid),Entry> jobs=[];
private readonly SemaphoreSlim workers=new(2);
public Task<AiChapterResult> Run(int user,Guid id,string hash,Func<CancellationToken,Task<AiChapterResult>> work)
private readonly SemaphoreSlim workers=new(Math.Max(1,Math.Min(2,options?.Value.MaxGlobalConcurrentAiRequests??2)));
public Task<AiChapterResult> Run(int user,Guid id,string hash,Func<CancellationToken,Task<AiChapterResult>> work,int book=0)
{
lock(gate)
{
foreach(var key in jobs.Where(j=>j.Value.Task.IsCompleted&&j.Value.Expires<clock.GetUtcNow()).Select(j=>j.Key).ToArray()){jobs[key].Stop.Dispose();jobs.Remove(key);}
if(jobs.TryGetValue((user,id),out var prior))
{if(prior.Hash!=hash)throw new ArgumentException("Request ID content mismatch.");return prior.Task;}
if(jobs.Count>=256||jobs.Count(j=>j.Key.Item1==user&&!j.Value.Task.IsCompleted)>=1)throw new InvalidOperationException("Analysis busy. Wait for the current chapter.");
if(jobs.Count>=256||jobs.Count(j=>j.Key.Item1==user&&!j.Value.Task.IsCompleted)>=1|| (book>0&&jobs.Values.Count(j=>j.Book==book&&!j.Task.IsCompleted)>=Math.Max(1,options?.Value.MaxConcurrentAiRequestsPerBook??2)))throw new InvalidOperationException("Analysis busy. Wait for the current chapter.");
var stop=new CancellationTokenSource(TimeSpan.FromMinutes(5));
var entry=new Entry(hash,clock.GetUtcNow().AddMinutes(30),stop);
var entry=new Entry(hash,clock.GetUtcNow().AddMinutes(30),stop,book);
jobs.Add((user,id),entry);entry.Task=Execute();return entry.Task;
async Task<AiChapterResult> Execute()
{
@ -27,6 +27,6 @@ public sealed class NativeAnalysisCache(TimeProvider clock)
}
}
public void Cancel(int user,Guid id){lock(gate){if(jobs.TryGetValue((user,id),out var job))job.Stop.Cancel();}}
private sealed class Entry(string hash,DateTimeOffset expires,CancellationTokenSource stop)
{public string Hash=hash;public DateTimeOffset Expires=expires;public CancellationTokenSource Stop=stop;public Task<AiChapterResult> Task=System.Threading.Tasks.Task.FromResult(new AiChapterResult());}
private sealed class Entry(string hash,DateTimeOffset expires,CancellationTokenSource stop,int book)
{public int Book=book;public string Hash=hash;public DateTimeOffset Expires=expires;public CancellationTokenSource Stop=stop;public Task<AiChapterResult> Task=System.Threading.Tasks.Task.FromResult(new AiChapterResult());}
}

View File

@ -146,7 +146,8 @@ public sealed class StoryPromptVersionService : IStoryPromptVersionService
public sealed class StoryIntelligenceClient(
HttpClient httpClient,
IOptions<StoryIntelligenceOptions> options,
ILogger<StoryIntelligenceClient> logger) : IStoryIntelligenceClient
ILogger<StoryIntelligenceClient> logger,
StoryIntelligenceRequestLimiter? limiter = null) : IStoryIntelligenceClient
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private readonly StoryIntelligenceOptions settings = options.Value;
@ -192,6 +193,7 @@ public sealed class StoryIntelligenceClient(
throw new InvalidOperationException("Completed prompt is empty.");
}
using var requestLease=limiter==null?null:await limiter.EnterAsync(cancellationToken);
var maxOutputTokens = maxOutputTokensOverride.GetValueOrDefault(settings.MaxOutputTokens);
if (maxOutputTokens <= 0)
{

View File

@ -0,0 +1,12 @@
using Microsoft.Extensions.Options;
using PlotLine.Models;
namespace PlotLine.Services;
// Shared by the existing typed AI client, including web onboarding and native previews.
public sealed class StoryIntelligenceRequestLimiter(IOptions<StoryIntelligenceOptions> options)
{
private readonly SemaphoreSlim slots=new(Math.Max(1,options.Value.MaxGlobalConcurrentAiRequests));
public async Task<IDisposable> EnterAsync(CancellationToken cancellation)
{await slots.WaitAsync(cancellation);return new Lease(slots);}
private sealed class Lease(SemaphoreSlim semaphore):IDisposable{private int disposed;public void Dispose(){if(Interlocked.Exchange(ref disposed,1)==0)semaphore.Release();}}
}

View File

@ -1,8 +1,10 @@
@model string
@{ ViewData["Title"] = "Connect Word Companion"; }
@{ Layout = null; }
<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Connect Word Companion</title><link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css"/></head><body>
<div class="container py-4" style="max-width:45rem">
<h1>Connect Word Companion</h1>
<p>Approve only if you just chose Connect in your own Word Companion. This grants access to your available books and allows chapter text you explicitly submit to use PlotDirector's configured AI provider.</p>
<p>Request code: <strong>@Model.Substring(Math.Max(0, Model.Length - 6))</strong>. Compare this with the Companion request before approving.</p>
<p>No manuscript is uploaded by signing in. The connection expires after four hours.</p>
<form method="post" action="/native-companion/authorize">
@Html.AntiForgeryToken()
@ -10,3 +12,5 @@
<button type="submit" class="btn btn-primary">Approve this Word Companion connection</button>
</form>
</div>
</body></html>