diff --git a/Docs/WordCompanion/2026-11-07-paragraph-sync-foundation.md b/Docs/WordCompanion/2026-11-07-paragraph-sync-foundation.md new file mode 100644 index 00000000..f485ad2b --- /dev/null +++ b/Docs/WordCompanion/2026-11-07-paragraph-sync-foundation.md @@ -0,0 +1,118 @@ +# Paragraph manuscript synchronisation foundation — 7 November 2026 + +## Delivery and operational boundaries + +This is a staged, opt-in foundation, **not an enabled Development or production rollout**. `Features:ParagraphManuscripts` defaults to false. Native source version is **1.0.0.18**; the separately qualified unified installer remains pinned to **1.0.0.17**. No installer, signing, installation or Word automation was performed on Atlas. + +The independently committed import recovery fix `2c0e02c7c9f68a9d1a4b6f9139c8798f80b83929` was published to Development from an archive of that exact commit, after the author explicitly confirmed the failed import was stopped and a restart was safe. Deployment release: `/srv/apps/plotdirector-dev/releases/2c0e02c-20261107T195222Z`; previous deployment preserved at `/srv/apps/plotdirector-dev/current-before-2c0e02c-20261107T195222Z`. Public health request returned HTTP 200 and `plotdirector-dev` was active. That deployment contained **none** of this unfinished-at-the-time foundation. The author was told they could resume their existing import. **Do not restart Development again on the strength of the earlier approval.** No Production changes. + +Migration `PlotLine/Sql/240_ParagraphManuscripts.sql` was applied and exercised only in guarded synthetic database `PlotDirector_Phase2_20261103_2305`, after a unique COPY_ONLY/CHECKSUM backup and RESTORE VERIFYONLY. No Development schema migration or feature activation was performed. SQL fixtures roll back their own newly created accounts, books, prose and events. + +## Architecture and consent + +```mermaid +flowchart LR + Word[Word STA / bounded reader] -->|Value fragments; optional native paragraph hint| Agent[Existing per-user agent] + Agent -->|Existing authenticated capture endpoint; full snapshot or delta| Server[Existing native capture service] + Wizard[Existing manuscript import wizard] -->|Explicit import / opt-in| Server + Workspace[Book: manuscript structure and evidence] -->|Owner-approved modes and edits; revision check| Domain[Paragraph manuscript service] + Server --> Domain + Domain -->|Dapper stored procedures| SQL[(Canonical scenes / prose / events + paragraph state)] + SQL -->|Exact session and revision position index| Presence[Existing native presence / Context / Intent] + Server -->|Canonical occurrence IDs and acknowledgement| Agent +``` + +There is no new agent process, local server, identity system or SignalR hub. Existing installation approval, token renewal, account scoping, named-pipe backpressure and document sessions remain in use. Old agents and Office.js workflows keep their existing capture method. New `paragraph-snapshots-v1` capability and `StartParagraphManuscriptScan` hub method are additive. + +With the feature enabled on an isolated server, the import wizard offers an **unchecked** paragraph-tracking consent option. Checking it alone transfers nothing. Clicking Import requests the existing native bounded reader and retains the complete raw paragraph stream in the accepted capture. The established chapter/character/import pipeline still owns import; no new scene-by-scene approval requirement is introduced. On successful opt-in build, paragraph tracking starts in On Save mode as described by the consent text. + +An owner can instead adopt a completed native capture from Book → Manuscript structure and evidence. Adoption is Manual by default, uses only that preview's canonical scene mappings, refuses an incomplete/non-reversible map, and never incorporates unrelated scene sources. Sections excluded in the accepted import remain captured but outside canonical story prose during later sync. + +Modes: + +- **Manual:** explicit Synchronise from Word only. +- **On Save:** explicit continuing authorisation for a saved/reconnected associated document. More than one eligible document, another manuscript GUID, incomplete import, active Story Intelligence job or lost owner authority prevents automatic transfer. +- **Off:** no automatic transfer; an explicit manual snapshot is still an author action. + +No idle/keystroke-triggered prose upload or automatic AI analysis was added. A successful save is observed through Word's saved state; neither the before-save handler nor IPC waits for the server. An unchanged, already-saved document avoids another extraction. A changed save or reconnect still requires a bounded document read; this is not an implementation of Word incremental change tracking. + +## Paragraph identity and reconciliation + +Shared value logic is in `Protocol/Manuscript/ParagraphIdentity.cs` and `ParagraphDelta.cs`; the agent and server use the same implementation. + +Each occurrence has an opaque GUID, current ordinal and Word positions, a SHA-256 content fingerprint, native hint, adjacent occurrence IDs, previous text, reconciliation reason and movement/change state. A text hash is **never** an identity. Native hints are only candidates. Unique native matches preserve ordinary edited/moved occurrences; unique contextual pairs and recognised neighbours provide fallback. Identical dialogue and copies retain independent identities. An ambiguous occurrence gets a new GUID; its old evidence remains unresolved rather than being assigned by a text-only guess. + +VSTO reads `w14:paraId` from a first-character `Range.WordOpenXML` range once per paragraph, on Word's thread and within the existing measured extraction scheduler. The parser reads only the main document part, bounds XML to 256 Ki characters, and prohibits DTDs/external entities. Unavailable hints fall back to context. It does not read full-document XML or insert per-paragraph controls/bookmarks. An unpersisted manuscript identity can be written as one existing PlotDirector-owned document property only on explicitly requested paragraph capture; Word is marked unsaved, never forcibly saved. Read-only documents require a writable copy. + +Microsoft documents `paraId` as unique within a document part, **not** as a permanent authoring identity. Regeneration, repeated ambiguous passages and simultaneous move/rewrite may be unresolvable. That uncertainty is intentional. Primary references: + +- [Word Range.WordOpenXML](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.range.wordopenxml?view=word-pia) +- [Microsoft DOCX paragraph identifiers](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-docx/a0e7d2e2-2246-44c6-96e8-1cf009823615) + +The agent keeps value snapshots in memory only (up to eight sessions and 32 Mi characters across entries), scoped to authentication context and manuscript. It sends ordered occurrence IDs plus changed paragraph text when the server's base hash matches. Repeated source text can reference another prior paragraph's **text**, never its identity or events. A restart/base mismatch sends one full authorised snapshot and adopts the server's canonical occurrence IDs from its acknowledgement. No plaintext manuscript queue is written to disk. Offline changes stay in Word and are reconciled after reconnection/save or an explicit request. + +Bounds include 100,000 paragraphs, 16 Mi characters per snapshot, existing bounded fragment queues, a 100 MiB HTTP request ceiling, 128 MiB SQL JSON ceiling, and bounded undo/evidence budgets. Delta expansion validates unique IDs, base revision, source-text references, ordering, spans and total length. Request hashes reject altered retries; revision CAS prevents a stale snapshot overwriting newer accepted structure. + +## Scene groupings and evidence + +`ParagraphManuscriptEngine` maintains opaque scene GUIDs mapped to canonical SceneIDs. Headings/front matter/excluded sections remain stored; every included story paragraph belongs to one current scene. Existing H1/marker-based chapter sections and accepted import exclusions are retained. Unknown headings/ambiguous boundaries are flagged; their raw snapshots are retained while canonical scene prose is kept at its last accepted projection. Authors can adjust or explicitly confirm a proposed grouping, separately from confirming factual evidence. The foundation does not automatically create new canonical chapters from later Word edits. Losing an excluded section boundary refuses the update instead of guessing which prose was approved for the book. + +A tracked chapter containing an unmapped author scene is refused rather than silently renumbering that scene. Newer archive/chapter decisions made through existing tools likewise cause a conflict instead of being undone by a snapshot. + +The book workspace provides paginated paragraphs, scene split, adjacent boundary movement, same-chapter adjacent merge and bounded undo. Moves/reordering of actual prose happen **in Word**, then reconcile; the server never reorders Word prose. Reliable complete scene movement preserves scene identity. Merge retains the retired canonical scene and its metadata; it does not automatically combine divergent planning, chronology or participant records into the surviving scene. Undo is invalidated by a changed manuscript snapshot or newer conflicting event positions. + +Optional primary/supporting evidence attaches to existing Knowledge/Relationship events using paragraph IDs and optional character offsets/ranges. Exact original, author-confirmed and current passages are retained. States are Verified, Needs review and Missing. Changed or deleted text never deletes its event. The workspace provides before/after text, positions, confirm, relink, detach while retaining the event, and access to the existing scene event editor for editing/removal. + +SQL derives an event's canonical scene only from verified primary evidence. Unanchored events retain normal scene-based behaviour. Evidence display state is excluded from legacy event JSON so old backup/checkpoint hashes do not change. Knowledge facts/regression checks and relationship state/continuity projections exclude unverified primary evidence while keeping it visible for review. The existing deterministic relationship checker runs inside the save transaction; no whole-book AI is scheduled. Statistics refresh is subsequent derived work and cannot turn a committed snapshot into a falsely reported rollback. + +An indexed current-position projection requires the exact manuscript GUID, live session and Word revision. A stale revision returns no scene and does not fall back to old imported offsets. Existing native presence carries the resolved scene to web workspaces. Paragraph-capable agents include cursor movement in their presence change key, even inside an older local marker range. + +## AI range recovery and confidence compatibility + +The 97-versus-99 fixture represents 97 numbered structural inputs, 99 raw source paragraphs (including heading/blank), and a final structural paragraph at Word index 3,551. The prompt contained 97 explicit numbered paragraphs, not 99 numbered inputs or global Word coordinates. The returned 1–99 range was a nonconforming AI proposal. There is no conversion that should turn 97 into 99. + +Recovery retains the affected chapter as one `StructuralFallback` scene, with exact accepted source sequence, rejected proposal JSON, diagnostic and a refinement warning; it invents neither confidence nor narrative summary. It does not clamp the invalid end. Valid chapter checkpoints are reused; identical fallback checkpoints also avoid repeating already-completed provider work. A corrupt source map is still refused rather than hidden. Safely discarding an empty trailing proposal after all real paragraphs are covered remains compatible with older imports. + +New opted-in chapter requests use prompt V3, schema 2.0 and strict provider **integer confidence 0–100** contracts. The response schema's paragraph maxima are generated from the actual submitted count. Integer JSON remains in persisted parsed output; the existing domain boundary converts once to normalized decimals for legacy consumers. Schema 1.0 decimal output remains readable. The new request version field is omitted when zero, preserving in-flight request/checkpoint hashes; old captures do not silently switch prompts/contracts. Other pre-existing AI stages are not globally re-versioned by this change. Actual provider execution of the new strict contract remains unverified here. + +## Schema and recovery limitations + +Migration 240 adds `BookParagraphManuscripts`, `BookParagraphPositions`, `ManuscriptEvidenceIndex`, the scoped `ParagraphManuscript` procedure and evidence projection procedure, and updates deterministic continuity/recovery guards. It does not migrate existing captures, rewrite planning, replay jobs, create credentials or delete author events. Writes require the existing project-owner role; readers require active project access. Book deletion cascades new state. + +**Important staged-release limitation:** downloaded backups/saved-point replacement do not yet have a qualified portable/remapped paragraph-evidence contract. Legacy recovery is explicitly refused for tracked projects, before incomplete export or replacement, rather than silently losing new author decisions. Do not enable this feature on a real author book until that extension is implemented and round-trip tested. Test using isolated books. The default-off gate and this refusal are deliberate; the feature is not ready for general author rollout. + +Other remaining qualification: actual Word native hint behaviour on paste/split/merge/reopen, Word UI responsiveness and first-character XML costs, the new browser workspace's interactive layout/actions, real desktop-to-server execution, live Context/Intent after paragraph edits, and strict AI provider execution. Atlas tests do not establish these. + +## Reproduction and verification + +Run serially from the repository root: + +```sh +dotnet build PlotLine.slnx +dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj +dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --paragraph-manuscripts +dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --native-import-corrections +dotnet run --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj +``` + +Browser regressions: first render the fixture using `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --paragraph-view`, then from `PlotLine.Tests/Browser` run `node native-import-connection.cjs` and `node paragraph-manuscript.cjs`. It exercises disconnected/expired/wrong-book states, explicit-only transfer, legacy method compatibility and the new unchecked/explicit paragraph consent path, using isolated browser fixtures, not an author's live import. + +Database fixture: `PlotLine.Tests/Sql/ParagraphManuscripts.sql`, only on its exact named synthetic database with the `PlotDirector.Phase2.SyntheticOnly=true` guard, after applying migration 240 there. Assertions compare exact prose, canonical event locations, identity/revision state, duplicate acknowledgements, stale position refusal, new scene allocation, cross-account refusal and explicit backup omission protection. Fixture changes are rolled back. + +Acceptance evidence covers initial occurrence IDs, serialized reopen/reconnect simulation, movement with attached event, copies, identical dialogue, rewritten/missing evidence, scene split/boundary/merge/undo, continuity exclusion and legacy/in-flight compatibility. The 250,000+ word fixture measures shared in-memory reconciliation, not COM. Final command results and commit references are recorded in the Windows handover. + +### Final Atlas verification + +- Solution build: succeeded, zero warnings/errors; managed Windows target compiled, VSTO host not built/run. +- Application executable harness: **455 reported PASS checks**, successful exit. +- Focused paragraph suite: **38 PASS checks**, including completed-build adoption/exclusions, save/reconnect, cancellation, permission/refinement and preference-only Off. +- Focused native import recovery/integer contract: **19 PASS checks**. +- Native executable harness: **270 checks**, successful exit; Linux pipe execution is not Windows ACL/COM evidence. +- Actual compiled Razor workspace rendered through an isolated HTTP fixture; scoped routes, antiforgery, encoded prose, typed evidence selection and 100-paragraph pagination checked. +- Playwright: `native-import-connection.cjs` and `paragraph-manuscript.cjs` passed, using isolated fixtures/compiled Razor output. This does not claim full shared-shell theme/layout or interactive Windows qualification. +- Synthetic SQL migration and six assertion groups passed: exact prose/revision/idempotency/missing evidence; canonical split and verified event move; uncertain grouping retains raw source without canonical overwrite; unmapped author scene refusal; backup omission protection; cross-account denial/rollback. SQL emitted only expected null-elimination aggregate warnings for an empty scene. +- 250,000+ word in-memory fixture: **372 ms** in the final focused run, not a Word responsiveness measurement. +- Synthetic backup: `/var/opt/mssql/backup/paragraph-foundation-20261107-201718.bak`, COPY_ONLY/CHECKSUM, RESTORE VERIFYONLY valid. No Development migration. +- Recovery-only deployed DLL SHA-256 matches the archived `2c0e02c` publication: `520762918cdd7cb5dc33f23ed17c6c55aba99d1bbe34679f302e68f5ec86ddf3`. + +For tracked test books, use the per-book Off preference to stop transfers while retaining the paragraph read/review infrastructure. Do not treat hiding the feature with a server-wide rollback as a qualified migration/recovery procedure. The portable backup extension remains a general-rollout blocker. diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index dca8fd9e..f5c181d6 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -138,7 +138,7 @@ public sealed partial class CloudGateway : IDisposable if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(context);throw new InvalidOperationException("Connection needs renewal. Retry after Companion reconnects automatically.");} if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");} await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size; - while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; + while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>(path=="api/native-companion/manuscript-capture"?4:1)*1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; var result=await JsonSerializer.DeserializeAsync(buffer,Json,stop.Token); lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.State="Connected";health.VerifiedUtc=Now.UtcDateTime;if(path.EndsWith("/presence",StringComparison.Ordinal))health.Explanation="Document heartbeat verified by PlotDirector.";} return result??throw new InvalidDataException(); diff --git a/PlotDirector.NativeCompanion/Agent/ParagraphSnapshotCache.cs b/PlotDirector.NativeCompanion/Agent/ParagraphSnapshotCache.cs new file mode 100644 index 00000000..9a092397 --- /dev/null +++ b/PlotDirector.NativeCompanion/Agent/ParagraphSnapshotCache.cs @@ -0,0 +1,34 @@ +using PlotDirector.Companion.Protocol; +using PlotDirector.Companion.Protocol.Manuscript; +namespace PlotDirector.Companion.Agent; +// Value snapshots only. No plaintext disk queue and no identities shared across account contexts. +public sealed class ParagraphSnapshotCache +{ + private sealed record Entry(Guid Authentication,Guid Manuscript,long Revision,string Hash,ParagraphOccurrence[] Rows); + private readonly Dictionary entries=[]; + private readonly object gate=new(); + public ParagraphOccurrence[] Prepare(Guid session,Guid authentication,ManuscriptCapture capture,long revision,string baseHash) + { + var rows=ParagraphReconciliation.Assemble(capture.Paragraphs,capture.End); + lock(gate){ + entries.TryGetValue(session,out var entry); + if(entry!=null&&entry.Authentication==authentication&&entry.Manuscript==capture.ManuscriptId&&entry.Hash==baseHash){ + rows=ParagraphReconciliation.Compare(entry.Rows,rows).Current; + capture.Delta=ParagraphDeltaCodec.Create(revision,entry.Rows,rows);capture.Paragraphs=[]; + }else rows=ParagraphReconciliation.Compare([],rows).Current; + capture.ParagraphIds=rows.Select(p=>p.Id).ToArray();return rows; + } + } + public void Accept(Guid session,Guid authentication,Guid manuscript,ParagraphOccurrence[] rows,NativePresence reply) + { + var ids=reply.CanonicalParagraphIds;if(ids==null||ids.Length!=rows.Length||ids.Any(id=>id==Guid.Empty)||ids.Distinct().Count()!=ids.Length)throw new InvalidDataException("Paragraph acknowledgement is incomplete."); + lock(gate){ + foreach(var key in entries.Where(p=>p.Value.Authentication!=authentication).Select(p=>p.Key).ToArray())entries.Remove(key); + for(int i=0;i=8||entries.Values.Sum(e=>e.Rows.Sum(p=>(long)p.Text.Length))+rows.Sum(p=>(long)p.Text.Length)>32*1024*1024){if(entries.Count==0)return;entries.Remove(entries.Keys.First());} + entries[session]=new(authentication,manuscript,reply.ParagraphRevision,ParagraphReconciliation.SnapshotFingerprint(rows),rows); + } + } + public void Remove(Guid session){lock(gate)entries.Remove(session);} +} diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index a7d18133..4a35e8db 100644 --- a/PlotDirector.NativeCompanion/Agent/PipeHost.cs +++ b/PlotDirector.NativeCompanion/Agent/PipeHost.cs @@ -56,7 +56,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action paragraphInstances=[]; private readonly object gate=new();private readonly Dictionary documents=[]; private readonly Dictionary> commands=[];private readonly Dictionary leases=[];private readonly HashSet captureInstances=[];private readonly HashSet maintenanceInstances=[];private readonly Dictionary maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[]; public event Action? OpenRequested; public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}} public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}} - public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false){lock(gate){Disconnected(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} + public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false){lock(gate){Disconnected(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default) { lock(gate) @@ -58,7 +61,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C } } public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}} - private void Remove(Guid session){foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}} + private void Remove(Guid session){paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}} private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;} public bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);} public void Maintain(Guid session,string kind) @@ -116,9 +119,10 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C public async Task Heartbeat(CancellationToken cancellation) { while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray(); - foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){if(doc.ChapterId!=reply.ChapterId)doc.ChapterTitle="";if(doc.SceneId!=reply.SceneId)doc.SceneTitle="";doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;} if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}} - if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if(reply.Navigation.Kind=="wizard-capture"&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision};doc.CaptureFragments.Clear();doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}else if(reply.Navigation.Kind=="wizard-capture")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}} + if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision,ParagraphTracking=reply.Navigation.ParagraphTracking};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear();doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}} if(available.Length==0&&cloud.Status().Health?.Authentication=="verified"&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){WordRunning=leases.Count>0,BookId=0,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},cloud.Status().AuthenticationContext);}catch(Exception e)when(NetworkFailure(e)) {}} else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);} } @@ -131,9 +135,9 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C if(request.Kind=="snapshot-begin"){doc.CaptureFragments.Clear();capture.End=request.End;} if(request.Kind=="snapshot-fragment"&&request.Fragment!=null){if(doc.CaptureFragments.Count>=200000){Cancel(doc);return;}doc.CaptureFragments.Add(request.Fragment);} if(request.Kind=="snapshot-end"){ - capture.Paragraphs=doc.CaptureFragments.ToArray();doc.CaptureFragments.Clear();doc.Capture=null;var context=doc.Authentication;uploading=1; + capture.Paragraphs=doc.CaptureFragments.ToArray();doc.CaptureFragments.Clear();doc.Capture=null;var context=doc.Authentication;var baseRevision=doc.CaptureBaseRevision;var baseHash=doc.CaptureBaseHash;uploading=1; doc.Status="Sending manuscript to PlotDirector; waiting for durable acceptance…"; - _=Task.Run(async()=>{try{await cloud.Capture(capture,context);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc){doc.AcceptedRevision=capture.Revision;doc.Status="Manuscript received by PlotDirector. Continue analysis and review in the import wizard. Word text is unchanged.";}}catch(Exception e)when(NetworkFailure(e)){_=cloud.FailCapture(capture.RequestId,context);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc)doc.Status="Manuscript was not acknowledged: "+e.Message+" Retry from PlotDirector.";}finally{lock(gate)uploading=0;}}); + _=Task.Run(async()=>{try{var rows=capture.ParagraphTracking?paragraphSnapshots.Prepare(doc.Session,context,capture,baseRevision,baseHash):null;var reply=await cloud.Capture(capture,context);if(rows!=null)paragraphSnapshots.Accept(doc.Session,context,capture.ManuscriptId,rows,reply);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc){doc.AcceptedRevision=capture.Revision;doc.Status=baseRevision>0?"Word snapshot received. Review scene structure and evidence in PlotDirector; Word text is unchanged.":"Manuscript received by PlotDirector. Continue analysis and review in the import wizard. Word text is unchanged.";}}catch(Exception e)when(NetworkFailure(e)){_=cloud.FailCapture(capture.RequestId,context);lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc)doc.Status="Manuscript was not acknowledged: "+e.Message+" Retry from PlotDirector.";}finally{lock(gate)uploading=0;}}); } } public void RefreshPresence(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status="Checking document connection. Use Import manuscript in PlotDirector to transfer prose.";}} @@ -142,7 +146,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C public sealed class TrayDocument { public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath=""; - public ManuscriptCapture? Capture;public List CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision; + public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision; public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started; public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List Errors=[]; internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;} diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index fd09bcdb..aa99a7fb 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable lock (gate) activePipe = pipe; await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false); if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner."); - await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability }, stop.Token).ConfigureAwait(false); + await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability }, stop.Token).ConfigureAwait(false); mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments. await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false); attempt = 0; StateChanged?.Invoke("connected"); diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 1d7e798f..9c3ff63d 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.17 +1.0.0.18 diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphDelta.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphDelta.cs new file mode 100644 index 00000000..697e474f --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphDelta.cs @@ -0,0 +1,38 @@ +namespace PlotDirector.Companion.Protocol.Manuscript; +public sealed class ParagraphDelta +{ + public long BaseRevision {get;set;} + public Guid[] Order {get;set;}=Array.Empty(); + public ParagraphDeltaItem[] Changes {get;set;}=Array.Empty(); +} +public sealed class ParagraphDeltaItem +{ + public Guid Id {get;set;} + public string NativeId {get;set;}=""; + public int Span {get;set;} + public int Outline {get;set;} + public string? Text {get;set;} + public Guid? TextFrom {get;set;} +} +public static class ParagraphDeltaCodec +{ + public static ParagraphDelta Create(long revision,IReadOnlyList prior,IReadOnlyList current) + { + var old=prior.ToDictionary(p=>p.Id);var hashes=prior.GroupBy(p=>ParagraphReconciliation.Fingerprint(p.Text)).ToDictionary(g=>g.Key,g=>g.First());var changes=new List(); + foreach(var p in current){var exists=old.TryGetValue(p.Id,out var previous);if(exists&&previous!.Text==p.Text&&previous.NativeId==p.NativeId&&previous.Outline==p.Outline&&previous.End-previous.Start==p.End-p.Start)continue; + hashes.TryGetValue(ParagraphReconciliation.Fingerprint(p.Text),out var sameText); + changes.Add(new(){Id=p.Id,NativeId=p.NativeId,Span=p.End-p.Start,Outline=p.Outline,Text=sameText==null?p.Text:null,TextFrom=sameText?.Id});} + return new(){BaseRevision=revision,Order=current.Select(p=>p.Id).ToArray(),Changes=changes.ToArray()}; + } + public static ParagraphOccurrence[] Expand(ParagraphDelta delta,IReadOnlyList prior,int end) + { + if(delta.Order==null||delta.Changes==null||delta.Order.Length>100000||delta.Changes.Length>100000||delta.Order.Any(i=>i==Guid.Empty)||delta.Order.Distinct().Count()!=delta.Order.Length)throw new ArgumentException("Invalid paragraph delta order."); + var old=prior.ToDictionary(p=>p.Id);var edits=delta.Changes.ToDictionary(p=>p.Id);var orderIds=new HashSet(delta.Order);if(edits.Keys.Any(k=>!orderIds.Contains(k)))throw new ArgumentException("Delta has an orphan edit."); + var result=new List();int position=0;long total=0; + foreach(var id in delta.Order){old.TryGetValue(id,out var original);edits.TryGetValue(id,out var edit);var text=edit==null?original?.Text:edit.Text??(edit.TextFrom.HasValue?(old.TryGetValue(edit.TextFrom.Value,out var referenced)?referenced.Text:null):null); + if(text==null)throw new ArgumentException("Delta base paragraph is unavailable.");var span=edit?.Span??(original!.End-original.Start);total+=text.Length;if(span<=0||span>16*1024*1024||total>16*1024*1024||position>(16*1024*1024)-span)throw new ArgumentException("Delta exceeds manuscript bounds."); + result.Add(new(){Id=id,Ordinal=result.Count,Text=text,NativeId=WordParagraphIdentity.Normalise(edit?.NativeId??original!.NativeId),Outline=edit?.Outline??original!.Outline,Start=position,End=position+span});position+=span; + } + if(position!=end)throw new ArgumentException("Delta does not cover the captured document.");return result.ToArray(); + } +} diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphIdentity.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphIdentity.cs new file mode 100644 index 00000000..5320037c --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphIdentity.cs @@ -0,0 +1,116 @@ +using System.Security.Cryptography; +using System.Text; +using System.Xml; +namespace PlotDirector.Companion.Protocol.Manuscript; +public sealed class ParagraphOccurrence +{ + public Guid Id {get;set;} + public string NativeId {get;set;}=""; + public string Fingerprint {get;set;}=""; + public string Text {get;set;}=""; + public string PreviousText {get;set;}=""; + public int Ordinal {get;set;} + public int Start {get;set;} + public int End {get;set;} + public int Outline {get;set;}=10; + public Guid? PreviousId {get;set;} + public Guid? NextId {get;set;} + public string Change {get;set;}="Inserted"; + public bool WasMoved {get;set;} + public string Resolution {get;set;}="New"; +} +public sealed class ParagraphComparison +{ + public ParagraphOccurrence[] Current {get;set;}=Array.Empty(); + public ParagraphOccurrence[] Removed {get;set;}=Array.Empty(); + public int Ambiguous {get;set;} +} +// Word w14:paraId is a document-part hint, not PlotDirector identity or proof of permanence. +public static class WordParagraphIdentity +{ + public static string Read(string xml) + { + if(string.IsNullOrEmpty(xml)||xml.Length>256*1024)return ""; + try{using var input=new StringReader(xml);using var reader=XmlReader.Create(input,new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=256*1024}); + bool package=false,main=false;int partDepth=-1; + while(reader.Read()) { + if(reader.NodeType==XmlNodeType.Element&&reader.LocalName=="package"&&reader.NamespaceURI=="http://schemas.microsoft.com/office/2006/xmlPackage")package=true; + if(reader.NodeType==XmlNodeType.Element&&reader.LocalName=="part"&&reader.NamespaceURI=="http://schemas.microsoft.com/office/2006/xmlPackage"){partDepth=reader.Depth;main=reader.GetAttribute("name","http://schemas.microsoft.com/office/2006/xmlPackage")=="/word/document.xml";} + if(reader.NodeType==XmlNodeType.EndElement&&reader.Depth==partDepth){main=false;partDepth=-1;} + if((!package||main)&&reader.NodeType==XmlNodeType.Element&&reader.LocalName=="p"&&reader.NamespaceURI=="http://schemas.openxmlformats.org/wordprocessingml/2006/main")return Normalise(reader.GetAttribute("paraId","http://schemas.microsoft.com/office/word/2010/wordml")); + } + }catch(XmlException){}return ""; + } + public static string Normalise(string? id)=>id!=null&&id.Length==8&&uint.TryParse(id,System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var n)&&n>0&&n<0x80000000?id.ToUpperInvariant():""; +} +public static class ParagraphReconciliation +{ + public static string Fingerprint(string text){using var hash=SHA256.Create();return BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-","");} + public static string SnapshotFingerprint(IReadOnlyList rows){var buffer=new StringBuilder();foreach(var row in rows)buffer.Append(row.NativeId.Length).Append(':').Append(row.NativeId).Append(':').Append(row.Outline).Append(':').Append(row.End-row.Start).Append(':').Append(row.Text.Length).Append(':').Append(row.Text);return Fingerprint(buffer.ToString());} + public static ParagraphComparison Compare(IReadOnlyList previous,IReadOnlyList incoming) + { + if(previous.Count>100000||incoming.Count>100000)throw new ArgumentException("Paragraph limit exceeded."); + if(previous.Any(p=>p.Id==Guid.Empty)||previous.Select(p=>p.Id).Distinct().Count()!=previous.Count)throw new ArgumentException("Invalid prior occurrence identities."); + var old=previous.ToArray();var next=incoming.Select((p,i)=>new ParagraphOccurrence{NativeId=WordParagraphIdentity.Normalise(p.NativeId),Text=p.Text,Fingerprint=Fingerprint(p.Text),Ordinal=i,Start=p.Start,End=p.End,Outline=p.Outline}).ToArray(); + if(next.Sum(p=>(long)p.Text.Length)>16*1024*1024)throw new ArgumentException("Manuscript text exceeds limit."); + var used=new HashSet();var pairs=new Dictionary(); + void Match(int a,int b,string resolution){if(!used.Contains(a)&&!pairs.ContainsKey(b)){used.Add(a);pairs[b]=a;next[b].Id=old[a].Id;next[b].Resolution=resolution;}} + // An unchanged sequence is sufficient to preserve occurrences even when Word regenerates its XML hints. + var oldNativePositions=old.Select((p,i)=>(Id:WordParagraphIdentity.Normalise(p.NativeId),Index:i)).Where(p=>p.Id!="").GroupBy(p=>p.Id).Where(g=>g.Count()==1).ToDictionary(g=>g.Key,g=>g.Single().Index); + var nativeContradiction=next.Select((p,i)=>(p.NativeId,i)).Any(p=>p.NativeId!=""&&oldNativePositions.TryGetValue(p.NativeId,out var at)&&at!=p.i); + if(!nativeContradiction&&old.Length==next.Length&&old.Select(p=>p.Text).SequenceEqual(next.Select(p=>p.Text))){for(var i=0;i(p,i)).Where(x=>WordParagraphIdentity.Normalise(x.p.NativeId)!="").GroupBy(x=>WordParagraphIdentity.Normalise(x.p.NativeId)).ToDictionary(g=>g.Key,g=>g.Select(x=>x.i).ToArray()); + var newNative=next.Select((p,i)=>(p,i)).Where(x=>x.p.NativeId!="").GroupBy(x=>x.p.NativeId).ToDictionary(g=>g.Key,g=>g.Select(x=>x.i).ToArray()); + foreach(var entry in newNative)if(entry.Value.Length==1&&oldNative.TryGetValue(entry.Key,out var prior)&&prior.Length==1)Match(prior[0],entry.Value[0],"Native identifier"); + var oldHashes=old.Select((p,i)=>(Hash:Fingerprint(p.Text),Index:i)).GroupBy(x=>x.Hash).ToDictionary(g=>g.Key,g=>g.Select(x=>x.Index).ToArray()); + var newHashes=next.Select((p,i)=>(Hash:p.Fingerprint,Index:i)).GroupBy(x=>x.Hash).ToDictionary(g=>g.Key,g=>g.Select(x=>x.Index).ToArray()); + // Independently unique adjacent content can establish a context pair if Word hints disappeared. + foreach(var entry in newHashes){if(entry.Value.Length!=1||!oldHashes.TryGetValue(entry.Key,out var prior)||prior.Length!=1)continue;int a=prior[0],b=entry.Value[0];if(used.Contains(a)||pairs.ContainsKey(b))continue; + bool SameNeighbour(int x,int y)=>x>=0&&x=0&&y0&&a>0&&pairs.TryGetValue(b-1,out var left)&&left==a-1)||(b+1(prior);var candidates=new Dictionary>(); + foreach(var b in entry.Value.Where(b=>!pairs.ContainsKey(b))){var adjacent=new HashSet(); + if(b>0&&pairs.TryGetValue(b-1,out var left)&&priorSet.Contains(left+1)&&!used.Contains(left+1))adjacent.Add(left+1); + if(b+1();if(values.Count<2)values.Add(b); + } + foreach(var candidate in candidates.Where(c=>c.Value.Count==1))Match(candidate.Key,candidate.Value[0],"Duplicate resolved by neighbour"); + } + // A single rewritten paragraph between two independently recognised neighbours is a reviewable occurrence, + // provided its old text has not moved elsewhere. Splits/merges and competing copies remain unresolved. + for(int b=1;b+1(oldHashes.Where(entry=>entry.Value.All(used.Contains)).Select(entry=>entry.Key)); + foreach(var p in next.Where(p=>p.Id==Guid.Empty))if(oldHashes.ContainsKey(p.Fingerprint)||(p.NativeId!=""&&oldNative.ContainsKey(p.NativeId)))p.Resolution=copiedHashes.Contains(p.Fingerprint)?"New copy":"Ambiguous"; + } + // Longest increasing subsequence distinguishes moves from index shifts caused by insertion/deletion. + var matched=pairs.OrderBy(p=>p.Key).ToArray();var tails=new List();var tailEntries=new List();var links=new int[matched.Length]; + for(int i=0;i0?tailEntries[lo-1]:-1;if(lo==tails.Count){tails.Add(matched[i].Value);tailEntries.Add(i);}else{tails[lo]=matched[i].Value;tailEntries[lo]=i;}} + var stable=new HashSet();for(int i=tailEntries.Count==0?-1:tailEntries[tailEntries.Count-1];i>=0;i=links[i])stable.Add(matched[i].Key); + var oldIds=new HashSet(old.Select(p=>p.Id));var proposedCounts=incoming.Where(p=>p.Id!=Guid.Empty).GroupBy(p=>p.Id).ToDictionary(g=>g.Key,g=>g.Count()); + for(int i=0;i0?next[i-1].Id:(Guid?)null; + } + for(int i=0;i+1!used.Contains(i)).ToArray(),Ambiguous=next.Count(p=>p.Resolution=="Ambiguous")}; + } + // Reassemble exactly the existing bounded stream; no paragraph text matching or prose rewriting. + public static ParagraphOccurrence[] Assemble(ParagraphFragment[] fragments,int documentEnd) + { + var rows=new List();var text=new StringBuilder();int position=0,index=1,start=0,outline=10;string native=""; + foreach(var f in fragments){if(f.Text==null||f.Start!=position||f.End<=f.Start||f.End>documentEnd||f.Text.Length>ProtocolVersion.MaxParagraphCharacters||f.ParagraphIndex!=index)throw new ArgumentException("Incomplete paragraph stream."); + if(text.Length==0){start=f.Start;outline=f.OutlineLevel;native=WordParagraphIdentity.Normalise(f.NativeParagraphId);} + else if(f.NativeParagraphId!=""&&WordParagraphIdentity.Normalise(f.NativeParagraphId)!=native)throw new ArgumentException("Paragraph identifier changed within a batch."); + text.Append(f.Text);position=f.End;if(f.CompletesParagraph){rows.Add(new(){Ordinal=rows.Count,Start=start,End=position,Outline=outline,NativeId=native,Text=text.ToString()});text.Clear();index++;} + if(rows.Count>100000||position>16*1024*1024)throw new ArgumentException("Paragraph stream exceeds limit."); + } + if(position!=documentEnd||text.Length!=0)throw new ArgumentException("Incomplete paragraph stream.");return rows.ToArray(); + } +} diff --git a/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs b/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs index 4d10dc1c..39e3d862 100644 --- a/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs +++ b/PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs @@ -3,6 +3,9 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class ManuscriptCapture { + [DataMember] public Guid[]? ParagraphIds {get;set;} + [DataMember] public Manuscript.ParagraphDelta? Delta {get;set;} + [DataMember] public bool ParagraphTracking {get;set;} [DataMember] public Guid RequestId {get;set;} [DataMember] public Guid InstanceId {get;set;} [DataMember] public Guid SessionId {get;set;} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index 315532b5..255b058a 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol; public static class ProtocolVersion { public const int Current = 1; + public const string ParagraphCapability="paragraph-snapshots-v1"; public const string MaintenanceCapability="document-maintenance-v1"; public const string CaptureCapability="wizard-capture-v1"; public const string TrayCapability="tray-adapter-v1"; @@ -86,6 +87,7 @@ public sealed class DocumentDescriptor [DataContract] public sealed class ParagraphFragment { + [DataMember] public string NativeParagraphId {get;set;}=""; [DataMember] public int ParagraphIndex { get; set; } [DataMember] public int Start { get; set; } [DataMember] public int End { get; set; } diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index 239c8df8..8b3400ad 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -3,6 +3,9 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AdapterCommand { + [DataMember] public bool ParagraphTracking {get;set;} + [DataMember] public long BaseRevision {get;set;} + [DataMember] public string BaseSnapshotHash {get;set;}=""; [DataMember] public Guid Id {get;set;}=Guid.NewGuid(); [DataMember] public string Kind {get;set;}=""; [DataMember] public Guid SessionId {get;set;} @@ -16,6 +19,10 @@ public sealed class AdapterCommand [DataContract] public sealed class NativePresence { + [DataMember] public Guid[]? CanonicalParagraphIds {get;set;} + [DataMember] public long ParagraphRevision {get;set;} + [DataMember] public string ParagraphSnapshotHash {get;set;}=""; + [DataMember] public bool CanParagraphSync {get;set;} [DataMember] public Guid CatalogVersion {get;set;} [DataMember] public Guid? CaptureRequestId {get;set;} [DataMember] public int CaptureProgress {get;set;} diff --git a/PlotDirector.NativeCompanion/Tests/ParagraphSnapshotTests.cs b/PlotDirector.NativeCompanion/Tests/ParagraphSnapshotTests.cs new file mode 100644 index 00000000..57f96c6e --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/ParagraphSnapshotTests.cs @@ -0,0 +1,18 @@ +using PlotDirector.Companion.Agent; +using PlotDirector.Companion.Protocol; +using PlotDirector.Companion.Protocol.Manuscript; +internal static class ParagraphSnapshotTests +{ + public static void Run(Action check) + { + var cache=new ParagraphSnapshotCache();var session=Guid.NewGuid();var auth=Guid.NewGuid();var manuscript=Guid.NewGuid(); + ManuscriptCapture Capture(string second="Second.\r")=>new(){ParagraphTracking=true,ManuscriptId=manuscript,End=7+second.Length,Paragraphs=[new(){ParagraphIndex=1,Start=0,End=7,Text="First.\r",CompletesParagraph=true,NativeParagraphId="00000001"},new(){ParagraphIndex=2,Start=7,End=7+second.Length,Text=second,CompletesParagraph=true,NativeParagraphId="00000002"}]}; + var capture=Capture();var rows=cache.Prepare(session,auth,capture,0,"");var serverIds=new[]{Guid.NewGuid(),Guid.NewGuid()};cache.Accept(session,auth,manuscript,rows,new(){CanonicalParagraphIds=serverIds,ParagraphRevision=1}); + var hash=ParagraphReconciliation.SnapshotFingerprint(rows);capture=Capture("Changed.\r");rows=cache.Prepare(session,auth,capture,1,hash); + check(capture.Delta?.Changes.Length==1&&capture.Paragraphs.Length==0&&rows[1].Id==serverIds[1],"snapshot cache transfers only changed paragraph prose using acknowledged server occurrence IDs"); + var another=Capture();cache.Prepare(Guid.NewGuid(),auth,another,1,hash);check(another.Delta==null,"another live document cannot use this session's delta base"); + var account=Capture();cache.Prepare(session,Guid.NewGuid(),account,1,hash);check(account.Delta==null&&!account.ParagraphIds!.Intersect(serverIds).Any(),"account switching never reuses prior account cache identities or source"); + var stale=Capture();cache.Prepare(session,auth,stale,2,"wrong-base");check(stale.Delta==null,"mismatched server base falls back to a complete authorised snapshot"); + cache.Remove(session);var restarted=Capture();cache.Prepare(session,auth,restarted,1,hash);check(restarted.Delta==null,"agent restart/disconnect has no plaintext cache dependency; server reconciliation recovers from full snapshot"); + } +} diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index b22819c5..cf76718a 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -180,6 +180,7 @@ Check(DocumentMaintenancePolicy.Properties.Length==5&&!DocumentMaintenancePolicy await AnalysisTests.Run(Check); await ChapterAiTests.Run(Check); await WorkflowTests.Run(Check); +ParagraphSnapshotTests.Run(Check); await TrayTests.Run(Check); await NativeConnectionRefreshTests.Run(Check); await PersistentConnectionTests.Run(Check); diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 9ebec784..e0f37e62 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("1.0.0.17")] -[assembly: AssemblyFileVersion("1.0.0.17")] +[assembly: AssemblyVersion("1.0.0.18")] +[assembly: AssemblyFileVersion("1.0.0.18")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index b19ce1d2..079243fa 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -228,8 +228,10 @@ namespace PlotDirector.WordAddIn try{ if(doc.Maintenance!=null){var previous=doc.Maintenance;scheduler.Cancel("maintenance:"+doc.Session);Reply(previous,"Stopped: superseded by a new document request. Inspect before retrying cleanup.");} if(command.Kind.StartsWith("maintenance-",StringComparison.Ordinal)){StartMaintenance(doc,command);return;} - else if(command.Kind=="wizard-capture"){ - CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true,command.Id))throw new InvalidOperationException("Word queue unavailable. Retry import from PlotDirector."); + else if((command.Kind=="wizard-capture"||command.Kind=="paragraph-snapshot")){ + CancelExtraction(doc); + if(command.ParagraphTracking&&!doc.IdentityPersisted){if(Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Save a writable copy before enabling persistent paragraph tracking.");WriteProperty(doc.Document,"PlotDirector.Native.DocumentGuid",doc.Identity.ToString("D"),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);doc.IdentityPersisted=true;Com(()=>{doc.Document.Saved=false;return true;});doc.WasSaved=false;} + doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true,command.Id,command.ParagraphTracking))throw new InvalidOperationException("Word queue unavailable. Retry import from PlotDirector."); } else if(command.Kind=="detect"){ CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true))throw new InvalidOperationException("Word queue unavailable. Retry detection."); @@ -308,10 +310,10 @@ namespace PlotDirector.WordAddIn if(!scheduler.Post("maintenance:"+doc.Session,next))Reply(command,"Stopped: Word queue busy."); } private void Reply(AdapterCommand command,string result){var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);if(doc?.Maintenance==command)doc.Maintenance=null;link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result});} - private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false,Guid? snapshot=null) + private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false,Guid? snapshot=null,bool paragraphs=false) { if (doc.Extraction != null || ConnectionState != "connected") return false; - doc.Extraction = new Extraction { Snapshot = snapshot??Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End }; + doc.Extraction = new Extraction { Snapshot = snapshot??Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End,ParagraphTracking=paragraphs }; if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc))) {doc.Extraction=null;return false;} return true; @@ -363,7 +365,7 @@ namespace PlotDirector.WordAddIn } private Message ReadFragment(LocalDocument doc,Extraction extraction) { - Word.Range point=null,paragraphRange=null,textRange=null; Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null; + Word.Range point=null,paragraphRange=null,textRange=null,identityRange=null; Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null; try { string[] tags=Array.Empty(); @@ -378,6 +380,12 @@ namespace PlotDirector.WordAddIn extraction.OutlineLevel=(int)Com(()=>paragraph.OutlineLevel); extraction.ParagraphIndex++; tags=ReadMarkers(paragraphRange); + extraction.NativeParagraphId=""; + if(extraction.ParagraphTracking){ + identityRange=Com(()=>doc.Document.Range(extraction.Position,Math.Min(extraction.Position+1,extraction.ParagraphEnd))); + try{var xml=Com(()=>identityRange.WordOpenXML);extraction.NativeParagraphId=PlotDirector.Companion.Protocol.Manuscript.WordParagraphIdentity.Read(xml);} + catch(COMException){/* XML hints are optional; context reconciliation remains conservative. */} + } } 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."); @@ -387,9 +395,9 @@ namespace PlotDirector.WordAddIn extraction.Position=end; 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}}; + Text=text,NativeParagraphId=extraction.NativeParagraphId,MarkerTags=tags,CompletesParagraph=end>=extraction.ParagraphEnd}}; } - finally { Release(textRange);Release(paragraphRange);Release(paragraph);Release(paragraphs);Release(point); } + finally { Release(identityRange);Release(textRange);Release(paragraphRange);Release(paragraph);Release(paragraphs);Release(point); } } private string[] ReadMarkers(Word.Range range) { @@ -446,11 +454,12 @@ namespace PlotDirector.WordAddIn 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.IsAi)link.Reset(); doc.Extraction=null; } + private bool UnchangedBeforeSave(Word.Document document,LocalDocument state){try{return Com(()=>document.Saved)&&DocumentEnd(document)==state.End;}catch(COMException){return false;}catch(InvalidOperationException){return false;}} 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)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Revision++;state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";RegisterState(state);} + if(documents.TryGetValue(document,out var state)){if(UnchangedBeforeSave(document,state))return;StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Revision++;state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";RegisterState(state);} } private void BeforeClose(Word.Document document,ref bool cancel) { @@ -595,6 +604,6 @@ namespace PlotDirector.WordAddIn public LocalDocument(Word.Document document){Document=document;} } private sealed class Extraction - {public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;} + {public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi,ParagraphTracking;public string NativeParagraphId="";public Message Pending;} } } diff --git a/PlotLine.Tests/Browser/native-import-connection.cjs b/PlotLine.Tests/Browser/native-import-connection.cjs index 15e089bf..8b4e9968 100644 --- a/PlotLine.Tests/Browser/native-import-connection.cjs +++ b/PlotLine.Tests/Browser/native-import-connection.cjs @@ -22,5 +22,9 @@ const {chromium}=require('playwright');const fs=require('node:fs');const path=re await state([{...manuscript,expires:new Date(Date.now()-1000).toISOString()}]);assert.equal(await button.isDisabled(),true,'stale document cannot enable import'); await page.evaluate(()=>handlers.WordCompanionPresenceChanged({isConnected:true,documentOpen:true,currentDocumentName:'Legacy Word'}));assert.equal(await button.isDisabled(),false,'connected Office.js workflow remains available when native manuscript is stale');await page.evaluate(()=>handlers.WordCompanionPresenceChanged({isConnected:false})); await state([{...manuscript,bookId:5}]);assert.equal(await page.evaluate(()=>invocations.includes('StartOnboardingManuscriptScan')),false,'presence updates never upload prose');await button.click();await page.waitForFunction(()=>invocations.includes('StartOnboardingManuscriptScan')); + await page.evaluate(()=>{handlers.OnboardingScanStateChanged({status:'NotStarted',percentComplete:0});const checkbox=document.createElement('input');checkbox.type='checkbox';checkbox.dataset.paragraphTracking='';checkbox.checked=true;document.body.append(checkbox);}); + assert.equal(await page.evaluate(()=>invocations.includes('StartParagraphManuscriptScan')),false,'opting in alone must not upload'); + await state([{...manuscript,bookId:5,canParagraphSync:true}]);await button.click();await page.waitForFunction(()=>invocations.includes('StartParagraphManuscriptScan')); + console.log('PASS explicit paragraph opt-in chooses the additive hub method; unchanged legacy callers remain compatible'); console.log('PASS browser wizard states: disconnected, authenticated/no Word, Word/no manuscript, unassociated first import, selected book, wrong book, stale lease and explicit-only transfer'); }finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/PlotLine.Tests/Browser/paragraph-manuscript.cjs b/PlotLine.Tests/Browser/paragraph-manuscript.cjs new file mode 100644 index 00000000..144d990e --- /dev/null +++ b/PlotLine.Tests/Browser/paragraph-manuscript.cjs @@ -0,0 +1,21 @@ +const {chromium}=require('playwright'); +const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const assert=require('node:assert/strict'); +(async()=>{ + const fixture=path.join(os.tmpdir(),'pd-paragraph-review-fixture.html'); + assert.ok(fs.existsSync(fixture),'First run dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --paragraph-view'); + const browser=await chromium.launch();try{ + const page=await browser.newPage();const failures=[];page.on('pageerror',e=>failures.push(e.message)); + await page.setContent(fs.readFileSync(fixture,'utf8')); + assert.equal(await page.locator('article').count(),100,'actual compiled view bounds paragraph pagination'); + assert.equal(await page.locator('script').count(),0,'manuscript markup must remain encoded text'); + assert.equal(await page.locator('select[name="eventKey"] option').first().getAttribute('value'),'Knowledge:9','event kind and ID travel together'); + for(const name of ['Synchronise from Word','Cancel pending snapshot','Refresh saved snapshot'])assert.equal(await page.getByRole(name==='Refresh saved snapshot'?'link':'button',{name,exact:true}).count(),1); + for(const form of await page.locator('form[method="post"]').all()){ + assert.equal(await form.locator('input[name="__RequestVerificationToken"]').count(),1,'every mutation form has antiforgery'); + assert.match(await form.getAttribute('action'),/^\/manuscript\/paragraphs\/(enable|snapshot|cancel|change)$/,'actions use the existing authorised controller'); + } + assert.doesNotMatch(await page.locator('body').innerText(),/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,'opaque identities are hidden inputs, never author labels'); + assert.deepEqual(failures,[]); + console.log('PASS actual compiled paragraph workspace DOM: bounded results, functional scoped form actions, typed evidence choice, encoded prose and antiforgery; shared-shell/Windows visual qualification not claimed'); + }finally{await browser.close();} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/PlotLine.Tests/NativeImportCorrectionTests.cs b/PlotLine.Tests/NativeImportCorrectionTests.cs index 0bb68d13..f07b5226 100644 --- a/PlotLine.Tests/NativeImportCorrectionTests.cs +++ b/PlotLine.Tests/NativeImportCorrectionTests.cs @@ -17,6 +17,9 @@ internal static class NativeImportCorrectionTests { await CheckpointRetry(); await Boundary97Versus99(); + var integer=Response(1,false).Replace("\"schemaVersion\":\"1.0\"","\"schemaVersion\":\"2.0\"").Replace("\"confidence\":0.9","\"confidence\":90"); + var (integerService,_)=Analysis(integer);var integerResult=await integerService.AnalyseChapterAsync(new(){ConfidenceContractVersion=2,ChapterText="Original narrative.\r",ParagraphMap=[new(){StructuralParagraphOrdinal=1,WordParagraphIndex=1,Text="Original narrative.\r"}],SourceParagraphs=[new(){WordParagraphIndex=1,Text="Original narrative.\r",IncludeInSourceText=true}]}); + Check(integerResult.Success&&integerResult.Scenes.Single().Confidence==.9m&&integerResult.ParsedJson!.Contains("\"confidence\":90"),"Integer provider confidence is persisted as schema 2.0 and normalized once for legacy domain consumers"); var options=new JsonSerializerOptions(JsonSerializerDefaults.Web); var parsed=StoryIntelligenceAiJsonParser.Parse(Response(4),options); Check(parsed.Success&&parsed.Parsed!.SceneBoundaries![3].Confidence==0.9m&&parsed.Warnings.Count>0,"Observed Counting the Days confidence token 0. Nine is repaired transparently without changing paragraph coordinates"); diff --git a/PlotLine.Tests/ParagraphManuscriptTests.cs b/PlotLine.Tests/ParagraphManuscriptTests.cs new file mode 100644 index 00000000..91395b8f --- /dev/null +++ b/PlotLine.Tests/ParagraphManuscriptTests.cs @@ -0,0 +1,75 @@ +using System.Diagnostics; +using System.Text.Json; +using PlotDirector.Companion.Protocol.Manuscript; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.Services.Manuscript; +internal static class ParagraphManuscriptTests +{ + private static int count; + private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);count++;} + private static ParagraphOccurrence[] Rows(params string[] texts){int start=0;return texts.Select((text,i)=>{var p=new ParagraphOccurrence{Text=text,Ordinal=i,NativeId=(i+1).ToString("X8"),Start=start,End=start+text.Length,Outline=10};start=p.End;return p;}).ToArray();} + private static ParagraphManuscript Initial()=>ParagraphManuscriptEngine.Bootstrap(4,2,Guid.NewGuid(),Rows("Arrival.\r","The keeper handed Mira the sealed letter.\r","No.\r","The train departed.\r","No.\r","Dusk.\r"),[new(){SceneId=41,ChapterId=11,Title="Arrival",Start=1,End=3},new(){SceneId=42,ChapterId=11,Title="Departure",Start=4,End=6}]); + public static void Run() + { + var capture=new PlotDirector.Companion.Protocol.ManuscriptCapture{ParagraphTracking=true,End=8,Paragraphs=[new(){Start=0,End=8,Text="Heading\r",ParagraphIndex=1,OutlineLevel=1,CompletesParagraph=true,NativeParagraphId="00000011"}]}; + var preview=PlotLine.Services.NativeCompanion.NativeManuscriptCapture.Build(capture,7,4,2,3,"Synthetic document"); + Check(preview.ParagraphTracking&&preview.NativeParagraphs?.Single().Id!=Guid.Empty&&preview.NativeParagraphs?.Single().Text=="Heading\r","Opted-in import capture retains raw paragraph text and opaque occurrence identity"); + var state=Initial();var ids=state.Paragraphs.Select(p=>p.Occurrence.Id).ToArray(); + Check(ids.Distinct().Count()==6&&ids.All(id=>id!=Guid.Empty),"Opaque occurrence IDs, including separate identical dialogue"); + var saved=ParagraphManuscriptEngine.Clone(state);ParagraphManuscriptEngine.Reconcile(saved,state.Paragraphs.Select(p=>p.Occurrence).ToArray()); + Check(saved.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(ids),"Saved snapshot and process reconstruction retain occurrence identities"); + var evidence=ParagraphManuscriptEngine.Anchor(state,"Knowledge",91,true,1,1,null,null);var original=evidence.OriginalText; + var current=state.Paragraphs.Select(p=>p.Occurrence).ToList();var moved=current[1];current.RemoveAt(1);current.Insert(4,moved);ParagraphManuscriptEngine.Reconcile(state,current); + Check(evidence.State=="Verified"&&evidence.DerivedSceneId==42&&state.Evidence.Count==1,"Reliable paragraph move updates derived event scene without copying event"); + var copy=new ParagraphOccurrence{Text=moved.Text,NativeId=moved.NativeId,Outline=10};current=state.Paragraphs.Select(p=>p.Occurrence).ToList();current.Add(copy);ParagraphManuscriptEngine.Reconcile(state,current); + Check(state.Paragraphs.Last().Occurrence.Id!=moved.Id&&state.Evidence.Count==1,"Copied paragraph has a distinct identity and no duplicated story event"); + state=Initial();evidence=ParagraphManuscriptEngine.Anchor(state,"Relationship",92,true,1,1,null,null);current=state.Paragraphs.Select(p=>p.Occurrence).ToList();current[1]=new(){Text="Mira refused the letter.\r",NativeId=current[1].NativeId,Outline=10};ParagraphManuscriptEngine.Reconcile(state,current); + Check(evidence.State=="Needs review"&&evidence.OriginalText==original&&evidence.CurrentText.Contains("refused")&&evidence.DerivedSceneId==null,"Rewritten evidence retains original passage and withholds unconfirmed derived facts"); + ParagraphManuscriptEngine.Confirm(state,evidence.Id);Check(evidence.State=="Verified","Author confirmation verifies changed evidence"); + current=state.Paragraphs.Select(p=>p.Occurrence).ToList();current.RemoveAt(1);ParagraphManuscriptEngine.Reconcile(state,current); + Check(evidence.State=="Missing"&&state.Evidence.Single().EventId==92&&evidence.OriginalText==original,"Deleting evidence preserves the event and before text"); + state=Initial();var raw=string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text));var first=state.Scenes[0].Id;var second=state.Scenes[1].Id; + ParagraphManuscriptEngine.Split(state,state.Paragraphs[1].Occurrence.Id,"The letter"); + Check(state.Scenes.Count(s=>!s.Retired)==3&&string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text))==raw,"Scene split preserves every raw Word character"); + ParagraphManuscriptEngine.Undo(state);Check(state.Paragraphs[1].SceneId==first&&state.Scenes.Count(s=>!s.Retired)==2,"Undo restores grouping and opaque scene identity"); + ParagraphManuscriptEngine.MoveBoundary(state,second,state.Paragraphs[2].Occurrence.Id); + Check(state.Paragraphs[2].SceneId==second,"Boundary moves between adjacent paragraphs"); + ParagraphManuscriptEngine.Merge(state,first,second);Check(state.Paragraphs.All(p=>p.SceneId==first)&&state.Scenes.Single(s=>s.Id==second).Retired&&string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text))==raw,"Adjacent merge retains text and retires, rather than destroys, scene identity"); + ParagraphManuscriptEngine.Undo(state);Check(state.Paragraphs[2].SceneId==second&&!state.Scenes.Single(s=>s.Id==second).Retired,"Merge undo restores original scene and prior boundary"); + var unresolved=Initial();foreach(var row in unresolved.Paragraphs.Take(3))row.PositionVerified=false;unresolved.Scenes[0].NeedsRefinement=true; + ParagraphManuscriptEngine.ConfirmGrouping(unresolved,unresolved.Scenes[0].Id); + Check(unresolved.Paragraphs.Take(3).All(p=>p.PositionVerified)&&!unresolved.Scenes[0].NeedsRefinement,"Author can explicitly confirm a proposed scene grouping without editing Word prose"); + ParagraphManuscriptEngine.Undo(unresolved);Check(unresolved.Paragraphs.Take(3).All(p=>!p.PositionVerified),"Grouping confirmation can be undone without discarding the Word snapshot"); + var excluded=Initial();excluded.Chapters.Add(new(){CanonicalId=0,HeadingId=excluded.Paragraphs[3].Occurrence.Id,Title="Explicitly excluded section"});foreach(var row in excluded.Paragraphs.Skip(3)){row.Story=false;row.SceneId=null;row.PositionVerified=false;} + ParagraphManuscriptEngine.Reconcile(excluded,excluded.Paragraphs.Select(p=>p.Occurrence).ToArray()); + Check(excluded.Paragraphs.Count(p=>p.Story)==3&&excluded.Paragraphs.Count==6,"Previously excluded import sections remain captured without silently importing their prose on sync"); + bool uncertain=false;try{ParagraphManuscriptEngine.Reconcile(excluded,excluded.Paragraphs.Where((p,i)=>i!=3).Select(p=>p.Occurrence).ToArray());}catch(InvalidOperationException){uncertain=true;} + Check(uncertain&&excluded.Paragraphs.Count==6,"An unresolvable excluded-section boundary refuses mutation instead of guessing where that book's prose starts"); + var before=ParagraphReconciliation.Compare([],Rows("Before.\r","Same.\r","Same.\r","After.\r")).Current; + var changes=Rows("Before.\r","Same.\r","New.\r","Same.\r","After.\r");changes[3].NativeId=before[2].NativeId;changes[4].NativeId=before[3].NativeId;changes[2].NativeId="00000030"; + var reconciled=ParagraphReconciliation.Compare(before,changes).Current; + Check(reconciled[1].Id==before[1].Id&&reconciled[3].Id==before[2].Id,"Identical short dialogue remains associated with its individual native occurrence"); + var delta=ParagraphDeltaCodec.Create(3,before,reconciled);var end=reconciled.Sum(p=>p.End-p.Start);var restored=ParagraphDeltaCodec.Expand(delta,before,end); + Check(restored.Select(p=>p.Id).SequenceEqual(reconciled.Select(p=>p.Id))&&restored.Select(p=>p.Text).SequenceEqual(reconciled.Select(p=>p.Text))&&delta.Changes.Count(p=>p.Text!=null)==1,"Delta sends only changed prose and retains occurrence order"); + var priorRewrite=Rows("Opening.\r","She entered.\r","Original revelation.\r","He waited.\r","Closing.\r");foreach(var row in priorRewrite)row.NativeId="";var priorIdentity=ParagraphReconciliation.Compare([],priorRewrite).Current; + var revised=Rows("Opening.\r","She entered.\r","Rewritten revelation.\r","He waited.\r","Closing.\r");foreach(var row in revised)row.NativeId="";var rewrite=ParagraphReconciliation.Compare(priorIdentity,revised); + Check(rewrite.Current[2].Id==priorIdentity[2].Id&&rewrite.Current[2].Change=="Modified"&&rewrite.Current[2].Resolution.Contains("review"),"Lost native hints can reconcile a single rewrite between recognised neighbours without matching a moved/copy candidate"); + var split=Rows("Before.\r","Same part one.\r","part two.\r","Same.\r","After.\r");split[2].NativeId="00000031";split[3].NativeId=before[2].NativeId;split[4].NativeId=before[3].NativeId; + var splitResult=ParagraphReconciliation.Compare(before,split);Check(splitResult.Current[1].Id==before[1].Id&&splitResult.Current[2].Id!=before[1].Id,"Paragraph split retains only the surviving occurrence identity"); + var xml=""; + Check(WordParagraphIdentity.Read(xml)=="00000022"&&WordParagraphIdentity.Read("]>&x;")=="","Word XML hint is restricted to main document part and forbids external entities"); + using var schema=JsonDocument.Parse(JsonSerializer.Serialize(ChapterStructureIntegerContract.ForParagraphCount(97).Schema)); + Check(schema.RootElement.GetProperty("properties").GetProperty("sceneBoundaries").GetProperty("items").GetProperty("properties").GetProperty("endParagraph").GetProperty("maximum").GetInt32()==97,"Provider schema is bounded by the actual 97 submitted paragraphs, never the raw source count 99"); + var request=JsonSerializer.Serialize(new ManuscriptStructureAnalysisRequest());Check(!request.Contains("ConfidenceContractVersion"),"Legacy request serialization omits new contract field, preserving checkpoint hashes"); + var validator=new ChapterStructureValidator();ChapterStructureModel Model(string schema,decimal confidence)=>new(){SchemaVersion=schema,ChapterSummary="Summary",SceneBoundaries=[new(){SceneNumber=1,StartParagraph=1,EndParagraph=1,Confidence=confidence,Reason="Single continuous scene",StructuralSummary="The manuscript contains one continuous narrative scene."}]}; + Check(validator.Validate(Model("1.0",.9m),1).IsValid&&validator.Validate(Model("2.0",90),1).IsValid&&!validator.Validate(Model("2.0",.9m),1).IsValid&&!validator.Validate(Model("2.0",101),1).IsValid,"Versioned integer confidence validation preserves legacy decimals and rejects new fractional scores"); + var large=Enumerable.Range(1,25000).Select(n=>new ParagraphOccurrence{Text=$"Paragraph {n}: one two three four five six seven eight nine.\r",NativeId=n.ToString("X8"),Start=n*65,End=n*65+65}).ToArray(); + var timer=Stopwatch.StartNew();var initial=ParagraphReconciliation.Compare([],large).Current;var repeat=ParagraphReconciliation.Compare(initial,large);timer.Stop(); + Check(repeat.Current.Select(p=>p.Id).SequenceEqual(initial.Select(p=>p.Id))&&timer.Elapsed{{41,0}},41); + Check(facts.Count==1&&facts[0].CharacterID==3,"Missing primary evidence is excluded from verified story facts while unanchored scene events remain compatible"); + Console.WriteLine($"{count} paragraph manuscript assertions passed."); + } +} diff --git a/PlotLine.Tests/ParagraphViewTests.cs b/PlotLine.Tests/ParagraphViewTests.cs new file mode 100644 index 00000000..b84c0832 --- /dev/null +++ b/PlotLine.Tests/ParagraphViewTests.cs @@ -0,0 +1,42 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Razor; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.DataProtection; +using PlotLine.Controllers; +using PlotLine.Models; +using PlotLine.Services.Manuscript; +using PlotDirector.Companion.Protocol.Manuscript; +internal static class ParagraphViewTests +{ + public static async Task Run() + { + var builder=WebApplication.CreateBuilder();builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");builder.Services.AddSingleton(new EphemeralDataProtectionProvider());builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ParagraphManuscriptController).Assembly); + await using var app=builder.Build();app.MapControllers();app.MapControllerRoute("default","{controller}/{action}/{id?}"); + app.MapGet("/fixture",async (HttpContext http)=>{ + http.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture")); + var rows=Enumerable.Range(1,210).Select(i=>new ParagraphOccurrence{Text=i==1?"\r":$"Saved narrative paragraph {i}.\r",Ordinal=i-1,Start=(i-1)*50,End=i*50}).ToArray(); + var state=ParagraphManuscriptEngine.Bootstrap(3,1,Guid.NewGuid(),rows,[new(){SceneId=11,ChapterId=4,Title="A long scene title",Start=1,End=210}]); + var route=new RouteData();route.Values["controller"]="ParagraphManuscript";route.Values["action"]="Index";var action=new ActionContext(http,route,new ActionDescriptor()); + var engine=http.RequestServices.GetRequiredService();var view=engine.GetView(null,"/Views/ParagraphManuscript/Index.cshtml",false);if(!view.Success)throw new Exception("Compiled paragraph view missing"); + using var output=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=new ParagraphWorkspaceModel{State=state,BookTitle="Synthetic book",Events=[new(){Kind="Knowledge",Id=9,SceneId=11,Description="The saved event"}]}}; + var temp=http.RequestServices.GetRequiredService().GetTempData(http);await view.View.RenderAsync(new ViewContext(action,view.View,data,temp,output,new HtmlHelperOptions())); + return Results.Content(output.ToString(),"text/html"); + }); + await app.StartAsync();try{ + var server=app.Services.GetRequiredService();var address=server.Features.Get()!.Addresses.Single();using var client=new HttpClient();var html=await client.GetStringAsync(address+"/fixture"); + if(!html.Contains("__RequestVerificationToken")||!html.Contains("/manuscript/paragraphs/change")||!html.Contains("Knowledge:9")||html.Contains("