Add opt-in paragraph manuscript reconciliation and evidence review foundation
This commit is contained in:
parent
2c0e02c7c9
commit
5d75546107
118
Docs/WordCompanion/2026-11-07-paragraph-sync-foundation.md
Normal file
118
Docs/WordCompanion/2026-11-07-paragraph-sync-foundation.md
Normal file
@ -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.
|
||||
@ -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<T>(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();
|
||||
|
||||
34
PlotDirector.NativeCompanion/Agent/ParagraphSnapshotCache.cs
Normal file
34
PlotDirector.NativeCompanion/Agent/ParagraphSnapshotCache.cs
Normal file
@ -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<Guid,Entry> 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<rows.Length;i++)rows[i].Id=ids[i];
|
||||
entries.Remove(session);
|
||||
while(entries.Count>=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);}
|
||||
}
|
||||
@ -56,7 +56,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
|
||||
}
|
||||
var trayAdapter=(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability);
|
||||
instance = hello.WordInstanceId; sessions.Attach(instance,lease);if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability));
|
||||
instance = hello.WordInstanceId; sessions.Attach(instance,lease);if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability));
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability},cancellation);
|
||||
log?.Invoke("peer-connected");
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
|
||||
@ -5,12 +5,15 @@ namespace PlotDirector.Companion.Agent;
|
||||
public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai)
|
||||
{
|
||||
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished;
|
||||
private bool ParagraphCapable(Guid instance){lock(gate)return paragraphInstances.Contains(instance);}
|
||||
private readonly ParagraphSnapshotCache paragraphSnapshots=new();
|
||||
private readonly HashSet<Guid> paragraphInstances=[];
|
||||
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
|
||||
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly HashSet<Guid> maintenanceInstances=[];private readonly Dictionary<Guid,(Guid Session,Guid Manuscript,Guid Authentication,string Kind,DateTime Started)> 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.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(doc.SceneId.HasValue?0:doc.Cursor)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;
|
||||
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;
|
||||
if(reply.ParagraphRevision>0)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<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
|
||||
public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List<ParagraphFragment> 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<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List<string> 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;}
|
||||
|
||||
@ -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");
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.17</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.18</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -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<Guid>();
|
||||
public ParagraphDeltaItem[] Changes {get;set;}=Array.Empty<ParagraphDeltaItem>();
|
||||
}
|
||||
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<ParagraphOccurrence> prior,IReadOnlyList<ParagraphOccurrence> 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<ParagraphDeltaItem>();
|
||||
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<ParagraphOccurrence> 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<Guid>(delta.Order);if(edits.Keys.Any(k=>!orderIds.Contains(k)))throw new ArgumentException("Delta has an orphan edit.");
|
||||
var result=new List<ParagraphOccurrence>();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();
|
||||
}
|
||||
}
|
||||
@ -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<ParagraphOccurrence>();
|
||||
public ParagraphOccurrence[] Removed {get;set;}=Array.Empty<ParagraphOccurrence>();
|
||||
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<ParagraphOccurrence> 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<ParagraphOccurrence> previous,IReadOnlyList<ParagraphOccurrence> 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<int>();var pairs=new Dictionary<int,int>();
|
||||
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<next.Length;i++)Match(i,i,"Unchanged sequence");}
|
||||
else{
|
||||
var oldNative=old.Select((p,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<old.Length&&y>=0&&y<next.Length&&old[x].Text==next[y].Text&&oldHashes[Fingerprint(old[x].Text)].Length==1&&newHashes[next[y].Fingerprint].Length==1;
|
||||
if(SameNeighbour(a-1,b-1)||SameNeighbour(a+1,b+1))Match(a,b,"Unique contextual pair");}
|
||||
// Exact text is only a candidate. A recognised neighbour must confirm the occurrence.
|
||||
for(var pass=0;pass<2;pass++)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;
|
||||
if((b>0&&a>0&&pairs.TryGetValue(b-1,out var left)&&left==a-1)||(b+1<next.Length&&a+1<old.Length&&pairs.TryGetValue(b+1,out var right)&&right==a+1))Match(a,b,"Fingerprint and neighbour");}
|
||||
// Duplicate native IDs/content (copy/paste): preserve only a single context-confirmed original.
|
||||
foreach(var entry in newHashes){if(!oldHashes.TryGetValue(entry.Key,out var prior))continue;
|
||||
var priorSet=new HashSet<int>(prior);var candidates=new Dictionary<int,List<int>>();
|
||||
foreach(var b in entry.Value.Where(b=>!pairs.ContainsKey(b))){var adjacent=new HashSet<int>();
|
||||
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<next.Length&&pairs.TryGetValue(b+1,out var right)&&priorSet.Contains(right-1)&&!used.Contains(right-1))adjacent.Add(right-1);
|
||||
if(adjacent.Count!=1)continue;var original=adjacent.Single();if(!candidates.TryGetValue(original,out var values))candidates[original]=values=new List<int>();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<next.Length;b++)if(next[b].Id==Guid.Empty&&pairs.TryGetValue(b-1,out var l)&&pairs.TryGetValue(b+1,out var r)&&r==l+2&&!used.Contains(l+1)&&!newHashes.ContainsKey(Fingerprint(old[l+1].Text)))Match(l+1,b,"Contextual rewrite; review");
|
||||
var copiedHashes=new HashSet<string>(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<int>();var tailEntries=new List<int>();var links=new int[matched.Length];
|
||||
for(int i=0;i<matched.Length;i++){int lo=0,hi=tails.Count;while(lo<hi){int m=(lo+hi)/2;if(tails[m]<matched[i].Value)lo=m+1;else hi=m;}links[i]=lo>0?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<int>();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<Guid>(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;i<next.Length;i++){
|
||||
var p=next[i];if(p.Id==Guid.Empty){var proposed=incoming[i].Id;p.Id=proposed!=Guid.Empty&&!oldIds.Contains(proposed)&&proposedCounts[proposed]==1?proposed:Guid.NewGuid();p.Change=p.Resolution=="Ambiguous"?"Ambiguous":"Inserted";}
|
||||
else{var prior=old[pairs[i]];p.PreviousText=prior.Text;p.WasMoved=!stable.Contains(i);p.Change=prior.Text!=p.Text?"Modified":p.WasMoved?"Moved":"Unchanged";}
|
||||
p.PreviousId=i>0?next[i-1].Id:(Guid?)null;
|
||||
}
|
||||
for(int i=0;i+1<next.Length;i++)next[i].NextId=next[i+1].Id;
|
||||
return new(){Current=next,Removed=old.Where((_,i)=>!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<ParagraphOccurrence>();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();
|
||||
}
|
||||
}
|
||||
@ -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;}
|
||||
|
||||
@ -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; }
|
||||
|
||||
@ -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;}
|
||||
|
||||
18
PlotDirector.NativeCompanion/Tests/ParagraphSnapshotTests.cs
Normal file
18
PlotDirector.NativeCompanion/Tests/ParagraphSnapshotTests.cs
Normal file
@ -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<bool,string> 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");
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
|
||||
@ -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)]
|
||||
|
||||
@ -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<string>();
|
||||
@ -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;}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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)});
|
||||
|
||||
21
PlotLine.Tests/Browser/paragraph-manuscript.cjs
Normal file
21
PlotLine.Tests/Browser/paragraph-manuscript.cjs
Normal file
@ -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)});
|
||||
@ -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<ChapterStructureModel>(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");
|
||||
|
||||
75
PlotLine.Tests/ParagraphManuscriptTests.cs
Normal file
75
PlotLine.Tests/ParagraphManuscriptTests.cs
Normal file
@ -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="<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml'><pkg:part pkg:name='/word/header1.xml'><w:p w14:paraId='00000011'/></pkg:part><pkg:part pkg:name='/word/document.xml'><w:p w14:paraId='00000022'/></pkg:part></pkg:package>";
|
||||
Check(WordParagraphIdentity.Read(xml)=="00000022"&&WordParagraphIdentity.Read("<!DOCTYPE a [<!ENTITY x SYSTEM 'file:///etc/passwd'>]><a>&x;</a>")=="","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<TimeSpan.FromSeconds(10),$"250,000+ word value snapshot reconciliation ({timer.ElapsedMilliseconds}ms; no Word COM performance claim)");
|
||||
Check(!JsonSerializer.Serialize(new CharacterKnowledgeItem()).Contains("EvidenceState")&&!JsonSerializer.Serialize(new RelationshipEvent()).Contains("EvidenceState"),"Derived evidence display state cannot change legacy backup hashes or accepted event payloads");
|
||||
var facts=StoryStateService.KnowledgeAtScene(new[]{new CharacterKnowledgeItem{CharacterKnowledgeID=1,CharacterID=2,SceneID=41,EvidenceState="Missing"},new CharacterKnowledgeItem{CharacterKnowledgeID=2,CharacterID=3,SceneID=41}},new Dictionary<int,int>{{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.");
|
||||
}
|
||||
}
|
||||
42
PlotLine.Tests/ParagraphViewTests.cs
Normal file
42
PlotLine.Tests/ParagraphViewTests.cs
Normal file
@ -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<IDataProtectionProvider>(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?"<script>unsafe()</script>\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<IRazorViewEngine>();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<ITempDataDictionaryFactory>().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<Microsoft.AspNetCore.Hosting.Server.IServer>();var address=server.Features.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()!.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("<script>unsafe()")||html.Contains("Saved narrative paragraph 101."))throw new Exception("Compiled review view lost scoped routes, antiforgery, typed identity, escaping or pagination");
|
||||
var path=Path.Combine(Path.GetTempPath(),"pd-paragraph-review-fixture.html");await File.WriteAllTextAsync(path,html);
|
||||
Console.WriteLine("PASS actual compiled Razor workspace: scoped form routes, antiforgery, typed event choice, encoded prose and bounded pagination (synthetic fixture only)");
|
||||
}finally{await app.StopAsync();}
|
||||
}
|
||||
}
|
||||
53
PlotLine.Tests/ParagraphWorkflowTests.cs
Normal file
53
PlotLine.Tests/ParagraphWorkflowTests.cs
Normal file
@ -0,0 +1,53 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
internal static class ParagraphWorkflowTests
|
||||
{
|
||||
private sealed class Memory: IParagraphManuscriptRepository
|
||||
{
|
||||
public ParagraphManuscript State=null!;public bool Empty;public bool Paused;public int Writes;
|
||||
public Task<ParagraphManuscript?> Get(int user,int book)=>Task.FromResult<ParagraphManuscript?>(Empty?null:ParagraphManuscriptEngine.Clone(State));
|
||||
public Task<ParagraphManuscript> SetMode(int user,int book,long expected,string mode){if(user!=7||expected!=State.Revision)throw new InvalidOperationException();State.Mode=mode;State.Revision++;return Task.FromResult(ParagraphManuscriptEngine.Clone(State));}
|
||||
public Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request){if(user!=7)throw new UnauthorizedAccessException();if(expected!=(Empty?-1:State.Revision))throw new InvalidOperationException("Revision conflict");state.Revision=Empty?1:state.Revision+1;Empty=false;state.LastRequestId=request;State=ParagraphManuscriptEngine.Clone(state);Writes++;return Task.FromResult(state);}
|
||||
public Task<ParagraphSyncStatus?> Status(int user,int book)=>Task.FromResult<ParagraphSyncStatus?>(new(){BookId=book,CanWrite=user==7,Paused=Paused,Mode=State.Mode,SessionId=State.SessionId,WordRevision=State.WordRevision,Revision=State.Revision,ManuscriptId=State.ManuscriptId,SnapshotHash=State.SnapshotHash});
|
||||
public Task<IReadOnlyList<ManuscriptEventOption>> Events(int user,int book)=>Task.FromResult<IReadOnlyList<ManuscriptEventOption>>([]);
|
||||
public Task<ManuscriptScanPreview?> Capture(int user,int book)=>Task.FromResult<ManuscriptScanPreview?>(null);
|
||||
public Task<ParagraphPosition?> Position(int user,int book,Guid manuscript,Guid session,long revision,int position)=>Task.FromResult<ParagraphPosition?>(null);
|
||||
}
|
||||
public static async Task Run()
|
||||
{
|
||||
void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
var manuscript=Guid.NewGuid();var rows=ParagraphReconciliation.Compare([],new[]{new ParagraphOccurrence{Text="The keeper waited.\r",NativeId="00000001",Start=0,End=19}}).Current;
|
||||
var memory=new Memory{State=ParagraphManuscriptEngine.Bootstrap(3,1,manuscript,rows,[new(){SceneId=11,ChapterId=4,Title="Waiting",Start=1,End=1}])};memory.State.Mode="OnSave";memory.State.Revision=1;
|
||||
var access=NativeWorkflowTests.Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=3}));
|
||||
var statistics=NativeWorkflowTests.Proxy<IManuscriptTextStatisticsService>((_,_)=>Task.CompletedTask);
|
||||
var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"Features:ParagraphManuscripts","true"}}).Build();
|
||||
using var services=new ServiceCollection().AddSingleton<IParagraphManuscriptRepository>(memory).AddSingleton(access).AddSingleton<IConfiguration>(configuration).AddSingleton(new ParagraphManuscriptService(memory,access,null!,null!,statistics,configuration)).BuildServiceProvider();
|
||||
var adoption=new Memory{State=new(){BookId=3},Empty=true};
|
||||
var build=NativeWorkflowTests.Proxy<IOnboardingBuildRepository>((n,a)=>n=="GetByPreviewAsync"?Task.FromResult<OnboardingManuscriptBuildResult?>(new(){BookID=3,ProjectID=1,SceneMappings=[new(){SceneID=11},new(){SceneID=12}]}):throw new Exception(n));
|
||||
int offset=0;var fragments=new[]{"Arrival\r","Opening prose.\r","Private section\r","Explicitly excluded prose.\r","Departure\r","Ending prose.\r"}.Select((text,i)=>{var f=new ParagraphFragment{ParagraphIndex=i+1,Start=offset,End=offset+text.Length,Text=text,OutlineLevel=i%2==0?1:10,CompletesParagraph=true,NativeParagraphId=(i+1).ToString("X8")};offset=f.End;return f;}).ToArray();
|
||||
var preview=NativeManuscriptCapture.Build(new(){ManuscriptId=manuscript,RequestId=Guid.NewGuid(),ParagraphTracking=true,End=offset,Paragraphs=fragments},7,4,1,3,"Synthetic selective import");
|
||||
var adopted=await new ParagraphManuscriptService(adoption,access,null!,build,statistics,configuration).Initialise(7,preview,[new(){SceneID=11,ChapterID=4,WordStartParagraphIndex=2},new(){SceneID=99,ChapterID=99,WordStartParagraphIndex=4},new(){SceneID=12,ChapterID=5,WordStartParagraphIndex=6}],1);
|
||||
Check(adopted.Scenes.Count==2&&adopted.Paragraphs.Count==6&&adopted.Paragraphs.Count(p=>p.Story)==2&&adopted.Chapters.Any(c=>c.CanonicalId==0),"Adoption uses only the completed capture's canonical scene map and retains excluded prose outside the imported book");
|
||||
ParagraphManuscriptEngine.Reconcile(adopted,adopted.Paragraphs.Select(p=>p.Occurrence).ToArray());Check(!adopted.Paragraphs[3].Story,"Reconnection cannot silently restore an excluded chapter into canonical scenes");
|
||||
var presence=new NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid();
|
||||
var input=new NativePresence{CanCapture=true,CanParagraphSync=true,WordSaved=true,BookId=3,ManuscriptId=manuscript,Revision=2,Sequence=1,Active=true,DocumentTitle="Synthetic novel"};presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,input);
|
||||
var capture=new NativeManuscriptCapture(presence,null!,TimeProvider.System,services.GetRequiredService<IServiceScopeFactory>(),configuration);
|
||||
memory.Paused=true;bool refused=false;try{await capture.RequestParagraphSnapshot(7,3);}catch(InvalidOperationException){refused=true;}Check(refused&&memory.Writes==0,"An unfinished import pauses snapshots without changing its accepted source or checkpoints");memory.Paused=false;
|
||||
await capture.ObserveParagraphSave(7,presence.Read(7,3).Single());var command=presence.TakeNavigation(7,"grant",instance,session)!;Check(command.Kind=="paragraph-snapshot"&&command.BaseRevision==1,"Explicitly opted-in save/reconnect uses existing exact-session capture channel");
|
||||
var body=new ManuscriptCapture{RequestId=command.Id,InstanceId=instance,SessionId=session,ManuscriptId=manuscript,Revision=2,ParagraphTracking=true,End=19,Paragraphs=[new(){ParagraphIndex=1,Start=0,End=19,Text="The keeper smiled.\r",CompletesParagraph=true,NativeParagraphId="00000001"}]};
|
||||
Check(await capture.AcceptParagraphSnapshot(7,"grant",body)&&memory.Writes==1&&memory.State.Paragraphs[0].Occurrence.Id==rows[0].Id&&memory.State.Paragraphs[0].Occurrence.Text.Contains("smiled"),"Authorised snapshot persists exact new prose and reconciles opaque paragraph identity");
|
||||
await capture.AcceptParagraphSnapshot(7,"grant",body);Check(memory.Writes==1,"Lost acknowledgement retry cannot apply the snapshot twice");
|
||||
Check((await capture.AcceptedParagraphState(7,body.RequestId)).Paragraphs.Single().Occurrence.Id==rows[0].Id,"Acknowledgement returns canonical occurrence ID for delta recovery");
|
||||
var id=await capture.RequestParagraphSnapshot(7,3);await capture.CancelParagraphSnapshot(7,3);Check(presence.TakeNavigation(7,"grant",instance,session)?.Kind=="cancel"&&memory.Writes==1,"Cancellation retires only pending snapshot and retains already accepted revision");
|
||||
bool foreign=false;try{await capture.RequestParagraphSnapshot(8,3);}catch(UnauthorizedAccessException){foreign=true;}Check(foreign&&memory.Writes==1,"Another account cannot request manuscript synchronisation");
|
||||
memory.Paused=true;await services.GetRequiredService<ParagraphManuscriptService>().Enable(7,3,"Off");Check(memory.State.Mode=="Off"&&memory.Writes==1,"Turning off automatic synchronisation changes only preferences even while imports or scene conflicts pause snapshots");
|
||||
}
|
||||
}
|
||||
@ -126,6 +126,8 @@ if(args.Contains("--intent-assessment")){await IntentAssessmentTests.Run();Conso
|
||||
if(args.Contains("--release-sprint")){ReleaseSprintTests.Run();Console.WriteLine("PASS continuity triage and public onboarding/installer guidance");return;}
|
||||
if(args.Contains("--native-import")){await NativeImportTests.Run();Console.WriteLine("PASS approved native import preview, source preservation, ownership, version and retry");return;}
|
||||
if(args.Contains("--native-installation")){await NativeInstallationTests.Run();Console.WriteLine("PASS trusted installation access, renewal, process replacement, account isolation and revocation");return;}
|
||||
if(args.Contains("--paragraph-view")){await ParagraphViewTests.Run();return;}
|
||||
if(args.Contains("--paragraph-manuscripts")){ParagraphManuscriptTests.Run();await ParagraphWorkflowTests.Run();return;}
|
||||
if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTests.Run();return;}
|
||||
if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;}
|
||||
if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;}
|
||||
@ -139,6 +141,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
|
||||
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
|
||||
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
|
||||
("Paragraph manuscript identity, evidence and exact-session synchronisation", () => { ParagraphManuscriptTests.Run();ParagraphWorkflowTests.Run().GetAwaiter().GetResult(); }),
|
||||
("Native wizard capture is scoped, durable and independent of Word", () => NativeManuscriptCaptureTests.Run().GetAwaiter().GetResult()),
|
||||
("Native tray presence and PWA review remain scoped, expiring and non-destructive", () => NativeTrayIntegrationTests.Run().GetAwaiter().GetResult()),
|
||||
("Native saved workspace and established import eligibility remain scoped and read-only", () => NativeWorkflowTests.Run().GetAwaiter().GetResult()),
|
||||
|
||||
72
PlotLine.Tests/Sql/ParagraphManuscripts.sql
Normal file
72
PlotLine.Tests/Sql/ParagraphManuscripts.sql
Normal file
@ -0,0 +1,72 @@
|
||||
-- Disposable synthetic database only. New author/book fixture is always rolled back.
|
||||
IF DB_NAME()<>N'PlotDirector_Phase2_20261103_2305' OR NOT EXISTS(SELECT 1 FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true') THROW 51000,'Guarded synthetic target required',1;
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Level int,@User int,@Other int,@Project int,@Book int,@Preview uniqueidentifier=NEWID();
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@capture.invalid',N'Capture fixture',N'not-a-credential');SET @User=SCOPE_IDENTITY();
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@capture.invalid',N'Other capture fixture',N'not-a-credential');SET @Other=SCOPE_IDENTITY();
|
||||
INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),N'Capture fixture',2,100,100,100,100,0,0,0);SET @Level=SCOPE_IDENTITY();
|
||||
INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@User,@Level,1,1,'2030-01-01');
|
||||
INSERT dbo.Projects(ProjectName) VALUES(N'Native capture fixture');SET @Project=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@Project,@User,N'Owner',1);
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Native capture fixture',1,1);SET @Book=SCOPE_IDENTITY();
|
||||
DECLARE @Chapter int,@Scene int,@Character int,@Knowledge int,@Manuscript uniqueidentifier=NEWID(),@SceneKey uniqueidentifier=NEWID(),@Paragraph uniqueidentifier=NEWID(),@Evidence uniqueidentifier=NEWID(),@Request uniqueidentifier=NEWID();
|
||||
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) SELECT @Book,1,N'Arrival',1,MIN(RevisionStatusID) FROM dbo.RevisionStatuses;SET @Chapter=SCOPE_IDENTITY();
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) SELECT @Chapter,1,N'The letter',1,(SELECT MIN(TimeModeID) FROM dbo.TimeModes),(SELECT MIN(TimeConfidenceID) FROM dbo.TimeConfidences),(SELECT MIN(RevisionStatusID) FROM dbo.RevisionStatuses);SET @Scene=SCOPE_IDENTITY();
|
||||
INSERT dbo.Characters(ProjectID,CharacterName) VALUES(@Project,N'Mira');SET @Character=SCOPE_IDENTITY();
|
||||
INSERT dbo.CharacterKnowledge(CharacterID,SceneID,KnowledgeStateID,Description) SELECT @Character,@Scene,MIN(KnowledgeStateID),N'Understands the letter' FROM dbo.KnowledgeStates;SET @Knowledge=SCOPE_IDENTITY();
|
||||
DECLARE @Payload nvarchar(max)=(SELECT 1 Version,@Book BookId,@Project ProjectId,@Manuscript ManuscriptId,N'Manual' Mode,NEWID() SessionId,3 WordRevision,N'synthetic-hash' SnapshotHash,
|
||||
JSON_QUERY((SELECT @SceneKey Id,@Scene CanonicalId,@Chapter ChapterId,N'The letter' Title,CAST(0 AS bit) Retired FOR JSON PATH)) Scenes,
|
||||
JSON_QUERY((SELECT JSON_QUERY((SELECT @Paragraph Id,0 Ordinal,N'The keeper handed Mira the letter.'+CHAR(13) Text,0 Start,34 [End],10 Outline FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) Occurrence,@SceneKey SceneId,@Chapter ChapterId,CAST(1 AS bit) Story,CAST(1 AS bit) PositionVerified FOR JSON PATH)) Paragraphs,
|
||||
JSON_QUERY((SELECT @Evidence Id,N'Knowledge' EventKind,@Knowledge EventId,CAST(1 AS bit) [Primary],N'Verified' State,@Paragraph StartParagraph,@Paragraph EndParagraph,@SceneKey CurrentScene FOR JSON PATH)) Evidence,
|
||||
JSON_QUERY((SELECT N'Knowledge' Kind,@Knowledge Id,@Scene SceneId FOR JSON PATH)) EventPositions FOR JSON PATH,WITHOUT_ARRAY_WRAPPER);
|
||||
CREATE TABLE #State(Payload nvarchar(max));
|
||||
INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=-1,@RequestID=@Request,@Payload=@Payload;
|
||||
IF (SELECT Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>1 THROW 51000,'Initial revision not committed',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE SceneID=@Scene AND SourceText=N'The keeper handed Mira the letter.'+CHAR(13)) THROW 51000,'Raw scene prose did not roundtrip',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex WHERE BookID=@Book AND EventID=@Knowledge AND EvidenceState=N'Verified') THROW 51000,'Evidence not indexed',1;
|
||||
TRUNCATE TABLE #State;
|
||||
INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=-1,@RequestID=@Request,@Payload=@Payload;
|
||||
IF (SELECT Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>1 THROW 51000,'Duplicate request changed revision',1;
|
||||
SET @Payload=JSON_MODIFY(@Payload,'$.Evidence[0].State',N'Missing');SET @Request=NEWID();
|
||||
TRUNCATE TABLE #State;
|
||||
INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=1,@RequestID=@Request,@Payload=@Payload;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge WHERE CharacterKnowledgeID=@Knowledge) OR NOT EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex WHERE EventID=@Knowledge AND EvidenceState=N'Missing' AND DerivedSceneID IS NULL) THROW 51000,'Missing evidence destroyed event or remained verified',1;
|
||||
DECLARE @Session uniqueidentifier=CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.SessionId'));
|
||||
CREATE TABLE #Position(HasSnapshot bit,Revision bigint,ChapterID int NULL,SceneID int NULL);
|
||||
INSERT #Position EXEC dbo.ParagraphManuscript @Action='position',@UserID=@User,@BookID=@Book,@ManuscriptID=@Manuscript,@SessionID=@Session,@WordRevision=3,@Position=5;
|
||||
IF NOT EXISTS(SELECT 1 FROM #Position WHERE SceneID=@Scene) THROW 51000,'Verified cursor mapping failed',1;
|
||||
TRUNCATE TABLE #Position;
|
||||
INSERT #Position EXEC dbo.ParagraphManuscript @Action='position',@UserID=@User,@BookID=@Book,@ManuscriptID=@Manuscript,@SessionID=@Session,@WordRevision=4,@Position=5;
|
||||
IF EXISTS(SELECT 1 FROM #Position WHERE SceneID IS NOT NULL) THROW 51000,'Stale cursor position was accepted',1;
|
||||
PRINT 'PASS exact prose, typed evidence, CAS revision, idempotent acknowledgement and missing-evidence event preservation';
|
||||
-- Split a canonical scene through the same transactional save.
|
||||
SET @Payload=(SELECT Payload FROM #State);DECLARE @NewScene uniqueidentifier=NEWID();
|
||||
SET @Payload=JSON_MODIFY(@Payload,'append $.Scenes',JSON_QUERY((SELECT @NewScene Id,0 CanonicalId,@Chapter ChapterId,N'Second scene' Title,CAST(0 AS bit) Retired FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)));
|
||||
SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs[0].SceneId',CONVERT(nvarchar(36),@NewScene));SET @Request=NEWID();TRUNCATE TABLE #State;
|
||||
INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=2,@RequestID=@Request,@Payload=@Payload;
|
||||
IF (SELECT COUNT(*) FROM dbo.Scenes WHERE ChapterID=@Chapter)<>2 THROW 51000,'Split did not materialise canonical scene',1;
|
||||
SET @Payload=(SELECT Payload FROM #State);SET @Payload=JSON_MODIFY(@Payload,'$.Evidence[0].State',N'Verified');SET @Payload=JSON_MODIFY(@Payload,'$.Evidence[0].CurrentScene',CONVERT(nvarchar(36),@NewScene));SET @Request=NEWID();TRUNCATE TABLE #State;
|
||||
INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=3,@RequestID=@Request,@Payload=@Payload;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID WHERE k.CharacterKnowledgeID=@Knowledge AND s.SceneTitle=N'Second scene') THROW 51000,'Verified primary evidence did not update canonical event scene',1;
|
||||
PRINT 'PASS split canonical identity allocation, exact source projection and verified event movement';
|
||||
SET @Payload=(SELECT Payload FROM #State);SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs[0].PositionVerified',CAST(0 AS bit));SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs[0].Occurrence.Text',N'Uncertain proposed prose'+CHAR(13));SET @Payload=JSON_MODIFY(@Payload,'$.Evidence[0].State',N'Needs review');SET @Request=NEWID();TRUNCATE TABLE #State;
|
||||
INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=4,@RequestID=@Request,@Payload=@Payload;
|
||||
IF NOT EXISTS(SELECT 1 FROM #State WHERE JSON_VALUE(Payload,'$.Paragraphs[0].Occurrence.Text')=N'Uncertain proposed prose'+CHAR(13)) OR EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE BookID=@Book AND SourceText=N'Uncertain proposed prose'+CHAR(13)) THROW 51000,'Uncertain grouping replaced accepted canonical prose or lost the raw snapshot',1;
|
||||
PRINT 'PASS uncertain scene grouping retains raw Word snapshot without overwriting canonical prose';
|
||||
TRUNCATE TABLE #State;INSERT #State EXEC dbo.ParagraphManuscript @Action='mode',@UserID=@User,@BookID=@Book,@ExpectedRevision=5,@Mode=N'Off';
|
||||
IF JSON_VALUE((SELECT Payload FROM #State),'$.Mode')<>N'Off' THROW 51000,'Preference mode was not persisted',1;
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) SELECT @Chapter,10,N'Unmapped author planning',10,TimeModeID,TimeConfidenceID,RevisionStatusID FROM dbo.Scenes WHERE SceneID=@Scene;
|
||||
DECLARE @Denied bit=0;SET @Request=NEWID();SET @Payload=(SELECT Payload FROM #State);
|
||||
BEGIN TRY EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=6,@RequestID=@Request,@Payload=@Payload;END TRY BEGIN CATCH IF ERROR_MESSAGE() LIKE 'This chapter contains a scene outside%' SET @Denied=1;END CATCH;
|
||||
IF @Denied=0 OR (SELECT Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>6 THROW 51000,'An unmapped author scene was silently reordered',1;
|
||||
PRINT 'PASS unmapped canonical author scene causes refusal without snapshot mutation';
|
||||
SET @Denied=0;
|
||||
BEGIN TRY EXEC dbo.ProjectRecovery_State @ProjectID=@Project;END TRY BEGIN CATCH IF ERROR_MESSAGE() LIKE 'Paragraph manuscript recovery%' SET @Denied=1;END CATCH;
|
||||
IF @Denied=0 THROW 51000,'Legacy backup silently omitted new author evidence',1;
|
||||
PRINT 'PASS legacy backup refuses silent omission of paragraph evidence';
|
||||
SET @Denied=0;
|
||||
BEGIN TRY EXEC dbo.ParagraphManuscript @Action='get',@UserID=@Other,@BookID=@Book;END TRY BEGIN CATCH IF ERROR_MESSAGE()='Book access denied' SET @Denied=1;END CATCH;
|
||||
IF @Denied=0 THROW 51000,'Cross-account manuscript leak',1;
|
||||
IF @@TRANCOUNT>0 ROLLBACK;
|
||||
PRINT 'PASS cross-account refusal; every synthetic fixture rolled back';
|
||||
@ -15,7 +15,13 @@ public sealed class NativeManuscriptCaptureController(NativeManuscriptCapture ca
|
||||
public async Task<IActionResult> Accept(ManuscriptCapture input)
|
||||
{
|
||||
var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
try{var state=await capture.Accept(user,User.FindFirstValue("NativeCompanion.Grant")??"",input);await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanCompleted",state);return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision});}
|
||||
try{var grant=User.FindFirstValue("NativeCompanion.Grant")??"";
|
||||
if(await capture.AcceptParagraphSnapshot(user,grant,input)){
|
||||
var state=await capture.AcceptedParagraphState(user,input.RequestId);
|
||||
await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("ParagraphSnapshotAccepted",new{bookId=state.BookId,revision=state.Revision});
|
||||
return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision,ParagraphRevision=state.Revision,ParagraphSnapshotHash=state.SnapshotHash,CanonicalParagraphIds=state.Paragraphs.Select(p=>p.Occurrence.Id).ToArray()});
|
||||
}
|
||||
var stateImport=await capture.Accept(user,User.FindFirstValue("NativeCompanion.Grant")??"",input);await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanCompleted",stateImport);return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision,CanonicalParagraphIds=capture.AcceptedParagraphIds(user,input.RequestId)});}
|
||||
catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(InvalidOperationException){return Conflict(new{message="The import wizard changed. Refresh it before retrying the transfer."});}
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,8 +22,10 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
if(book==null){input.ChapterId=null;input.SceneId=null;}
|
||||
if(input.CursorStart is <0)return BadRequest("Invalid cursor position.");
|
||||
if(input.CanCapture&&input.WordSaved!=true){input.ChapterId=null;input.SceneId=null;}
|
||||
if(book!=null&&input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;}
|
||||
if(book!=null&&input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}
|
||||
var paragraphPosition=book!=null&&input.CanParagraphSync&&input.CursorStart.HasValue&&capture!=null?await capture.ResolveParagraphPosition(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value):null;
|
||||
if(paragraphPosition!=null){input.ParagraphRevision=paragraphPosition.Revision;input.ChapterId=input.WordSaved==true?paragraphPosition.ChapterID:null;input.SceneId=input.WordSaved==true?paragraphPosition.SceneID:null;}
|
||||
if(paragraphPosition==null&&book!=null&&input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;}
|
||||
if(paragraphPosition==null&&book!=null&&input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}
|
||||
var chapter=input.ChapterId.HasValue?book!.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null;
|
||||
if(input.SceneId.HasValue){var parent=book!.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent)){input.SceneId=null;input.ChapterId=null;chapter=null;}else{chapter=parent;input.ChapterId=parent.ChapterId;}}
|
||||
if(input.ChapterId.HasValue&&chapter==null){input.ChapterId=null;input.SceneId=null;}
|
||||
@ -31,6 +33,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
|
||||
if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
|
||||
if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);}
|
||||
if(input.CanParagraphSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);}
|
||||
input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input);
|
||||
}
|
||||
[HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")]
|
||||
|
||||
37
PlotLine/Controllers/ParagraphManuscriptController.cs
Normal file
37
PlotLine/Controllers/ParagraphManuscriptController.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Controllers;
|
||||
[Authorize,Route("manuscript/paragraphs")]
|
||||
public sealed class ParagraphManuscriptController(ParagraphManuscriptService manuscripts,NativeManuscriptCapture capture,NativePresenceStore presence):Controller
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(int bookId,int page=1,int evidencePage=1)
|
||||
{
|
||||
if(!manuscripts.Enabled)return NotFound();
|
||||
try{var model=await manuscripts.Workspace(Author,bookId,page);model.EvidencePage=Math.Max(1,evidencePage);model.Message=TempData["ParagraphMessage"] as string;return View(model);}catch(UnauthorizedAccessException){return Forbid();}
|
||||
}
|
||||
[HttpPost("enable"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Enable(int bookId,string mode)=>Run(bookId,async()=>{await manuscripts.Enable(Author,bookId,mode);return "Paragraph tracking preference saved. Word prose is never rewritten by PlotDirector.";});
|
||||
[HttpPost("snapshot"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Snapshot(int bookId)=>Run(bookId,async()=>{var id=await capture.RequestParagraphSnapshot(Author,bookId);return id==Guid.Empty?"A transfer is already pending. Refresh after it finishes.":"Word snapshot requested. Keep Word open until the transfer is acknowledged, then refresh this page.";});
|
||||
[HttpPost("cancel"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Cancel(int bookId)=>Run(bookId,async()=>{await capture.CancelParagraphSnapshot(Author,bookId);return "Pending snapshot cancelled. Already acknowledged snapshots remain saved.";});
|
||||
[HttpPost("change"),ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Change(int bookId,long revision,string action,Guid target,Guid other,string? text,string? eventKey,bool primary,int from,int to,int? startOffset,int? endOffset)=>Run(bookId,async()=>{
|
||||
string? kind=null;int eventId=0;if(action=="anchor"){var pieces=eventKey?.Split(':');if(pieces?.Length!=2||pieces[0] is not ("Knowledge" or "Relationship")||!int.TryParse(pieces[1],out eventId))throw new ArgumentException("Choose a saved knowledge or relationship event.");kind=pieces[0];}
|
||||
await manuscripts.Change(Author,bookId,revision,action,target,other,text,kind,eventId,primary,from-1,to-1,startOffset,endOffset);presence.BooksChanged(Author);return "Manuscript structure and evidence updated. Word prose is unchanged.";});
|
||||
private async Task<IActionResult> Run(int book,Func<Task<string>> work)
|
||||
{
|
||||
if(!manuscripts.Enabled)return NotFound();
|
||||
try{TempData["ParagraphMessage"]=await work();}catch(UnauthorizedAccessException){return Forbid();}
|
||||
catch(Exception e)when(e is ArgumentException or InvalidOperationException){TempData["ParagraphMessage"]=e.Message;}
|
||||
catch(SqlException e)when(e.Number==51000){TempData["ParagraphMessage"]=e.Message;}
|
||||
catch(SqlException){TempData["ParagraphMessage"]="The change was refused. Check your owner permissions, finish any active import, then refresh before retrying.";}
|
||||
return RedirectToAction(nameof(Index),new{bookId=book});
|
||||
}
|
||||
}
|
||||
18
PlotLine/Data/ParagraphEvidenceProjection.cs
Normal file
18
PlotLine/Data/ParagraphEvidenceProjection.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Data;
|
||||
internal static class ParagraphEvidenceProjection
|
||||
{
|
||||
private sealed class State { public int EventID {get;set;} public string EvidenceState {get;set;}="Verified"; }
|
||||
private static async Task<Dictionary<int,string>> States(IDbConnection db,IConfiguration? configuration,string kind,IEnumerable<int> ids)
|
||||
{
|
||||
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)return [];
|
||||
var values=ids.Distinct().ToArray();if(values.Length==0)return [];
|
||||
var rows=await db.QueryAsync<State>("dbo.ParagraphEvidence_States",new{EventKind=kind,EventIDs=JsonSerializer.Serialize(values)},commandType:CommandType.StoredProcedure);
|
||||
return rows.ToDictionary(p=>p.EventID,p=>p.EvidenceState);
|
||||
}
|
||||
public static async Task<List<CharacterKnowledgeItem>> Apply(IDbConnection db,IConfiguration? configuration,IEnumerable<CharacterKnowledgeItem> items){var rows=items.ToList();var states=await States(db,configuration,"Knowledge",rows.Select(p=>p.CharacterKnowledgeID));foreach(var row in rows)row.EvidenceState=states.GetValueOrDefault(row.CharacterKnowledgeID,"Verified");return rows;}
|
||||
public static async Task<List<RelationshipEvent>> Apply(IDbConnection db,IConfiguration? configuration,IEnumerable<RelationshipEvent> items){var rows=items.ToList();var states=await States(db,configuration,"Relationship",rows.Select(p=>p.RelationshipEventID));foreach(var row in rows)row.EvidenceState=states.GetValueOrDefault(row.RelationshipEventID,"Verified");return rows;}
|
||||
}
|
||||
25
PlotLine/Data/ParagraphManuscriptRepository.cs
Normal file
25
PlotLine/Data/ParagraphManuscriptRepository.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Data;
|
||||
public interface IParagraphManuscriptRepository
|
||||
{
|
||||
Task<ParagraphPosition?> Position(int user,int book,Guid manuscript,Guid session,long revision,int position);
|
||||
Task<ParagraphManuscript?> Get(int user,int book);
|
||||
Task<ParagraphManuscript> SetMode(int user,int book,long expected,string mode);
|
||||
Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request);
|
||||
Task<ManuscriptScanPreview?> Capture(int user,int book);
|
||||
Task<ParagraphSyncStatus?> Status(int user,int book);
|
||||
Task<IReadOnlyList<ManuscriptEventOption>> Events(int user,int book);
|
||||
}
|
||||
public sealed class ParagraphManuscriptRepository(ISqlConnectionFactory factory):IParagraphManuscriptRepository
|
||||
{
|
||||
public async Task<ParagraphPosition?> Position(int user,int book,Guid manuscript,Guid session,long revision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<ParagraphPosition>("dbo.ParagraphManuscript",new{Action="position",UserID=user,BookID=book,ManuscriptID=manuscript,SessionID=session,WordRevision=revision,Position=position},commandType:CommandType.StoredProcedure);}
|
||||
public async Task<ParagraphManuscript?> Get(int user,int book){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.ParagraphManuscript",new{Action="get",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);return json==null?null:JsonSerializer.Deserialize<ParagraphManuscript>(json);}
|
||||
public async Task<ParagraphManuscript> SetMode(int user,int book,long expected,string mode){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="mode",UserID=user,BookID=book,ExpectedRevision=expected,Mode=mode},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
|
||||
public async Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="save",UserID=user,BookID=state.BookId,ExpectedRevision=expected,RequestID=request,Payload=JsonSerializer.Serialize(state)},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
|
||||
public async Task<ManuscriptScanPreview?> Capture(int user,int book){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.ParagraphManuscript",new{Action="capture",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);return json==null?null:JsonSerializer.Deserialize<ManuscriptScanPreview>(json);}
|
||||
public async Task<ParagraphSyncStatus?> Status(int user,int book){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<ParagraphSyncStatus>("dbo.ParagraphManuscript",new{Action="status",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);}
|
||||
public async Task<IReadOnlyList<ManuscriptEventOption>> Events(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync<ManuscriptEventOption>("dbo.ParagraphManuscript",new{Action="events",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToList();}
|
||||
}
|
||||
@ -1760,18 +1760,14 @@ public sealed class ExportRepository(ISqlConnectionFactory connectionFactory) :
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DynamicsRepository(ISqlConnectionFactory connectionFactory) : IDynamicsRepository
|
||||
public sealed class DynamicsRepository(ISqlConnectionFactory connectionFactory,IConfiguration? paragraphConfiguration=null) : IDynamicsRepository
|
||||
{
|
||||
public async Task<(Character? Character, IReadOnlyList<CharacterArcPoint> ArcPoints, IReadOnlyList<RelationshipEvent> RelationshipEvents, IReadOnlyList<CharacterKnowledgeItem> KnowledgeEvents, IReadOnlyList<DynamicsIssue> Issues)> GetCharacterArcAsync(int characterId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
using var result = await connection.QueryMultipleAsync("dbo.Dynamics_CharacterArc", new { CharacterID = characterId }, commandType: CommandType.StoredProcedure);
|
||||
return (
|
||||
await result.ReadSingleOrDefaultAsync<Character>(),
|
||||
(await result.ReadAsync<CharacterArcPoint>()).ToList(),
|
||||
(await result.ReadAsync<RelationshipEvent>()).ToList(),
|
||||
(await result.ReadAsync<CharacterKnowledgeItem>()).ToList(),
|
||||
(await result.ReadAsync<DynamicsIssue>()).ToList());
|
||||
var character=await result.ReadSingleOrDefaultAsync<Character>();var arc=(await result.ReadAsync<CharacterArcPoint>()).ToList();var relationships=(await result.ReadAsync<RelationshipEvent>()).ToList();var knowledge=(await result.ReadAsync<CharacterKnowledgeItem>()).ToList();var issues=(await result.ReadAsync<DynamicsIssue>()).ToList();
|
||||
return (character,arc,await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,relationships),await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,knowledge),issues);
|
||||
}
|
||||
|
||||
public async Task<(CharacterRelationship? Relationship, IReadOnlyList<RelationshipProgressionPoint> Events, IReadOnlyList<DynamicsIssue> Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId)
|
||||
@ -1788,10 +1784,8 @@ public sealed class DynamicsRepository(ISqlConnectionFactory connectionFactory)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
using var result = await connection.QueryMultipleAsync("dbo.Dynamics_KnowledgeTimeline", new { CharacterID = characterId }, commandType: CommandType.StoredProcedure);
|
||||
return (
|
||||
await result.ReadSingleOrDefaultAsync<Character>(),
|
||||
(await result.ReadAsync<CharacterKnowledgeItem>()).ToList(),
|
||||
(await result.ReadAsync<DynamicsIssue>()).ToList());
|
||||
var character=await result.ReadSingleOrDefaultAsync<Character>();var knowledge=(await result.ReadAsync<CharacterKnowledgeItem>()).ToList();var issues=(await result.ReadAsync<DynamicsIssue>()).ToList();
|
||||
return (character,await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,knowledge),issues);
|
||||
}
|
||||
|
||||
public async Task<(IReadOnlyList<CharacterPairingSummary> Pairings, IReadOnlyList<DynamicsIssue> Issues)> GetStoryDynamicsAsync(int projectId)
|
||||
@ -3713,7 +3707,7 @@ public sealed class AssetRepository(ISqlConnectionFactory connectionFactory) : I
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory) : ICharacterRepository
|
||||
public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory,IConfiguration? paragraphConfiguration=null) : ICharacterRepository
|
||||
{
|
||||
public async Task<CharacterLookupData> GetLookupsAsync(int? projectId = null)
|
||||
{
|
||||
@ -4051,14 +4045,14 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
var rows = await connection.QueryAsync<CharacterKnowledgeItem>("dbo.CharacterKnowledge_ListByScene", new { SceneID = sceneId }, commandType: CommandType.StoredProcedure);
|
||||
return rows.ToList();
|
||||
return await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,rows);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<CharacterKnowledgeItem>> ListKnowledgeByCharacterAsync(int characterId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
var rows = await connection.QueryAsync<CharacterKnowledgeItem>("dbo.CharacterKnowledge_ListByCharacter", new { CharacterID = characterId }, commandType: CommandType.StoredProcedure);
|
||||
return rows.ToList();
|
||||
return await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,rows);
|
||||
}
|
||||
|
||||
public async Task<int> SaveKnowledgeAsync(CharacterKnowledgeItem knowledge)
|
||||
@ -4161,14 +4155,14 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
var rows = await connection.QueryAsync<RelationshipEvent>("dbo.RelationshipEvent_ListByScene", new { SceneID = sceneId }, commandType: CommandType.StoredProcedure);
|
||||
return rows.ToList();
|
||||
return await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,rows);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<RelationshipEvent>> ListRelationshipEventsByCharacterAsync(int characterId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
var rows = await connection.QueryAsync<RelationshipEvent>("dbo.RelationshipEvent_ListByCharacter", new { CharacterID = characterId }, commandType: CommandType.StoredProcedure);
|
||||
return rows.ToList();
|
||||
return await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,rows);
|
||||
}
|
||||
|
||||
public async Task<int> SaveRelationshipEventAsync(RelationshipEvent relationshipEvent)
|
||||
@ -4208,7 +4202,7 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
using var result = await connection.QueryMultipleAsync("dbo.RelationshipMap_GetByProject", new { ProjectID = projectId }, commandType: CommandType.StoredProcedure);
|
||||
return new RelationshipMapData
|
||||
var data=new RelationshipMapData
|
||||
{
|
||||
Characters = (await result.ReadAsync<Character>()).ToList(),
|
||||
Books = (await result.ReadAsync<Book>()).ToList(),
|
||||
@ -4218,5 +4212,7 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory)
|
||||
RelationshipEvents = (await result.ReadAsync<RelationshipEvent>()).ToList(),
|
||||
RelationshipCategories = (await result.ReadAsync<RelationshipCategory>()).ToList()
|
||||
};
|
||||
await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,data.RelationshipEvents);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,14 +19,14 @@ public interface IStoryPointRepository
|
||||
Task<StoryPointHistory> GetHistoryAsync(int projectId, int sceneId);
|
||||
}
|
||||
|
||||
public sealed class StoryPointRepository(ISqlConnectionFactory connections) : IStoryPointRepository
|
||||
public sealed class StoryPointRepository(ISqlConnectionFactory connections,IConfiguration? paragraphConfiguration=null) : IStoryPointRepository
|
||||
{
|
||||
public async Task<StoryPointHistory> GetHistoryAsync(int projectId, int sceneId)
|
||||
{
|
||||
using var connection = connections.CreateConnection();
|
||||
using var rows = await connection.QueryMultipleAsync("dbo.StoryPoint_GetHistory",
|
||||
new { ProjectID = projectId, SceneID = sceneId }, commandType: CommandType.StoredProcedure);
|
||||
return new StoryPointHistory
|
||||
var history=new StoryPointHistory
|
||||
{
|
||||
Knowledge = (await rows.ReadAsync<CharacterKnowledgeItem>()).ToList(),
|
||||
AssetLocations = (await rows.ReadAsync<SceneAssetLocation>()).ToList(),
|
||||
@ -35,5 +35,7 @@ public sealed class StoryPointRepository(ISqlConnectionFactory connections) : IS
|
||||
Threads = (await rows.ReadAsync<PlotThread>()).ToList(),
|
||||
ThreadEvents = (await rows.ReadAsync<ThreadEvent>()).ToList()
|
||||
};
|
||||
await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,history.Knowledge);
|
||||
return history;
|
||||
}
|
||||
}
|
||||
|
||||
225
PlotLine/Docs/AI/Chapter-Structure-Prompt-V3.md
Normal file
225
PlotLine/Docs/AI/Chapter-Structure-Prompt-V3.md
Normal file
@ -0,0 +1,225 @@
|
||||
# Chapter Structure Prompt V3
|
||||
|
||||
## Runtime Use
|
||||
|
||||
This prompt is intended to be loaded from disk and sent to the OpenAI API with minimal runtime substitution.
|
||||
|
||||
Replace the insertion blocks marked with `{{...}}` before sending.
|
||||
|
||||
## Prompt
|
||||
|
||||
You are PlotDirector's Chapter Structure engine.
|
||||
|
||||
You are an assistant archivist for a novelist. You observe chapter structure only. You do not critique, rewrite, create story entities or infer canon.
|
||||
|
||||
Your only task is to identify likely scene boundaries in one chapter, provide a short descriptive title for each detected scene, provide a light factual summary for each detected scene, record a compact structural setting where clear, and record compact point-of-view evidence when it is clear.
|
||||
|
||||
## Operating Principles
|
||||
|
||||
1. Treat the supplied chapter text as the authority.
|
||||
2. Identify structural breaks, not story meaning.
|
||||
3. Prefer slightly larger scenes over excessive fragmentation.
|
||||
4. Do not split merely because there is a paragraph break.
|
||||
5. Do not try to create perfect scenes.
|
||||
6. Return strict JSON only.
|
||||
7. Do not wrap JSON in markdown fences.
|
||||
8. Do not include explanatory prose before or after the JSON object.
|
||||
|
||||
## Boundary Guidance
|
||||
|
||||
A new scene normally begins when one or more of these occur:
|
||||
|
||||
- significant location change;
|
||||
- significant time change;
|
||||
- viewpoint change;
|
||||
- dramatic transition;
|
||||
- clear narrative break.
|
||||
|
||||
Do not create boundaries for ordinary paragraph changes, small action beats, dialogue turns or changes in emotional intensity alone.
|
||||
|
||||
Prefer larger, complete dramatic scenes over short fragments.
|
||||
|
||||
A scene should normally be a continuous unit of action, location, time and participating characters.
|
||||
|
||||
Do not create a new scene solely because:
|
||||
|
||||
- emotional tone changes;
|
||||
- a conversation changes topic;
|
||||
- a character has an internal realization;
|
||||
- narrative focus narrows or widens;
|
||||
- a character notices something new;
|
||||
- a paragraph begins with reflective narration;
|
||||
- the scene moves from action into dialogue or dialogue into reflection.
|
||||
|
||||
A new scene boundary should usually require one or more strong signals:
|
||||
|
||||
- meaningful location change;
|
||||
- significant passage of time;
|
||||
- clear change in participating characters;
|
||||
- clear break in dramatic action;
|
||||
- explicit scene break marker;
|
||||
- new viewpoint or narrator;
|
||||
- transition that a human reader would naturally perceive as the next scene.
|
||||
|
||||
Treat continuous arrival, settling, conversation and reflection in the same location as one scene unless there is a strong break.
|
||||
|
||||
Example: if a character enters a church, sits down, speaks with a reverend and leaves with a new personal realization, this should normally be one scene unless there is a clear time jump, viewpoint change or explicit break.
|
||||
|
||||
Avoid treating chapter headings or narrator/date headers as standalone scenes. If paragraph 1 is a chapter title and paragraph 2 is a narrator/date line, attach them to the first real scene rather than creating a separate metadata-only scene.
|
||||
|
||||
For ordinary prose chapters without explicit scene breaks, err slightly toward under-splitting rather than over-splitting.
|
||||
|
||||
## Paragraph Numbering
|
||||
|
||||
The supplied chapter text is already split into numbered paragraphs.
|
||||
|
||||
Each paragraph begins with an explicit marker such as:
|
||||
|
||||
```text
|
||||
[1] First paragraph text...
|
||||
[2] Second paragraph text...
|
||||
[3] Third paragraph text...
|
||||
```
|
||||
|
||||
Use only the supplied paragraph numbers.
|
||||
|
||||
Each `startParagraph` and `endParagraph` must refer to those explicit paragraph numbers.
|
||||
|
||||
Never invent paragraph numbers.
|
||||
|
||||
Never return an `endParagraph` greater than the highest paragraph number supplied.
|
||||
The final scene must end at the highest paragraph number supplied.
|
||||
|
||||
Do not create a separate final scene for a closing line unless it corresponds to an actual supplied paragraph number. If the final beat belongs to the previous scene, include it in the previous scene.
|
||||
|
||||
## Point of View Guidance
|
||||
|
||||
Identify the default chapter point of view only when the supplied text provides a clear narrator/viewpoint signal.
|
||||
|
||||
Explicit manuscript labels such as `Narrated by Lena` are extremely strong evidence.
|
||||
When `chapterContext.knownCharacters` contains a matching canonical character or alias, prefer that spelling for POV names.
|
||||
|
||||
If no POV can be determined, return `defaultPov` as `null`.
|
||||
|
||||
If the chapter has one default POV with a few clear scene-level changes, set `mixedPov` to `true` and add `povOverride` only on scenes where the POV differs from the chapter default.
|
||||
|
||||
If the whole chapter is mixed and no default is clear, set `mixedPov` to `true`, return `defaultPov` as `null`, and add scene `povOverride` values only where clear.
|
||||
|
||||
Use manuscript names exactly as presented. Do not invent canonical full names.
|
||||
|
||||
Do not create placeholder scenes or invalid ranges to "ensure coverage". If the previous scene already ends at the final supplied paragraph, stop there.
|
||||
|
||||
Scene boundaries must:
|
||||
|
||||
- start at paragraph `1`;
|
||||
- cover the chapter in order;
|
||||
- not overlap;
|
||||
- not leave gaps;
|
||||
- be contiguous and non-overlapping where possible;
|
||||
- correspond to actual supplied paragraph numbers;
|
||||
- never use a `startParagraph` greater than `endParagraph`;
|
||||
- use increasing `sceneNumber` values starting at `1`.
|
||||
|
||||
## Output Requirements
|
||||
|
||||
Return exactly one JSON object and no prose outside it.
|
||||
|
||||
Return only these root properties:
|
||||
|
||||
- `schemaVersion`
|
||||
- `chapterSummary`
|
||||
- `defaultPov`
|
||||
- `mixedPov`
|
||||
- `sceneBoundaries`
|
||||
|
||||
Each `sceneBoundaries` item must contain exactly:
|
||||
|
||||
- `sceneNumber`
|
||||
- `startParagraph`
|
||||
- `endParagraph`
|
||||
- `suggestedTitle`
|
||||
- `structuralSummary`
|
||||
- `structuralSetting`
|
||||
- `povOverride`
|
||||
- `confidence`
|
||||
- `reason`
|
||||
|
||||
Use confidence values from `0` to `100` (integers only; never decimals).
|
||||
Confidence values must be standard JSON numbers with no spaces inside the number.
|
||||
Correct examples: `0.8`, `0.75`, `1.0`, `0.0`.
|
||||
Incorrect examples: `0. 8`, `7 .5`, `0,8`, `"0.8"`.
|
||||
|
||||
Use `structuralSummary` for a factual, neutral summary of what happens in that scene. It should normally be 25 to 40 words, avoid interpretation, and only use information present in the supplied text.
|
||||
|
||||
Use `structuralSetting` for the scene's compact active place/time label when the chapter text supports it, such as `Mara's car at night`, `church office`, or `archive reception`. Use `null` when no active setting is clear. Do not invent named locations.
|
||||
|
||||
Use `suggestedTitle` for a concise, factual scene title. It must be 2 to 6 words, memorable without being dramatic, and grounded only in the supplied text. Avoid generic titles such as "Opening Scene", "Conversation", "Chapter Scene", or "Scene 1". Do not truncate or restate the structural summary.
|
||||
|
||||
Use `defaultPov` for the chapter's suggested default narrator/viewpoint character, or `null` when not clear. When present it must contain exactly `characterName`, `confidence`, `evidence`, and `isExplicit`.
|
||||
|
||||
Use `povOverride` only where that scene clearly differs from `defaultPov`, or where there is no default but that scene's POV is clear. Otherwise return `null`.
|
||||
|
||||
Use short factual reasons, such as:
|
||||
|
||||
`Location changes from house to train.`
|
||||
|
||||
Do not output:
|
||||
|
||||
- characters;
|
||||
- locations;
|
||||
- assets;
|
||||
- relationships;
|
||||
- metrics;
|
||||
- interpretive scene analysis;
|
||||
- observations;
|
||||
- continuity warnings;
|
||||
- plot threads.
|
||||
|
||||
## JSON Shape
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": "2.0",
|
||||
"chapterSummary": "Structural analysis of the supplied chapter.",
|
||||
"defaultPov": {
|
||||
"characterName": "Lena",
|
||||
"confidence": 96,
|
||||
"evidence": "The chapter begins with an explicit Narrated by Lena label.",
|
||||
"isExplicit": true
|
||||
},
|
||||
"mixedPov": false,
|
||||
"sceneBoundaries": [
|
||||
{
|
||||
"sceneNumber": 1,
|
||||
"startParagraph": 1,
|
||||
"endParagraph": 3,
|
||||
"suggestedTitle": "Arrival at the Church",
|
||||
"structuralSummary": "The opening scene follows the same continuous action across the supplied paragraphs, keeping the characters in one time and place while the immediate situation is established.",
|
||||
"structuralSetting": "church",
|
||||
"povOverride": null,
|
||||
"confidence": 86,
|
||||
"reason": "Opening scene remains in the same place and time."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If the chapter appears to contain only one scene, return one boundary covering all paragraphs.
|
||||
|
||||
## Runtime Data Insertion
|
||||
|
||||
The application will insert chapter context and chapter text below.
|
||||
|
||||
### Supplied Chapter Context
|
||||
|
||||
```json
|
||||
{{CHAPTER_CONTEXT_JSON}}
|
||||
```
|
||||
|
||||
### Chapter Text
|
||||
|
||||
```text
|
||||
{{CHAPTER_TEXT}}
|
||||
```
|
||||
|
||||
Now return the Chapter Structure JSON object only.
|
||||
@ -125,7 +125,9 @@ public sealed class WordCompanionFollowHub(
|
||||
return await WritingWorkspaceStatusAsync(userId, scope);
|
||||
}
|
||||
|
||||
public async Task<ManuscriptScanState> StartOnboardingManuscriptScan()
|
||||
public Task<ManuscriptScanState> StartOnboardingManuscriptScan()=>StartManuscriptScan(false);
|
||||
public Task<ManuscriptScanState> StartParagraphManuscriptScan()=>StartManuscriptScan(true);
|
||||
private async Task<ManuscriptScanState> StartManuscriptScan(bool paragraphs)
|
||||
{
|
||||
var userId = RequireUserId();
|
||||
var state = await onboarding.GetAsync(userId);
|
||||
@ -138,9 +140,10 @@ public sealed class WordCompanionFollowHub(
|
||||
}
|
||||
|
||||
if(nativeCapture!=null){
|
||||
try{var native=await nativeCapture.Start(userId,state.UserOnboardingStateID,state.ProjectID.Value,state.BookID.Value);if(native!=null){await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanStateChanged",native);return native;}}
|
||||
try{var native=await nativeCapture.Start(userId,state.UserOnboardingStateID,state.ProjectID.Value,state.BookID.Value,paragraphs);if(native!=null){await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanStateChanged",native);return native;}}
|
||||
catch(InvalidOperationException e){throw new HubException(e.Message);}
|
||||
}
|
||||
if(paragraphs)throw new HubException("Connect the updated native Companion to use paragraph tracking. No legacy capture was started.");
|
||||
var presenceStatus = await presence.GetStatusAsync(userId);
|
||||
if (!presenceStatus.IsConnected)
|
||||
{
|
||||
|
||||
@ -1270,6 +1270,9 @@ public sealed class KnowledgeState
|
||||
|
||||
public sealed class CharacterKnowledgeItem
|
||||
{
|
||||
[Microsoft.AspNetCore.Mvc.ModelBinding.BindNever]
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public string EvidenceState {get;set;}="Verified";
|
||||
[Microsoft.AspNetCore.Mvc.ModelBinding.BindNever]
|
||||
public string? SourceReviewKey { get; set; }
|
||||
public int CharacterKnowledgeID { get; set; }
|
||||
@ -1364,6 +1367,9 @@ public sealed class CharacterRelationship
|
||||
|
||||
public sealed class RelationshipEvent
|
||||
{
|
||||
[Microsoft.AspNetCore.Mvc.ModelBinding.BindNever]
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public string EvidenceState {get;set;}="Verified";
|
||||
public int? CreatedByUserID { get; set; }
|
||||
public int? ModifiedByUserID { get; set; }
|
||||
public DateTime? CreatedDateUTC { get; set; }
|
||||
|
||||
@ -64,6 +64,10 @@ public sealed class ManuscriptScanChunk
|
||||
|
||||
public sealed class ManuscriptScanPreview
|
||||
{
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition=System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public bool ParagraphTracking {get;init;}
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition=System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
|
||||
public PlotDirector.Companion.Protocol.Manuscript.ParagraphOccurrence[]? NativeParagraphs {get;init;}
|
||||
public Guid PreviewID { get; init; } = Guid.NewGuid();
|
||||
public int UserID { get; init; }
|
||||
public int OnboardingID { get; init; }
|
||||
|
||||
83
PlotLine/Models/ParagraphManuscriptModels.cs
Normal file
83
PlotLine/Models/ParagraphManuscriptModels.cs
Normal file
@ -0,0 +1,83 @@
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
namespace PlotLine.Models;
|
||||
public sealed class ParagraphManuscript
|
||||
{
|
||||
public int Version {get;set;}=1;
|
||||
public int BookId {get;set;}
|
||||
public int ProjectId {get;set;}
|
||||
public string DocumentName {get;set;}="";
|
||||
public Guid ManuscriptId {get;set;}
|
||||
public long Revision {get;set;}
|
||||
public Guid LastRequestId {get;set;}
|
||||
public Guid SessionId {get;set;}
|
||||
public long WordRevision {get;set;}
|
||||
public string SnapshotHash {get;set;}="";
|
||||
public string Mode {get;set;}="Manual";
|
||||
public DateTime UpdatedUtc {get;set;}
|
||||
public List<StoryParagraph> Paragraphs {get;set;}=[];
|
||||
public List<ParagraphChapter> Chapters {get;set;}=[];
|
||||
public List<ParagraphScene> Scenes {get;set;}=[];
|
||||
public List<StoryEvidence> Evidence {get;set;}=[];
|
||||
public List<ManuscriptEventOption> EventPositions {get;set;}=[];
|
||||
public List<ParagraphLayout> Undo {get;set;}=[];
|
||||
}
|
||||
public sealed class StoryParagraph
|
||||
{
|
||||
public ParagraphOccurrence Occurrence {get;set;}=new();
|
||||
public int? ChapterId {get;set;}
|
||||
public Guid? SceneId {get;set;}
|
||||
public bool Story {get;set;}
|
||||
public bool PositionVerified {get;set;}
|
||||
}
|
||||
public sealed class ParagraphScene
|
||||
{
|
||||
public Guid Id {get;set;}=Guid.NewGuid();
|
||||
public int CanonicalId {get;set;}
|
||||
public int ChapterId {get;set;}
|
||||
public string Title {get;set;}="";
|
||||
public bool Retired {get;set;}
|
||||
public Guid? MergedInto {get;set;}
|
||||
public bool NeedsRefinement {get;set;}
|
||||
}
|
||||
public sealed class StoryEvidence
|
||||
{
|
||||
public Guid Id {get;set;}=Guid.NewGuid();
|
||||
public string EventKind {get;set;}="";
|
||||
public int EventId {get;set;}
|
||||
public bool Primary {get;set;}
|
||||
public Guid StartParagraph {get;set;}
|
||||
public Guid EndParagraph {get;set;}
|
||||
public int? StartOffset {get;set;}
|
||||
public int? EndOffset {get;set;}
|
||||
public string OriginalText {get;set;}="";
|
||||
public string ConfirmedText {get;set;}="";
|
||||
public string CurrentText {get;set;}="";
|
||||
public string OriginalPosition {get;set;}="";
|
||||
public string PreviousPosition {get;set;}="";
|
||||
public string CurrentPosition {get;set;}="";
|
||||
public Guid? PreviousScene {get;set;}
|
||||
public Guid? CurrentScene {get;set;}
|
||||
public string State {get;set;}="Verified";
|
||||
public int? DerivedSceneId {get;set;}
|
||||
}
|
||||
public sealed class ParagraphLayout
|
||||
{
|
||||
public List<ParagraphChapter> Chapters {get;set;}=[];
|
||||
public string SnapshotHash {get;set;}="";
|
||||
public List<ParagraphScene> Scenes {get;set;}=[];
|
||||
public List<ParagraphAssignment> Assignments {get;set;}=[];
|
||||
public List<ManuscriptEventOption> EventPositions {get;set;}=[];
|
||||
}
|
||||
public sealed class ParagraphAssignment {public Guid ParagraphId {get;set;}public int? ChapterId {get;set;}public Guid? SceneId {get;set;}public bool PositionVerified {get;set;}}
|
||||
public sealed class ManuscriptEventOption {public string Kind {get;set;}="";public int Id {get;set;}public int SceneId {get;set;}public string Description {get;set;}="";}
|
||||
public sealed class ParagraphBootstrapScene {public int SceneId {get;set;}public int ChapterId {get;set;}public string Title {get;set;}="";public int Start {get;set;}public int End {get;set;}public bool NeedsRefinement {get;set;}}
|
||||
public sealed class ParagraphWorkspaceModel
|
||||
{
|
||||
public ParagraphManuscript State {get;set;}=new();public string BookTitle {get;set;}="";public IReadOnlyList<ManuscriptEventOption> Events {get;set;}=[];public int Page {get;set;}=1;public int EvidencePage {get;set;}=1;public string? Message {get;set;}
|
||||
}
|
||||
|
||||
public sealed class ParagraphSyncStatus {public string SnapshotHash {get;set;}="";public int BookId {get;set;}public Guid ManuscriptId {get;set;}public long Revision {get;set;}public string Mode {get;set;}="Manual";public Guid SessionId {get;set;}public long WordRevision {get;set;}public bool CanWrite {get;set;}public bool Paused {get;set;}}
|
||||
|
||||
public sealed class ParagraphChapter {public int CanonicalId {get;set;}public Guid HeadingId {get;set;}public string Title {get;set;}="";}
|
||||
|
||||
public sealed class ParagraphPosition { public bool HasSnapshot {get;set;} public long Revision {get;set;} public int? ChapterID {get;set;} public int? SceneID {get;set;} }
|
||||
@ -112,6 +112,8 @@ public class Program
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativeManuscriptCapture>();
|
||||
builder.Services.AddHostedService<PlotLine.Services.NativeCompanion.NativeCaptureExpiry>();
|
||||
builder.Services.AddScoped<IManuscriptCaptureRepository, ManuscriptCaptureRepository>();
|
||||
builder.Services.AddScoped<IParagraphManuscriptRepository,ParagraphManuscriptRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Manuscript.ParagraphManuscriptService>();
|
||||
builder.Services.AddSingleton<StoryIntelligenceRequestLimiter>();
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
|
||||
@ -52,6 +52,8 @@ public static class ChapterStructureBoundaryNormaliser
|
||||
{
|
||||
SchemaVersion = chapterStructure.SchemaVersion,
|
||||
ChapterSummary = chapterStructure.ChapterSummary,
|
||||
DefaultPov = chapterStructure.DefaultPov,
|
||||
MixedPov = chapterStructure.MixedPov,
|
||||
SceneBoundaries = boundaries.ToList(),
|
||||
ExtensionData = chapterStructure.ExtensionData
|
||||
};
|
||||
|
||||
@ -29,9 +29,9 @@ public sealed class ChapterStructureValidator : IChapterStructureValidator
|
||||
}
|
||||
|
||||
RequiredString(chapterStructure.SchemaVersion, "schemaVersion", result);
|
||||
if (!string.Equals(chapterStructure.SchemaVersion, "1.0", StringComparison.Ordinal))
|
||||
if (chapterStructure.SchemaVersion is not ("1.0" or "2.0"))
|
||||
{
|
||||
AddError(result, "schemaVersion", "Schema version must be \"1.0\".", "Return schemaVersion as \"1.0\".");
|
||||
AddError(result, "schemaVersion", "Unsupported chapter structure schema.", "Use schemaVersion 1.0 for legacy decimals or 2.0 for integer confidence.");
|
||||
}
|
||||
|
||||
RequiredString(chapterStructure.ChapterSummary, "chapterSummary", result);
|
||||
@ -41,7 +41,8 @@ public sealed class ChapterStructureValidator : IChapterStructureValidator
|
||||
}
|
||||
else
|
||||
{
|
||||
ValidateBoundaries(chapterStructure.SceneBoundaries, paragraphCount, result);
|
||||
ValidateBoundaries(chapterStructure.SceneBoundaries, paragraphCount, result, chapterStructure.SchemaVersion == "2.0");
|
||||
ValidatePov(chapterStructure.DefaultPov, "defaultPov", result, chapterStructure.SchemaVersion == "2.0");
|
||||
}
|
||||
|
||||
Unknown(chapterStructure.ExtensionData, "$", result);
|
||||
@ -59,7 +60,7 @@ public sealed class ChapterStructureValidator : IChapterStructureValidator
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void ValidateBoundaries(List<ChapterSceneBoundary> boundaries, int paragraphCount, ValidationResult result)
|
||||
private static void ValidateBoundaries(List<ChapterSceneBoundary> boundaries, int paragraphCount, ValidationResult result, bool integerScale)
|
||||
{
|
||||
if (boundaries.Count == 0)
|
||||
{
|
||||
@ -118,7 +119,8 @@ public sealed class ChapterStructureValidator : IChapterStructureValidator
|
||||
expectedStart = boundary.EndParagraph.Value + 1;
|
||||
}
|
||||
|
||||
Confidence(boundary.Confidence, $"{path}.confidence", result);
|
||||
Confidence(boundary.Confidence, $"{path}.confidence", result, integerScale);
|
||||
ValidatePov(boundary.PovOverride, $"{path}.povOverride", result, integerScale);
|
||||
RequiredString(boundary.StructuralSummary, $"{path}.structuralSummary", result);
|
||||
if (!string.IsNullOrWhiteSpace(boundary.StructuralSummary))
|
||||
{
|
||||
@ -138,15 +140,19 @@ public sealed class ChapterStructureValidator : IChapterStructureValidator
|
||||
}
|
||||
}
|
||||
|
||||
private static void Confidence(decimal? value, string path, ValidationResult result)
|
||||
private static void ValidatePov(ChapterStructurePovSuggestion? pov,string path,ValidationResult result,bool integerScale) { if(integerScale&&pov!=null) Confidence(pov.Confidence,path+".confidence",result,integerScale); }
|
||||
|
||||
private static void Confidence(decimal? value, string path, ValidationResult result, bool integerScale)
|
||||
{
|
||||
if (!value.HasValue)
|
||||
{
|
||||
AddError(result, path, "Confidence is required.", "Return a confidence value from 0.0 to 1.0.");
|
||||
AddError(result, path, "Confidence is required.", integerScale ? "Return an integer confidence score from 0 to 100." : "Return a confidence value from 0.0 to 1.0.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (value < 0 || value > 1)
|
||||
if (integerScale && (value < 0 || value > 100 || decimal.Truncate(value.Value)!=value.Value))
|
||||
{ AddError(result,path,"Confidence must be an integer from 0 to 100.","Use integer confidence scores for schema 2.0."); }
|
||||
else if (!integerScale && (value < 0 || value > 1))
|
||||
{
|
||||
AddError(result, path, "Confidence must be from 0.0 to 1.0.", "Use the 0.0 to 1.0 confidence scale.");
|
||||
}
|
||||
|
||||
@ -4138,7 +4138,7 @@ public sealed partial class StoryStateService(
|
||||
|
||||
foreach (var character in charactersToCheck)
|
||||
{
|
||||
var knowledgeEvents = items.Where(x => x.CharacterID == character.CharacterID)
|
||||
var knowledgeEvents = items.Where(x => x.EvidenceState=="Verified" && x.CharacterID == character.CharacterID)
|
||||
.Where(x => context.SceneIndexes.ContainsKey(x.SceneID))
|
||||
.OrderBy(x => context.SceneIndexes.GetValueOrDefault(x.SceneID, int.MaxValue))
|
||||
.ThenBy(x => x.CreatedDate)
|
||||
@ -5975,7 +5975,7 @@ public sealed class RelationshipMapService(IProjectRepository projects, ICharact
|
||||
{
|
||||
var visibleEvents = maxSceneIndex < 0
|
||||
? []
|
||||
: events.Where(x => SceneIndex(sceneOrder, x.SceneID) <= maxSceneIndex).ToList();
|
||||
: events.Where(x => x.EvidenceState=="Verified" && SceneIndex(sceneOrder, x.SceneID) <= maxSceneIndex).ToList();
|
||||
|
||||
var hasInitialState = hasDatedInitialState || relationship.IsInitialRelationship || !events.Any();
|
||||
if (!hasInitialState && visibleEvents.Count == 0)
|
||||
|
||||
@ -0,0 +1,23 @@
|
||||
using System.Text.Json;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.Manuscript;
|
||||
// Versioned provider contract; normalized decimals remain only at the legacy domain boundary.
|
||||
public static class ChapterStructureIntegerContract
|
||||
{
|
||||
public static StoryIntelligenceResponseContract ForParagraphCount(int count)
|
||||
{
|
||||
if(count<1)throw new ArgumentOutOfRangeException(nameof(count));
|
||||
var schema=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(Contract.Schema))!;
|
||||
var boundaries=schema["properties"]!["sceneBoundaries"]!;boundaries["minItems"]=1;boundaries["maxItems"]=count;
|
||||
foreach(var name in new[]{"sceneNumber","startParagraph","endParagraph"})boundaries["items"]!["properties"]![name]!["maximum"]=count;
|
||||
return new(){Name=Contract.Name,Schema=schema,Strict=true};
|
||||
}
|
||||
public static StoryIntelligenceResponseContract Contract {get;}=new(){Name="chapter_structure_v2",Schema=JsonSerializer.Deserialize<JsonElement>("""
|
||||
{"type":"object","additionalProperties":false,"required":["schemaVersion","chapterSummary","defaultPov","mixedPov","sceneBoundaries"],"properties":{
|
||||
"schemaVersion":{"type":"string","enum":["2.0"]},"chapterSummary":{"type":"string"},"defaultPov":{"$ref":"#/$defs/pov"},"mixedPov":{"type":"boolean"},
|
||||
"sceneBoundaries":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["sceneNumber","startParagraph","endParagraph","suggestedTitle","structuralSummary","structuralSetting","povOverride","confidence","reason"],"properties":{
|
||||
"sceneNumber":{"type":"integer","minimum":1},"startParagraph":{"type":"integer","minimum":1},"endParagraph":{"type":"integer","minimum":1},
|
||||
"suggestedTitle":{"type":"string"},"structuralSummary":{"type":"string"},"structuralSetting":{"type":["string","null"]},"povOverride":{"$ref":"#/$defs/pov"},"confidence":{"type":"integer","minimum":0,"maximum":100},"reason":{"type":"string"}}}}},
|
||||
"$defs":{"pov":{"anyOf":[{"type":"null"},{"type":"object","additionalProperties":false,"required":["characterName","confidence","evidence","isExplicit"],"properties":{"characterName":{"type":"string"},"confidence":{"type":"integer","minimum":0,"maximum":100},"evidence":{"type":"string"},"isExplicit":{"type":"boolean"}}}]}}}
|
||||
""")};
|
||||
}
|
||||
137
PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs
Normal file
137
PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs
Normal file
@ -0,0 +1,137 @@
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.Manuscript;
|
||||
// One reconciliation engine; the existing capture transport supplies value snapshots, never COM objects.
|
||||
public static class ParagraphManuscriptEngine
|
||||
{
|
||||
public static ParagraphManuscript Bootstrap(int book,int project,Guid manuscript,IReadOnlyList<ParagraphOccurrence> rows,IReadOnlyList<ParagraphBootstrapScene> scenes)
|
||||
{
|
||||
if(manuscript==Guid.Empty||book<=0)throw new ArgumentException("A persistent manuscript and book are required.");
|
||||
var state=new ParagraphManuscript{BookId=book,ProjectId=project,ManuscriptId=manuscript};
|
||||
state.Scenes=scenes.Select(s=>new ParagraphScene{CanonicalId=s.SceneId,ChapterId=s.ChapterId,Title=s.Title,NeedsRefinement=s.NeedsRefinement}).ToList();
|
||||
var comparison=ParagraphReconciliation.Compare([],rows);
|
||||
if(rows.All(p=>p.Id!=Guid.Empty)&&rows.Select(p=>p.Id).Distinct().Count()==rows.Count)for(int i=0;i<rows.Count;i++)comparison.Current[i].Id=rows[i].Id;
|
||||
foreach(var p in comparison.Current){var source=scenes.LastOrDefault(s=>p.Ordinal+1>=s.Start&&p.Ordinal+1<=s.End);var scene=source==null?null:state.Scenes.First(s=>s.CanonicalId==source.SceneId);
|
||||
state.Paragraphs.Add(new(){Occurrence=p,ChapterId=scene?.ChapterId,SceneId=p.Outline==1?null:scene?.Id,Story=scene!=null&&p.Outline!=1,PositionVerified=scene!=null});}
|
||||
foreach(var chapter in scenes.GroupBy(s=>s.ChapterId)){
|
||||
var first=chapter.Min(s=>s.Start)-1;var heading=state.Paragraphs.LastOrDefault(p=>p.Occurrence.Ordinal<=first&&p.Occurrence.Outline==1);
|
||||
state.Chapters.Add(new(){CanonicalId=chapter.Key,HeadingId=heading?.Occurrence.Id??Guid.Empty,Title=heading?.Occurrence.Text.Trim()??"Chapter"});
|
||||
}
|
||||
foreach(var p in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){var chapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==p.Occurrence.Id);p.ChapterId=chapter?.CanonicalId;p.PositionVerified=p.ChapterId>0;}
|
||||
state.SnapshotHash=Hash(rows);state.UpdatedUtc=DateTime.UtcNow;Validate(state);return state;
|
||||
}
|
||||
public static string Hash(IReadOnlyList<ParagraphOccurrence> rows)=>ParagraphReconciliation.SnapshotFingerprint(rows);
|
||||
public static ParagraphManuscript Clone(ParagraphManuscript state)=>JsonSerializer.Deserialize<ParagraphManuscript>(JsonSerializer.Serialize(state))!;
|
||||
public static void Reconcile(ParagraphManuscript state,IReadOnlyList<ParagraphOccurrence> rows)
|
||||
{
|
||||
var comparison=ParagraphReconciliation.Compare(state.Paragraphs.Select(p=>p.Occurrence).ToArray(),rows);var old=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var next=comparison.Current;
|
||||
var index=next.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i);
|
||||
var chapterHeadings=state.Chapters.Where(c=>index.ContainsKey(c.HeadingId)).ToDictionary(c=>c.HeadingId);
|
||||
if(state.Chapters.Any(c=>c.CanonicalId==0&&c.HeadingId!=Guid.Empty&&!index.ContainsKey(c.HeadingId)))throw new InvalidOperationException("An excluded manuscript section boundary cannot be reliably identified. Review the Word structure before synchronising; no saved manuscript was changed.");
|
||||
var excludedAt=new bool[next.Length];bool excluded=false;
|
||||
var chapterAt=new int?[next.Length];int? currentChapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==Guid.Empty)?.CanonicalId;
|
||||
for(int n=0;n<next.Length;n++){if(chapterHeadings.TryGetValue(next[n].Id,out var binding)){excluded=binding.CanonicalId==0;currentChapter=excluded?null:binding.CanonicalId;}else if(next[n].Outline==1){currentChapter=null;excluded=false;}chapterAt[n]=currentChapter;excludedAt[n]=excluded;}
|
||||
var oldGroups=state.Paragraphs.Where(p=>p.SceneId.HasValue).GroupBy(p=>p.SceneId!.Value).ToDictionary(g=>g.Key,g=>g.ToArray());
|
||||
var starts=new List<(int At,ParagraphScene Scene,bool Verified)>();
|
||||
foreach(var scene in state.Scenes.Where(s=>!s.Retired)){
|
||||
var prior=oldGroups.GetValueOrDefault(scene.Id)??[];if(prior.Length==0)continue;
|
||||
if(index.TryGetValue(prior[0].Occurrence.Id,out var at)){
|
||||
// A moved scene-start paragraph alone is not proof that the whole scene moved.
|
||||
var positions=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray();
|
||||
var complete=positions.Length==prior.Length&&positions[^1]-positions[0]+1==positions.Length;
|
||||
if(complete&&chapterAt[positions[0]].HasValue&&positions.All(pos=>chapterAt[pos]==chapterAt[positions[0]]))scene.ChapterId=chapterAt[positions[0]]!.Value;
|
||||
var verified=at==positions[0]&&(prior.Length==1||complete||!next[at].WasMoved);
|
||||
if(!verified&&!complete){var remaining=positions.Where(pos=>!next[pos].WasMoved).ToArray();if(remaining.Length>0)at=remaining[0];scene.NeedsRefinement=true;}
|
||||
starts.Add((at,scene,verified));
|
||||
}else{
|
||||
var surviving=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray();
|
||||
if(surviving.Length>0){starts.Add((surviving[0],scene,false));scene.NeedsRefinement=true;}
|
||||
}
|
||||
}
|
||||
starts=starts.OrderBy(s=>s.At).ToList();var current=new List<StoryParagraph>();int boundaryIndex=-1;
|
||||
foreach(var p in next){while(boundaryIndex+1<starts.Count&&starts[boundaryIndex+1].At<=p.Ordinal)boundaryIndex++;var boundary=boundaryIndex>=0?starts[boundaryIndex]:default;var before=old.GetValueOrDefault(p.Id);var scene=boundary.Scene;
|
||||
// Heading 1 is structure, not prose. Front matter before an imported boundary stays outside the story.
|
||||
if(scene==null&&p.Outline!=1&&chapterAt[p.Ordinal].HasValue){var first=starts.FirstOrDefault(s=>s.Scene.ChapterId==chapterAt[p.Ordinal]);if(first.Scene!=null){scene=first.Scene;scene.NeedsRefinement=true;}}
|
||||
var story=!excludedAt[p.Ordinal]&&p.Outline!=1&&scene!=null;
|
||||
current.Add(new(){Occurrence=p,Story=story,SceneId=story?scene!.Id:null,ChapterId=chapterAt[p.Ordinal],PositionVerified=(p.Outline==1&&chapterAt[p.Ordinal]>0)||(story&&boundary.Scene!=null&&boundary.Scene.Id==scene?.Id&&boundary.Verified&&p.Resolution!="Ambiguous"&&chapterAt[p.Ordinal]==scene?.ChapterId)});
|
||||
}
|
||||
// If a boundary disappeared, preserve that scene's surviving paragraph grouping as unresolved.
|
||||
foreach(var p in current.Where(p=>p.SceneId==null&&p.Occurrence.Outline!=1&&!excludedAt[p.Occurrence.Ordinal]))if(old.TryGetValue(p.Occurrence.Id,out var prior)&&prior.Story){p.Story=true;p.SceneId=prior.SceneId;p.ChapterId=prior.ChapterId;p.PositionVerified=false;}
|
||||
foreach(var scene in state.Scenes.Where(s=>!s.Retired))if(current.Any(p=>p.SceneId==scene.Id&&!p.PositionVerified))scene.NeedsRefinement=true;
|
||||
state.Paragraphs=current;var hash=Hash(rows);if(hash!=state.SnapshotHash)state.Undo.Clear();state.SnapshotHash=hash;state.UpdatedUtc=DateTime.UtcNow;RefreshEvidence(state);Validate(state);
|
||||
}
|
||||
private static ParagraphLayout Layout(ParagraphManuscript state)=>new(){Chapters=state.Chapters.Select(c=>new ParagraphChapter{CanonicalId=c.CanonicalId,HeadingId=c.HeadingId,Title=c.Title}).ToList(),SnapshotHash=state.SnapshotHash,EventPositions=state.EventPositions.Select(e=>new ManuscriptEventOption{Kind=e.Kind,Id=e.Id,SceneId=e.SceneId,Description=e.Description}).ToList(),Scenes=state.Scenes.Select(s=>new ParagraphScene{Id=s.Id,CanonicalId=s.CanonicalId,ChapterId=s.ChapterId,Title=s.Title,Retired=s.Retired,MergedInto=s.MergedInto,NeedsRefinement=s.NeedsRefinement}).ToList(),Assignments=state.Paragraphs.Select(p=>new ParagraphAssignment{ParagraphId=p.Occurrence.Id,ChapterId=p.ChapterId,SceneId=p.SceneId,PositionVerified=p.PositionVerified}).ToList()};
|
||||
private static void Remember(ParagraphManuscript state){var limit=Math.Clamp(100000/Math.Max(1,state.Paragraphs.Count),1,12);while(state.Undo.Count>=limit)state.Undo.RemoveAt(0);state.Undo.Add(Layout(state));}
|
||||
public static void ConfirmGrouping(ParagraphManuscript state,Guid sceneId)
|
||||
{
|
||||
var scene=state.Scenes.Single(s=>s.Id==sceneId&&!s.Retired);var rows=state.Paragraphs.Where(p=>p.SceneId==sceneId&&p.Story).ToArray();if(rows.Length==0)throw new ArgumentException("No surviving scene paragraphs to confirm.");
|
||||
Remember(state);foreach(var p in rows){p.PositionVerified=true;p.ChapterId=scene.ChapterId;}scene.NeedsRefinement=false;
|
||||
foreach(var heading in state.Paragraphs.Where(p=>p.Occurrence.Outline==1&&p.Occurrence.Ordinal>=rows[0].Occurrence.Ordinal-1&&p.Occurrence.Ordinal<=rows[^1].Occurrence.Ordinal&&state.Chapters.All(c=>c.HeadingId!=p.Occurrence.Id)))state.Chapters.Add(new(){CanonicalId=scene.ChapterId,HeadingId=heading.Occurrence.Id,Title=heading.Occurrence.Text.Trim()});
|
||||
RefreshEvidence(state);Validate(state);
|
||||
}
|
||||
public static void Split(ParagraphManuscript state,Guid paragraph,string title)
|
||||
{
|
||||
var p=state.Paragraphs.SingleOrDefault(p=>p.Occurrence.Id==paragraph&&p.Story)??throw new ArgumentException("Choose a story paragraph.");var source=state.Scenes.Single(s=>s.Id==p.SceneId&&!s.Retired);
|
||||
var group=state.Paragraphs.Where(x=>x.SceneId==source.Id).ToArray();if(group[0]==p)throw new ArgumentException("The paragraph already begins a scene.");if(string.IsNullOrWhiteSpace(title)||title.Length>200)throw new ArgumentException("Enter a scene title of up to 200 characters.");
|
||||
Remember(state);var created=new ParagraphScene{ChapterId=source.ChapterId,Title=title.Trim()};state.Scenes.Add(created);foreach(var row in group.Where(x=>x.Occurrence.Ordinal>=p.Occurrence.Ordinal)){row.SceneId=created.Id;row.PositionVerified=true;}source.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
|
||||
}
|
||||
public static void MoveBoundary(ParagraphManuscript state,Guid rightScene,Guid firstParagraph)
|
||||
{
|
||||
var right=state.Scenes.SingleOrDefault(s=>s.Id==rightScene&&!s.Retired)??throw new ArgumentException("Scene no longer exists.");
|
||||
var ordered=state.Paragraphs.Where(p=>p.Story).GroupBy(p=>p.SceneId).ToArray();var i=Array.FindIndex(ordered,g=>g.Key==rightScene);if(i<=0)throw new ArgumentException("Choose an adjacent scene boundary.");
|
||||
var left=state.Scenes.Single(s=>s.Id==ordered[i-1].Key);if(left.ChapterId!=right.ChapterId)throw new ArgumentException("A boundary cannot cross chapters.");
|
||||
var rows=ordered[i-1].Concat(ordered[i]).OrderBy(p=>p.Occurrence.Ordinal).ToArray();var cut=Array.FindIndex(rows,p=>p.Occurrence.Id==firstParagraph);if(cut<=0||cut>=rows.Length)throw new ArgumentException("Keep at least one paragraph in each scene.");
|
||||
Remember(state);for(int n=0;n<rows.Length;n++){rows[n].SceneId=n<cut?left.Id:right.Id;rows[n].PositionVerified=true;}left.NeedsRefinement=right.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
|
||||
}
|
||||
public static void Merge(ParagraphManuscript state,Guid leftScene,Guid rightScene)
|
||||
{
|
||||
var groups=state.Paragraphs.Where(p=>p.Story).GroupBy(p=>p.SceneId).ToArray();var i=Array.FindIndex(groups,g=>g.Key==leftScene);if(i<0||i+1>=groups.Length||groups[i+1].Key!=rightScene)throw new ArgumentException("Only adjacent scenes can be merged.");
|
||||
var left=state.Scenes.Single(s=>s.Id==leftScene&&!s.Retired);var right=state.Scenes.Single(s=>s.Id==rightScene&&!s.Retired);if(left.ChapterId!=right.ChapterId)throw new ArgumentException("Scenes belong to different chapters.");
|
||||
Remember(state);foreach(var p in state.Paragraphs.Where(p=>p.SceneId==rightScene)){p.SceneId=leftScene;p.PositionVerified=true;}right.Retired=true;right.MergedInto=left.Id;foreach(var e in state.EventPositions.Where(e=>e.SceneId==right.CanonicalId))e.SceneId=left.CanonicalId;left.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
|
||||
}
|
||||
public static void Undo(ParagraphManuscript state)
|
||||
{
|
||||
if(state.Undo.Count==0)throw new InvalidOperationException("No structure change to undo.");var previous=state.Undo[^1];if(previous.SnapshotHash!=state.SnapshotHash)throw new InvalidOperationException("Word changed. This earlier layout cannot safely be restored.");
|
||||
state.Undo.RemoveAt(state.Undo.Count-1);foreach(var extra in state.Scenes.Where(s=>previous.Scenes.All(p=>p.Id!=s.Id))){extra.Retired=true;previous.Scenes.Add(extra);}state.Scenes=previous.Scenes;state.Chapters=previous.Chapters;state.EventPositions=previous.EventPositions;var assignments=previous.Assignments.ToDictionary(p=>p.ParagraphId);foreach(var p in state.Paragraphs){var a=assignments[p.Occurrence.Id];p.SceneId=a.SceneId;p.ChapterId=a.ChapterId;p.PositionVerified=a.PositionVerified;}RefreshEvidence(state);Validate(state);
|
||||
}
|
||||
public static StoryEvidence Anchor(ParagraphManuscript state,string kind,int eventId,bool primary,int from,int to,int? startOffset,int? endOffset)
|
||||
{
|
||||
if(kind is not ("Knowledge" or "Relationship")||eventId<=0)throw new ArgumentException("Choose a saved event.");var rows=state.Paragraphs.Where(p=>p.Occurrence.Ordinal>=from&&p.Occurrence.Ordinal<=to).ToArray();
|
||||
if(rows.Length==0||to<from||rows.Length!=to-from+1||rows.Any(p=>!p.Story||!p.PositionVerified))throw new ArgumentException("Choose a reliably mapped story passage.");
|
||||
var evidence=new StoryEvidence{EventKind=kind,EventId=eventId,Primary=primary,StartParagraph=rows[0].Occurrence.Id,EndParagraph=rows[^1].Occurrence.Id,StartOffset=startOffset,EndOffset=endOffset};
|
||||
evidence.CurrentText=Text(state,evidence)??throw new ArgumentException("Passage offsets are outside the selected text.");if(evidence.CurrentText.Length==0||evidence.CurrentText.Length>100000)throw new ArgumentException("Choose a passage of up to 100,000 characters.");
|
||||
evidence.OriginalText=evidence.ConfirmedText=evidence.CurrentText;if(primary)foreach(var old in state.Evidence.Where(e=>e.EventKind==kind&&e.EventId==eventId))old.Primary=false;
|
||||
state.Evidence.Add(evidence);state.Undo.Clear();RefreshEvidence(state);evidence.OriginalPosition=evidence.CurrentPosition;return evidence;
|
||||
}
|
||||
public static void Confirm(ParagraphManuscript state,Guid evidence)
|
||||
{
|
||||
var item=state.Evidence.Single(e=>e.Id==evidence);var text=Text(state,item)??throw new ArgumentException("Relink missing evidence first.");
|
||||
var start=state.Paragraphs.Single(p=>p.Occurrence.Id==item.StartParagraph);if(!start.PositionVerified)throw new ArgumentException("Resolve the scene boundary before confirming evidence.");item.ConfirmedText=text;state.Undo.Clear();RefreshEvidence(state);
|
||||
}
|
||||
public static string? Text(ParagraphManuscript state,StoryEvidence anchor,IReadOnlyDictionary<Guid,int>? positions=null)
|
||||
{
|
||||
int a=positions==null?state.Paragraphs.FindIndex(p=>p.Occurrence.Id==anchor.StartParagraph):positions.GetValueOrDefault(anchor.StartParagraph,-1),b=positions==null?state.Paragraphs.FindIndex(p=>p.Occurrence.Id==anchor.EndParagraph):positions.GetValueOrDefault(anchor.EndParagraph,-1);if(a<0||b<a)return null;
|
||||
var rows=state.Paragraphs.Skip(a).Take(b-a+1).ToArray();int start=anchor.StartOffset??0,end=anchor.EndOffset??rows[^1].Occurrence.Text.Length;
|
||||
if(start<0||start>rows[0].Occurrence.Text.Length||end<0||end>rows[^1].Occurrence.Text.Length||(rows.Length==1&&end<start))return null;
|
||||
return rows.Length==1?rows[0].Occurrence.Text.Substring(start,end-start):rows[0].Occurrence.Text[start..]+string.Concat(rows.Skip(1).Take(rows.Length-2).Select(p=>p.Occurrence.Text))+rows[^1].Occurrence.Text[..end];
|
||||
}
|
||||
public static void RefreshEvidence(ParagraphManuscript state)
|
||||
{
|
||||
var positions=state.Paragraphs.Select((p,i)=>(p.Occurrence.Id,i)).ToDictionary(p=>p.Id,p=>p.i);var byId=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var scenes=state.Scenes.ToDictionary(s=>s.Id);
|
||||
foreach(var e in state.Evidence){var current=Text(state,e,positions);var paragraph=byId.GetValueOrDefault(e.StartParagraph);if(e.CurrentScene!=paragraph?.SceneId){e.PreviousScene=e.CurrentScene;e.PreviousPosition=e.CurrentPosition;}
|
||||
e.CurrentText=current??"";e.CurrentScene=paragraph?.SceneId;e.CurrentPosition=paragraph==null?"Paragraph missing":$"Paragraph {paragraph.Occurrence.Ordinal+1} · { (paragraph.SceneId.HasValue&&scenes.TryGetValue(paragraph.SceneId.Value,out var scene)?scene.Title:"Scene needs review") }";
|
||||
e.State=current==null?"Missing":current!=e.ConfirmedText||paragraph?.PositionVerified!=true||!RangeVerified(state,e,positions)?"Needs review":"Verified";
|
||||
e.DerivedSceneId=e.State=="Verified"&&e.CurrentScene.HasValue?scenes[e.CurrentScene.Value].CanonicalId:null;
|
||||
}
|
||||
}
|
||||
private static bool RangeVerified(ParagraphManuscript state,StoryEvidence evidence,IReadOnlyDictionary<Guid,int> positions){int a=positions.GetValueOrDefault(evidence.StartParagraph,-1),b=positions.GetValueOrDefault(evidence.EndParagraph,-1);return a>=0&&b>=a&&state.Paragraphs.Skip(a).Take(b-a+1).All(p=>p.PositionVerified);}
|
||||
public static void Validate(ParagraphManuscript state)
|
||||
{
|
||||
if(state.Paragraphs.Count>100000||state.Evidence.Count>10000||state.Scenes.Count>10000||state.Evidence.Sum(e=>(long)e.OriginalText.Length+e.ConfirmedText.Length+e.CurrentText.Length)>8*1024*1024)throw new ArgumentException("Manuscript structure exceeds limits.");
|
||||
if(state.Evidence.Any(e=>e.Id==Guid.Empty)||state.Evidence.Select(e=>e.Id).Distinct().Count()!=state.Evidence.Count)throw new ArgumentException("Duplicate or empty evidence identities.");
|
||||
if(state.Paragraphs.Any(p=>p.Occurrence.Id==Guid.Empty)||state.Scenes.Any(s=>s.Id==Guid.Empty)||state.Paragraphs.Select(p=>p.Occurrence.Id).Distinct().Count()!=state.Paragraphs.Count||state.Scenes.Select(s=>s.Id).Distinct().Count()!=state.Scenes.Count)throw new ArgumentException("Duplicate manuscript identities.");
|
||||
var scenes=state.Scenes.Where(s=>!s.Retired).ToDictionary(s=>s.Id);if(state.Paragraphs.Any(p=>p.Story&&(!p.SceneId.HasValue||!scenes.ContainsKey(p.SceneId.Value))))throw new ArgumentException("Every story paragraph must belong to one current scene.");
|
||||
var completed=new HashSet<Guid>();Guid? last=null;foreach(var p in state.Paragraphs.Where(p=>p.Story)){if(p.SceneId!=last){if(p.SceneId.HasValue&&completed.Contains(p.SceneId.Value))throw new ArgumentException("Scene groups must be contiguous.");if(last.HasValue)completed.Add(last.Value);last=p.SceneId;}}
|
||||
}
|
||||
}
|
||||
103
PlotLine/Services/Manuscript/ParagraphManuscriptService.cs
Normal file
103
PlotLine/Services/Manuscript/ParagraphManuscriptService.cs
Normal file
@ -0,0 +1,103 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.Manuscript;
|
||||
public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository repository,IWordCompanionRepository access,IBookRepository books,IOnboardingBuildRepository imports,IManuscriptTextStatisticsService statistics,IConfiguration configuration,ILogger<ParagraphManuscriptService>? logger=null)
|
||||
{
|
||||
public bool Enabled=>configuration.GetValue<bool>("Features:ParagraphManuscripts");
|
||||
private void RequireFeature(){if(!Enabled)throw new InvalidOperationException("Paragraph synchronisation is not enabled on this server.");}
|
||||
public async Task<ParagraphWorkspaceModel> Workspace(int user,int book,int page=1)
|
||||
{
|
||||
RequireFeature();if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();var title=await books.GetAsync(book)??throw new ArgumentException("Book not found.");
|
||||
var state=await repository.Get(user,book)??new(){BookId=book,ProjectId=title.ProjectID};ParagraphManuscriptEngine.RefreshEvidence(state);
|
||||
return new(){State=state,BookTitle=title.BookDisplayTitle,Events=await repository.Events(user,book),Page=Math.Max(1,page)};
|
||||
}
|
||||
public async Task<ParagraphManuscript> Enable(int user,int book,string mode)
|
||||
{
|
||||
RequireFeature();if(mode is not ("Manual" or "OnSave" or "Off"))throw new ArgumentException("Choose manual or save/reconnect synchronisation.");
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();var current=await repository.Get(user,book);
|
||||
if(current!=null)return await repository.SetMode(user,book,current.Revision,mode);
|
||||
var source=await repository.Capture(user,book)??throw new InvalidOperationException("Finish a native manuscript import first. No existing book data was changed.");
|
||||
var bookRow=await books.GetAsync(book)??throw new ArgumentException("Book no longer exists.");var sceneSources=await imports.ListSceneManuscriptSourcesByBookAsync(book);
|
||||
return await Initialise(user,source,sceneSources,bookRow.ProjectID,mode);
|
||||
}
|
||||
public async Task<ParagraphManuscript> Initialise(int user,ManuscriptScanPreview source,IReadOnlyList<SceneManuscriptSourceRecord> sceneSources,int project,string mode="Manual")
|
||||
{
|
||||
RequireFeature();var prior=await repository.Get(user,source.BookID);if(prior!=null)return prior;
|
||||
if(!Guid.TryParse(source.CompanionDocumentIdentifier,out var manuscript)||manuscript==Guid.Empty||source.NativeParagraphPositions.Count==0)throw new InvalidOperationException("The accepted capture lacks native document provenance. Existing manuscript data is unchanged.");
|
||||
var paragraphs=ParagraphReconciliation.Compare([],source.ParagraphTracking&&source.NativeParagraphs!=null?source.NativeParagraphs:LegacyParagraphs(source)).Current;
|
||||
var completed=await imports.GetByPreviewAsync(user,source.PreviewID)??throw new InvalidOperationException("Finish the accepted manuscript build before enabling tracking.");
|
||||
if(completed.BookID!=source.BookID||completed.ProjectID!=project)throw new UnauthorizedAccessException();
|
||||
var mapped=completed.SceneMappings.Select(s=>s.SceneID).ToHashSet();
|
||||
var limits=new List<ParagraphBootstrapScene>();var ordered=sceneSources.Where(s=>mapped.Contains(s.SceneID)&&s.WordStartParagraphIndex.HasValue).OrderBy(s=>s.WordStartParagraphIndex).ToArray();
|
||||
if(ordered.Length!=mapped.Count)throw new InvalidOperationException("The accepted build does not have a complete canonical scene map. No unrelated scene sources were adopted.");
|
||||
if(ordered.Length==0)throw new InvalidOperationException("Imported scenes have no reversible paragraph map. No paragraph mapping was guessed.");
|
||||
if(source.Chapters.Any(c=>!c.StartPosition.HasValue))throw new InvalidOperationException("The accepted capture has an incomplete chapter map.");
|
||||
var sourceChapters=source.Chapters.OrderBy(c=>c.StartPosition).ToArray();
|
||||
var bindings=new List<ParagraphChapter>();
|
||||
foreach(var chapter in ordered.GroupBy(s=>s.ChapterID)){
|
||||
var scenes=chapter.OrderBy(s=>s.WordStartParagraphIndex).ToArray();var firstWord=scenes[0].WordStartParagraphIndex!.Value;
|
||||
var section=Array.FindLastIndex(sourceChapters,c=>c.StartPosition<=firstWord);if(section<0)throw new InvalidOperationException("The accepted chapter has no reversible source section.");
|
||||
var start=sourceChapters[section].StartPosition!.Value;var end=section+1<sourceChapters.Length?sourceChapters[section+1].StartPosition!.Value-1:paragraphs.Length;
|
||||
if(start<1||start>paragraphs.Length||scenes.Any(s=>s.WordStartParagraphIndex>end))throw new InvalidOperationException("Chapter source sections overlap. Existing manuscript is unchanged.");
|
||||
bindings.Add(new(){CanonicalId=chapter.Key,HeadingId=paragraphs[start-1].Id,Title=sourceChapters[section].Title});
|
||||
for(int n=0;n<scenes.Length;n++){var scene=scenes[n];limits.Add(new(){SceneId=scene.SceneID,ChapterId=scene.ChapterID,Title=scene.SceneTitle??"Scene",Start=n==0?start+(paragraphs[start-1].Outline==1?1:0):scene.WordStartParagraphIndex!.Value,End=n+1<scenes.Length?scenes[n+1].WordStartParagraphIndex!.Value-1:end,NeedsRefinement=scene.SourceKind=="StructuralFallback"});}
|
||||
}
|
||||
foreach(var chapter in sourceChapters.Where(c=>c.StartPosition>=1&&c.StartPosition<=paragraphs.Length&&bindings.All(b=>b.HeadingId!=paragraphs[c.StartPosition!.Value-1].Id)))bindings.Add(new(){CanonicalId=0,HeadingId=paragraphs[chapter.StartPosition!.Value-1].Id,Title=chapter.Title});
|
||||
if(bindings.Select(b=>b.HeadingId).Distinct().Count()!=bindings.Count)throw new InvalidOperationException("Multiple canonical chapters share one captured section. Review their association before enabling tracking; no manuscript was changed.");
|
||||
var state=ParagraphManuscriptEngine.Bootstrap(source.BookID,project,manuscript,paragraphs,limits);state.Chapters=bindings;foreach(var heading in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){var binding=bindings.FirstOrDefault(b=>b.HeadingId==heading.Occurrence.Id);heading.ChapterId=binding?.CanonicalId>0?binding.CanonicalId:null;heading.PositionVerified=heading.ChapterId.HasValue;}
|
||||
state.DocumentName=source.DocumentTitle??"Word manuscript";state.Mode=mode;state.SessionId=source.NativeSessionID??Guid.Empty;state.WordRevision=source.NativeRevision??0;
|
||||
state.EventPositions=(await repository.Events(user,source.BookID)).ToList();return await repository.Save(user,state,-1,source.PreviewID);
|
||||
}
|
||||
public static ParagraphOccurrence[] LegacyParagraphs(ManuscriptScanPreview source)
|
||||
{
|
||||
var rows=source.Chapters.SelectMany(c=>c.SourceParagraphs).OrderBy(p=>p.WordParagraphIndex).ToArray();
|
||||
if(rows.Select(p=>p.WordParagraphIndex).Distinct().Count()!=rows.Length||rows.Select(p=>p.WordParagraphIndex).Where((p,i)=>p!=i+1).Any())throw new InvalidOperationException("The accepted source does not contain every original paragraph in order. No identities were guessed.");
|
||||
return rows.Select((p,i)=>new ParagraphOccurrence{Ordinal=i,Text=p.Text,Outline=p.IsChapterHeading?1:p.IsSceneHeading?2:10,Start=source.NativeParagraphPositions[p.WordParagraphIndex],End=i+1<rows.Length?source.NativeParagraphPositions[rows[i+1].WordParagraphIndex]:source.NativeDocumentEnd}).ToArray();
|
||||
}
|
||||
public async Task<ParagraphManuscript> Snapshot(int user,int book,ManuscriptCapture capture,long expected)
|
||||
{
|
||||
RequireFeature();var state=await repository.Get(user,book)??throw new InvalidOperationException("Enable paragraph tracking for this book first.");
|
||||
if(state.LastRequestId==capture.RequestId)return state;
|
||||
if(state.Revision!=expected)throw new InvalidOperationException("Manuscript changed during capture. Refresh and request a new snapshot.");
|
||||
if(state.ManuscriptId!=capture.ManuscriptId)throw new InvalidOperationException("This is a different Word manuscript. Import it into a separate book; existing evidence is not guessed across documents.");
|
||||
var rows=capture.Delta==null?ParagraphReconciliation.Assemble(capture.Paragraphs,capture.End):capture.Delta.BaseRevision!=expected?throw new InvalidOperationException("Delta base revision changed."):ParagraphDeltaCodec.Expand(capture.Delta,state.Paragraphs.Select(p=>p.Occurrence).ToArray(),capture.End);
|
||||
if(capture.Delta==null&&capture.ParagraphIds!=null){if(capture.ParagraphIds.Length!=rows.Length||capture.ParagraphIds.Any(id=>id==Guid.Empty)||capture.ParagraphIds.Distinct().Count()!=rows.Length)throw new ArgumentException("Invalid paragraph occurrence IDs.");for(int n=0;n<rows.Length;n++)rows[n].Id=capture.ParagraphIds[n];}state.EventPositions=(await repository.Events(user,book)).ToList();
|
||||
state.Evidence.RemoveAll(e=>state.EventPositions.All(a=>a.Kind!=e.EventKind||a.Id!=e.EventId));
|
||||
ParagraphManuscriptEngine.Reconcile(state,rows);state.ManuscriptId=capture.ManuscriptId;state.SessionId=capture.SessionId;state.WordRevision=capture.Revision;
|
||||
return await Save(user,state,expected,capture.RequestId);
|
||||
}
|
||||
public async Task<ParagraphManuscript> Change(int user,int book,long expected,string action,Guid target=default,Guid other=default,string? text=null,string? kind=null,int eventId=0,bool primary=true,int from=0,int to=0,int? startOffset=null,int? endOffset=null)
|
||||
{
|
||||
RequireFeature();var state=await repository.Get(user,book)??throw new ArgumentException("Enable paragraph tracking first.");if(state.Revision!=expected)throw new InvalidOperationException("The manuscript changed. Refresh before making this change.");
|
||||
var actual=(await repository.Events(user,book)).ToList();
|
||||
if(action=="undo"&&state.EventPositions.Any(saved=>actual.All(e=>e.Kind!=saved.Kind||e.Id!=saved.Id||e.SceneId!=saved.SceneId)))throw new InvalidOperationException("Saved event positions changed after this layout. Review boundaries instead of undoing over newer decisions.");
|
||||
if(action!="undo")state.EventPositions=actual;
|
||||
switch(action){
|
||||
case "group":ParagraphManuscriptEngine.ConfirmGrouping(state,target);break;
|
||||
case "split":ParagraphManuscriptEngine.Split(state,target,text??"");break;
|
||||
case "boundary":ParagraphManuscriptEngine.MoveBoundary(state,target,other);break;
|
||||
case "merge":ParagraphManuscriptEngine.Merge(state,target,other);break;
|
||||
case "undo":ParagraphManuscriptEngine.Undo(state);break;
|
||||
case "confirm":ParagraphManuscriptEngine.Confirm(state,target);break;
|
||||
case "anchor":
|
||||
if(!actual.Any(e=>e.Kind==kind&&e.Id==eventId))throw new UnauthorizedAccessException();ParagraphManuscriptEngine.Anchor(state,kind!,eventId,primary,from,to,startOffset,endOffset);break;
|
||||
case "relink":
|
||||
var old=state.Evidence.Single(e=>e.Id==target);if(!actual.Any(e=>e.Kind==old.EventKind&&e.Id==old.EventId))throw new UnauthorizedAccessException();state.Evidence.Remove(old);
|
||||
var next=ParagraphManuscriptEngine.Anchor(state,old.EventKind,old.EventId,old.Primary,from,to,startOffset,endOffset);next.Id=old.Id;next.OriginalText=old.OriginalText;next.OriginalPosition=old.OriginalPosition;next.PreviousPosition=old.CurrentPosition;break;
|
||||
case "unlink":state.Evidence.RemoveAll(e=>e.Id==target);state.Undo.Clear();break;
|
||||
default:throw new ArgumentException("Unknown manuscript action.");
|
||||
}
|
||||
// Explicitly removed events from the established editors are not recreated by synchronisation.
|
||||
state.Evidence.RemoveAll(e=>actual.All(a=>a.Kind!=e.EventKind||a.Id!=e.EventId));ParagraphManuscriptEngine.RefreshEvidence(state);return await Save(user,state,expected,Guid.NewGuid());
|
||||
}
|
||||
private async Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request)
|
||||
{
|
||||
ParagraphManuscriptEngine.Validate(state);var result=await repository.Save(user,state,expected,request);
|
||||
// Reuse deterministic continuity/statistics; never schedule whole-book AI.
|
||||
try{await statistics.RecalculateBookAsync(state.BookId);}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or InvalidOperationException){logger?.LogWarning("Manuscript revision {Revision} committed; derived statistics require refresh ({FailureKind}).",result.Revision,e.GetType().Name);}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -305,7 +305,7 @@ public sealed class ManuscriptScanPreviewStore(
|
||||
OnboardingID = preview.OnboardingID,
|
||||
ProjectID = preview.ProjectID,
|
||||
BookID = preview.BookID,
|
||||
Source = preview.Source,NativeInstanceID=preview.NativeInstanceID,NativeSessionID=preview.NativeSessionID,NativeRevision=preview.NativeRevision,NativeDocumentEnd=preview.NativeDocumentEnd,NativeParagraphPositions=preview.NativeParagraphPositions,
|
||||
ParagraphTracking=preview.ParagraphTracking,NativeParagraphs=preview.NativeParagraphs,Source = preview.Source,NativeInstanceID=preview.NativeInstanceID,NativeSessionID=preview.NativeSessionID,NativeRevision=preview.NativeRevision,NativeDocumentEnd=preview.NativeDocumentEnd,NativeParagraphPositions=preview.NativeParagraphPositions,
|
||||
DocumentTitle = preview.DocumentTitle,
|
||||
CompanionDocumentIdentifier = preview.CompanionDocumentIdentifier,
|
||||
TotalWordCount = preview.TotalWordCount,
|
||||
@ -479,7 +479,7 @@ file static class ManuscriptScanPreviewExtensions
|
||||
OnboardingID = preview.OnboardingID,
|
||||
ProjectID = preview.ProjectID,
|
||||
BookID = preview.BookID,
|
||||
Source = preview.Source,NativeInstanceID=preview.NativeInstanceID,NativeSessionID=preview.NativeSessionID,NativeRevision=preview.NativeRevision,NativeDocumentEnd=preview.NativeDocumentEnd,NativeParagraphPositions=preview.NativeParagraphPositions,
|
||||
ParagraphTracking=preview.ParagraphTracking,NativeParagraphs=preview.NativeParagraphs,Source = preview.Source,NativeInstanceID=preview.NativeInstanceID,NativeSessionID=preview.NativeSessionID,NativeRevision=preview.NativeRevision,NativeDocumentEnd=preview.NativeDocumentEnd,NativeParagraphPositions=preview.NativeParagraphPositions,
|
||||
DocumentTitle = preview.DocumentTitle,
|
||||
CompanionDocumentIdentifier = preview.CompanionDocumentIdentifier,
|
||||
TotalWordCount = preview.TotalWordCount,
|
||||
|
||||
@ -46,11 +46,12 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
|
||||
try
|
||||
{
|
||||
var promptVersion = versions.GetPromptVersion(ChapterPromptFile);
|
||||
var promptFile = request.ConfidenceContractVersion == 2 ? "Chapter-Structure-Prompt-V3.md" : ChapterPromptFile;
|
||||
var promptVersion = versions.GetPromptVersion(promptFile);
|
||||
var clientStatus = client.GetConfigurationStatus();
|
||||
var template = await prompts.LoadPromptAsync(ChapterPromptFile, cancellationToken);
|
||||
var template = await prompts.LoadPromptAsync(promptFile, cancellationToken);
|
||||
var prompt = BuildChapterPrompt(template, BuildChapterContextJson(request,paragraphs.Count), StoryIntelligenceParagraphs.Number(paragraphs));
|
||||
var result = await client.ExecutePromptAsync(prompt, promptVersion, cancellationToken, clientStatus.ChapterStructureModel);
|
||||
var result = await client.ExecutePromptAsync(prompt, promptVersion, cancellationToken, clientStatus.ChapterStructureModel,responseContract:request.ConfidenceContractVersion==2?Manuscript.ChapterStructureIntegerContract.ForParagraphCount(paragraphs.Count):null);
|
||||
var chapterJson = ExtractOutputText(result.RawResponseText);
|
||||
var parseResult = StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(chapterJson, JsonOptions);
|
||||
if (!parseResult.Success)
|
||||
@ -60,7 +61,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
prompt,
|
||||
parseResult.ErrorMessage ?? parseResult.InitialErrorMessage ?? "Chapter Structure JSON could not be parsed.",
|
||||
chapterJson);
|
||||
var retryResult = await client.ExecutePromptAsync(retryPrompt, promptVersion, cancellationToken, clientStatus.ChapterStructureModel);
|
||||
var retryResult = await client.ExecutePromptAsync(retryPrompt, promptVersion, cancellationToken, clientStatus.ChapterStructureModel,responseContract:request.ConfidenceContractVersion==2?Manuscript.ChapterStructureIntegerContract.ForParagraphCount(paragraphs.Count):null);
|
||||
var retryJson = ExtractOutputText(retryResult.RawResponseText);
|
||||
var retryParseResult = StoryIntelligenceAiJsonParser.Parse<ChapterStructureModel>(retryJson, JsonOptions);
|
||||
if (!retryParseResult.Success)
|
||||
@ -94,8 +95,12 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
}
|
||||
|
||||
var parsed = parseResult.Parsed;
|
||||
// Do not let the legacy continuity normaliser turn an out-of-range proposal into trusted AI output.
|
||||
if(parsed?.SceneBoundaries?.Any(b=>b.StartParagraph<1||b.EndParagraph<1||b.EndParagraph>paragraphs.Count)==true)
|
||||
return ManuscriptStructureAnalysisResult.Failed(request.TemporaryChapterKey,$"Scene proposal is outside submitted structural paragraphs 1..{paragraphs.Count}. {BuildBoundaryDiagnostic(parsed,request.ParagraphMap,paragraphs.Count)}",parseResult.RawJson);
|
||||
var normalisation = ChapterStructureBoundaryNormaliser.Normalise(parsed, paragraphs.Count);
|
||||
var chapter = normalisation.ChapterStructure;
|
||||
if(request.ConfidenceContractVersion==2 && chapter?.SchemaVersion!="2.0") return ManuscriptStructureAnalysisResult.Failed(request.TemporaryChapterKey,"Expected integer-confidence schema 2.0.",parseResult.RawJson);
|
||||
var explicitPov = DetectExplicitNarrator(text);
|
||||
var validation = validator.Validate(chapter, paragraphs.Count);
|
||||
ChapterStructureBoundaryNormaliser.AddIssuesTo(validation, normalisation);
|
||||
@ -164,8 +169,8 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
var sceneParagraphs = paragraphs.Skip(start - 1).Take(end - start + 1).ToList();
|
||||
var sourceText = BuildSourceText(request.SourceParagraphs, startMap.WordParagraphIndex, endMap.WordParagraphIndex);
|
||||
var suggestedTitle = CleanSuggestedTitle(boundary.SuggestedTitle, sceneNumber);
|
||||
var aiDefaultPov = CleanPovSuggestion(chapter.DefaultPov);
|
||||
var pov = CleanPovSuggestion(boundary.PovOverride) ?? explicitPov ?? aiDefaultPov;
|
||||
var aiDefaultPov = CleanPovSuggestion(chapter.DefaultPov, chapter.SchemaVersion == "2.0");
|
||||
var pov = CleanPovSuggestion(boundary.PovOverride, chapter.SchemaVersion == "2.0") ?? explicitPov ?? aiDefaultPov;
|
||||
scenes.Add(new ManuscriptStructureSceneBoundary
|
||||
{
|
||||
TemporarySceneKey = $"{request.TemporaryChapterKey}-ai-scene-{sceneNumber}",
|
||||
@ -181,7 +186,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
StructuralSummary = Trim(boundary.StructuralSummary, 600),
|
||||
StructuralSetting = Trim(boundary.StructuralSetting, 300),
|
||||
Reason = boundary.Reason,
|
||||
Confidence = boundary.Confidence,
|
||||
Confidence = chapter.SchemaVersion == "2.0" ? boundary.Confidence / 100m : boundary.Confidence,
|
||||
SuggestedPovName = pov?.CharacterName,
|
||||
SuggestedPovConfidence = pov?.Confidence,
|
||||
SuggestedPovEvidence = pov?.Evidence,
|
||||
@ -191,7 +196,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
});
|
||||
}
|
||||
|
||||
var rawPov = CleanPovSuggestion(chapter.DefaultPov);
|
||||
var rawPov = CleanPovSuggestion(chapter.DefaultPov, chapter.SchemaVersion == "2.0");
|
||||
if (!request.PrivateAnalysis) logger.LogInformation(
|
||||
"Structural POV audit. ProjectID={ProjectID} BookID={BookID} PreviewID={PreviewID} TemporaryChapterKey={TemporaryChapterKey} ExplicitNarrator={ExplicitNarrator} AiDefaultPov={AiDefaultPov} MixedPov={MixedPov} RawStructuralJson={RawStructuralJson}",
|
||||
request.ProjectID,
|
||||
@ -210,7 +215,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
request.TemporaryChapterKey,
|
||||
scenes.Count);
|
||||
|
||||
var defaultPov = explicitPov ?? CleanPovSuggestion(chapter.DefaultPov);
|
||||
var defaultPov = explicitPov ?? CleanPovSuggestion(chapter.DefaultPov, chapter.SchemaVersion == "2.0");
|
||||
return ManuscriptStructureAnalysisResult.Succeeded(
|
||||
request.TemporaryChapterKey,
|
||||
scenes,
|
||||
@ -631,7 +636,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
return wordCount is >= 2 and <= 6 ? clean : null;
|
||||
}
|
||||
|
||||
private static ChapterStructurePovSuggestion? CleanPovSuggestion(ChapterStructurePovSuggestion? suggestion)
|
||||
private static ChapterStructurePovSuggestion? CleanPovSuggestion(ChapterStructurePovSuggestion? suggestion, bool integerScale=false)
|
||||
{
|
||||
var name = Trim(suggestion?.CharacterName, 120);
|
||||
if (string.IsNullOrWhiteSpace(name)
|
||||
@ -644,7 +649,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
return new ChapterStructurePovSuggestion
|
||||
{
|
||||
CharacterName = name,
|
||||
Confidence = suggestion?.Confidence,
|
||||
Confidence = integerScale ? suggestion?.Confidence / 100m : suggestion?.Confidence,
|
||||
Evidence = Trim(suggestion?.Evidence, 400),
|
||||
IsExplicit = suggestion?.IsExplicit
|
||||
};
|
||||
@ -704,6 +709,8 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
|
||||
public sealed class ManuscriptStructureAnalysisRequest
|
||||
{
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition=System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public int ConfidenceContractVersion {get;init;}
|
||||
public bool PrivateAnalysis { get; init; }
|
||||
public int ProjectID { get; init; }
|
||||
public int BookID { get; init; }
|
||||
|
||||
@ -2,22 +2,25 @@ using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
|
||||
// Short-lived transfer authorisation, issued only by the authenticated existing import wizard.
|
||||
// Prose acceptance is durable through IManuscriptScanPreviewStore, not through this dictionary.
|
||||
public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes)
|
||||
public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes,IConfiguration? configuration=null)
|
||||
{
|
||||
private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null);
|
||||
private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null,bool Paragraphs=false,bool Sync=false,long BaseRevision=-1,ManuscriptScanPreview? Prepared=null,ParagraphManuscript? AcceptedSnapshot=null);
|
||||
private readonly ConcurrentDictionary<Guid,Pending> pending=new();
|
||||
private readonly SemaphoreSlim acceptance=new(1,1);
|
||||
public async Task<ManuscriptScanState?> Start(int user,int onboarding,int project,int book)
|
||||
public async Task<ManuscriptScanState?> Start(int user,int onboarding,int project,int book,bool paragraphs=false)
|
||||
{
|
||||
await acceptance.WaitAsync();try{
|
||||
if(paragraphs&&configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled on this server.");
|
||||
using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IWordCompanionRepository>();
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new InvalidOperationException("The selected book is not accessible.");
|
||||
foreach(var expired in pending.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _);
|
||||
var all=presence.Read(user,0).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture).ToArray();
|
||||
var all=presence.Read(user,0).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture&&(!paragraphs||l.Position.CanParagraphSync)).ToArray();
|
||||
var linked=all.Where(l=>l.Position.BookId==book).ToArray();
|
||||
var documents=linked.Length>0?linked:all.Where(l=>l.Position.BookId==0).ToArray();
|
||||
if(linked.Length==0&&documents.Length>0&&all.Any(l=>l.Position.Active&&l.Position.BookId>0&&l.Position.BookId!=book))
|
||||
@ -28,22 +31,64 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
if(pending.Values.Any(p=>p.User==user&&p.Hash==null))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying.");
|
||||
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later.");
|
||||
var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value;
|
||||
pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20));
|
||||
if(!presence.RequestCapture(user,selected,id,book)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");}
|
||||
pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:paragraphs);
|
||||
if(!presence.RequestCapture(user,selected,id,book,paragraphs)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");}
|
||||
return state;
|
||||
}finally{acceptance.Release();}
|
||||
}
|
||||
public async Task<ParagraphPosition?> ResolveParagraphPosition(int user,int book,Guid manuscript,Guid session,long revision,int position){if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)return null;using var scope=scopes.CreateScope();return await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Position(user,book,manuscript,session,revision,position);}
|
||||
public async Task CancelParagraphSnapshot(int user,int book){using var scope=scopes.CreateScope();var status=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();foreach(var item in pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Hash==null).ToArray()){presence.RequestCancellation(user,item.Value.Lease);await Fail(user,item.Value.Lease.Grant,item.Key);}}
|
||||
private readonly Dictionary<(int,Guid,Guid),DateTimeOffset> autoChecks=[];
|
||||
public async Task<Guid> RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null)
|
||||
{
|
||||
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled.");
|
||||
await acceptance.WaitAsync();try{
|
||||
using var scope=scopes.CreateScope();var repository=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>();
|
||||
var status=await repository.Status(user,book)??throw new InvalidOperationException("Enable paragraph tracking for this book first.");
|
||||
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("The existing book import is still active. Synchronisation is paused to protect it.");
|
||||
var documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanParagraphSync).ToArray();
|
||||
if(automatic!=null&&(status.Mode!="OnSave"||documents.Length!=1||!automatic.Position.WordSaved.GetValueOrDefault()||(status.SessionId==automatic.Session&&status.WordRevision==automatic.Position.Revision)))return Guid.Empty;
|
||||
var active=documents.Where(l=>l.Position.Active).ToArray();var selected=automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected."));
|
||||
if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This is a different document. Import a different manuscript into a separate book; automatic cross-document evidence matching is refused.");
|
||||
if(pending.Values.Any(p=>p.User==user&&p.Hash==null))return Guid.Empty;
|
||||
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfer capacity is busy.");var id=Guid.NewGuid();
|
||||
pending[id]=new(user,0,0,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:true,Sync:true,BaseRevision:status.Revision);
|
||||
if(!presence.RequestCapture(user,selected,id,book,true,true,status.Revision,status.SnapshotHash)){pending.TryRemove(id,out _);throw new InvalidOperationException("Word changed or is busy. Request a fresh snapshot.");}return id;
|
||||
}finally{acceptance.Release();}
|
||||
}
|
||||
public async Task ObserveParagraphSave(int user,NativeLease lease)
|
||||
{
|
||||
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true||!lease.Position.CanParagraphSync||lease.Position.BookId<=0||lease.Position.WordSaved!=true)return;
|
||||
var key=(user,lease.Instance,lease.Session);lock(autoChecks){var now=clock.GetUtcNow();if(autoChecks.TryGetValue(key,out var after)&&now<after)return;if(autoChecks.Count>=256)autoChecks.Clear();autoChecks[key]=now.AddSeconds(15);}
|
||||
try{await RequestParagraphSnapshot(user,lease.Position.BookId,automatic:lease);}catch(Exception e)when(e is InvalidOperationException or UnauthorizedAccessException or Microsoft.Data.SqlClient.SqlException){/* Paused/unauthorised books never trigger a transfer. */}
|
||||
}
|
||||
public Guid[]? AcceptedParagraphIds(int user,Guid request)=>pending.TryGetValue(request,out var value)&&value.User==user?value.Prepared?.NativeParagraphs?.Select(p=>p.Id).ToArray():null;
|
||||
public Task<ParagraphManuscript> AcceptedParagraphState(int user,Guid id){if(!pending.TryGetValue(id,out var request)||request.User!=user||!request.Sync||request.Hash==null||request.AcceptedSnapshot==null)throw new UnauthorizedAccessException();return Task.FromResult(request.AcceptedSnapshot);}
|
||||
public async Task<bool> AcceptParagraphSnapshot(int user,string grant,ManuscriptCapture capture)
|
||||
{
|
||||
await acceptance.WaitAsync();try{
|
||||
if(!pending.TryGetValue(capture.RequestId,out var request)||!request.Sync)return false;
|
||||
if(request.User!=user||request.Lease.Grant!=grant||request.Expires<=clock.GetUtcNow()||!capture.ParagraphTracking||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException();
|
||||
var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture)));
|
||||
if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Snapshot retry has different contents.");return true;}
|
||||
using var scope=scopes.CreateScope();var accepted=await scope.ServiceProvider.GetRequiredService<ParagraphManuscriptService>().Snapshot(user,request.Book,capture,request.BaseRevision);
|
||||
presence.BooksChanged(user);
|
||||
pending[capture.RequestId]=request with{Hash=hash,AcceptedSnapshot=new ParagraphManuscript{BookId=accepted.BookId,Revision=accepted.Revision,SnapshotHash=accepted.SnapshotHash,Paragraphs=accepted.Paragraphs.Select(p=>new StoryParagraph{Occurrence=new ParagraphOccurrence{Id=p.Occurrence.Id}}).ToList()}};return true;
|
||||
}finally{acceptance.Release();}
|
||||
}
|
||||
public async Task<ManuscriptScanState> Accept(int user,string grant,ManuscriptCapture capture)
|
||||
{
|
||||
await acceptance.WaitAsync();try{
|
||||
if(!pending.TryGetValue(capture.RequestId,out var request)||request.Expires<=clock.GetUtcNow()||request.User!=user||request.Lease.Grant!=grant||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException();
|
||||
if(!pending.TryGetValue(capture.RequestId,out var request)||request.Sync||request.Paragraphs!=capture.ParagraphTracking||request.Expires<=clock.GetUtcNow()||request.User!=user||request.Lease.Grant!=grant||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException();
|
||||
using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IWordCompanionRepository>();var onboardingState=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IOnboardingRepository>();
|
||||
var current=await onboardingState.GetAsync(user);
|
||||
if(current==null||current.UserOnboardingStateID!=request.Onboarding||current.ProjectID!=request.Project||current.BookID!=request.Book)throw new UnauthorizedAccessException();
|
||||
var structure=await access.GetBookStructureAsync(request.Book,user)??throw new UnauthorizedAccessException();
|
||||
var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture)));
|
||||
if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Capture identity conflict. Start a new transfer.");return await scans.GetStateAsync(user,request.Onboarding);}
|
||||
var preview=Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure);
|
||||
var preview=request.Prepared??Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure);
|
||||
// Reuse server-minted occurrence IDs if a durable write succeeds but its acknowledgement is lost.
|
||||
pending[capture.RequestId]=request=request with{Prepared=preview};
|
||||
var state=await scans.CompleteAsync(user,preview);
|
||||
pending[capture.RequestId]=request with{Hash=hash};
|
||||
// Retain request until expiry for idempotent same-ID retransmission; no import is committed here.
|
||||
@ -52,7 +97,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
}
|
||||
public async Task<ManuscriptScanState?> Progress(int user,string grant,Guid id,int percent)
|
||||
{
|
||||
if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null;
|
||||
if(!pending.TryGetValue(id,out var request)||request.Sync||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null;
|
||||
return await scans.ProgressAsync(user,new(){OnboardingID=request.Onboarding,PercentComplete=Math.Clamp(percent,0,100)*9/10,Message="Reading Word manuscript in bounded batches. Keep Word open until PlotDirector acknowledges receipt."});
|
||||
}
|
||||
public async Task<IReadOnlyList<(int User,ManuscriptScanState State)>> Expire()
|
||||
@ -71,13 +116,18 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
var sceneMarkers=result.SceneMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>{var start=preview.NativeParagraphPositions[i.WordParagraphIndex];return(Start:start,Chapter:boundaries.LastOrDefault(c=>c.Start<=start).Chapter,Scene:(int?)i.EntityID);}).Where(i=>i.Chapter>0);
|
||||
presence.Map(user,preview.BookID,manuscript,preview.NativeSessionID.Value,preview.NativeRevision.Value,preview.NativeDocumentEnd,boundaries.Concat(sceneMarkers).OrderBy(i=>i.Start).ThenBy(i=>i.Scene.HasValue?1:0).ToArray());
|
||||
}
|
||||
if(preview.ParagraphTracking){
|
||||
var paragraphs=scope.ServiceProvider.GetRequiredService<ParagraphManuscriptService>();var bookRow=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IBookRepository>().GetAsync(preview.BookID);
|
||||
var sources=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IOnboardingBuildRepository>().ListSceneManuscriptSourcesByBookAsync(preview.BookID);
|
||||
await paragraphs.Initialise(user,preview,sources,bookRow!.ProjectID,"OnSave");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public async Task<ManuscriptScanState?> Fail(int user,string grant,Guid id)
|
||||
{
|
||||
await acceptance.WaitAsync();try{
|
||||
if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null;
|
||||
pending.TryRemove(id,out _);var state=await scans.GetStateAsync(user,request.Onboarding);
|
||||
pending.TryRemove(id,out _);if(request.Sync)return null;var state=await scans.GetStateAsync(user,request.Onboarding);
|
||||
return state.ScanID==id?await scans.FailAsync(user,request.Onboarding,"Word transfer interrupted before server acceptance. Retry Import manuscript; existing story data is unchanged."):null;
|
||||
}finally{acceptance.Release();}
|
||||
}
|
||||
@ -104,7 +154,9 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
|
||||
chapters.Add(new(){IsFrontMatter=front,TemporaryChapterKey=key,ChapterNumber=number,Title=front?"Opening material (not a story chapter)":heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+number:"Manuscript",ChapterText=chapterText,WordCount=Words(chapterText),StartPosition=first.Index,ExistingChapterID=structure?.Chapters.FirstOrDefault(c=>c.ChapterId==Marker(first.Tags,"PD-CHAPTER-"))?.ChapterId,ParagraphMap=body.Where(p=>!string.IsNullOrWhiteSpace(p.Text)).Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),SourceParagraphs=rows.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.Index==first.Index&&heading,IsSceneHeading=p.Outline==2,IsSceneSeparator=Separator(p.Text),IncludeInSourceText=!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)}).ToArray()});
|
||||
foreach(var row in rows.Where(p=>p.Outline==2||Marker(p.Tags,"PD-SCENE-").HasValue))scenes.Add(new(){TemporaryChapterKey=key,TemporarySceneKey="scene-"+(scenes.Count+1),SceneNumberWithinChapter=scenes.Count(s=>s.TemporaryChapterKey==key)+1,Title=row.Text.Trim(),StartPosition=row.Index,ExistingSceneID=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==Marker(row.Tags,"PD-SCENE-"))?.SceneId});
|
||||
}
|
||||
return new(){NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count(c=>!c.IsFrontMatter),SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes};
|
||||
var nativeParagraphs=capture.ParagraphTracking?ParagraphReconciliation.Compare([],ParagraphReconciliation.Assemble(capture.Paragraphs,capture.End)).Current:null;
|
||||
if(nativeParagraphs!=null&&capture.ParagraphIds!=null){if(capture.ParagraphIds.Length!=nativeParagraphs.Length||capture.ParagraphIds.Any(id=>id==Guid.Empty)||capture.ParagraphIds.Distinct().Count()!=nativeParagraphs.Length)throw new ArgumentException("Invalid paragraph occurrence identities.");for(int n=0;n<nativeParagraphs.Length;n++)nativeParagraphs[n].Id=capture.ParagraphIds[n];}
|
||||
return new(){ParagraphTracking=capture.ParagraphTracking,NativeParagraphs=nativeParagraphs,NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count(c=>!c.IsFrontMatter),SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes};
|
||||
}
|
||||
private static bool FrontMatterHeading(string text)=>new[]{"title page","copyright","dedication","contents","table of contents","acknowledgements","acknowledgments","about the author"}.Contains(text.Trim(),StringComparer.OrdinalIgnoreCase);
|
||||
private static int? Marker(string[] tags,string prefix)=>tags.Where(t=>t.StartsWith(prefix,StringComparison.Ordinal)).Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue);
|
||||
|
||||
@ -18,13 +18,14 @@ public sealed class NativePresenceStore(TimeProvider clock)
|
||||
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
|
||||
if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision<prior.Position.Revision)return false;}
|
||||
else if(leases.Count>=4096||leases.Values.Count(p=>p.User==user)>=64)return false;
|
||||
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanCapture=value.CanCapture,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
|
||||
leases[key]=new(user,grant,expires,instance,session,new NativePresence{ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
|
||||
}
|
||||
public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}}
|
||||
public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start)
|
||||
{lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||start<0)return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}}
|
||||
public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0)
|
||||
{lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BookId=book,Kind="wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}}
|
||||
public void RequestCancellation(int user,NativeLease selected){lock(gate){var key=(user,selected.Instance,selected.Session);if(leases.TryGetValue(key,out var current)&¤t.Grant==selected.Grant&¤t.Position.Revision==selected.Position.Revision)navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};}}
|
||||
public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0,bool paragraphs=false,bool synchronise=false,long baseRevision=0,string baseHash="")
|
||||
{lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BaseRevision=baseRevision,BaseSnapshotHash=baseHash,BookId=book,ParagraphTracking=paragraphs,Kind=synchronise?"paragraph-snapshot":"wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}}
|
||||
public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session)
|
||||
{lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)?command:null;}}
|
||||
public void Remove(int user,string grant,Guid instance,Guid session,long? throughSequence=null){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant&&(!throughSequence.HasValue||prior.Position.Sequence<=throughSequence.Value)){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}}
|
||||
|
||||
@ -500,6 +500,8 @@ public sealed class OnboardingService(
|
||||
progress);
|
||||
var request = new ManuscriptStructureAnalysisRequest
|
||||
{
|
||||
ConfidenceContractVersion = preview.ParagraphTracking ? 2 : 0,
|
||||
PrivateAnalysis = preview.ParagraphTracking,
|
||||
ProjectID = preview.ProjectID,
|
||||
BookID = preview.BookID,
|
||||
PreviewID = preview.PreviewID,
|
||||
|
||||
@ -27,7 +27,7 @@ public sealed partial class StoryStateService
|
||||
IEnumerable<CharacterKnowledgeItem> items, IReadOnlyDictionary<int, int> indexes, int sceneId)
|
||||
{
|
||||
if (!indexes.TryGetValue(sceneId, out var maximum)) return [];
|
||||
return items.Where(x => indexes.TryGetValue(x.SceneID, out var index) && index <= maximum)
|
||||
return items.Where(x => x.EvidenceState=="Verified" && indexes.TryGetValue(x.SceneID, out var index) && index <= maximum)
|
||||
.GroupBy(x => (x.CharacterID, Identity: KnowledgeIdentity(x)))
|
||||
.Select(x => x.OrderBy(y => indexes[y.SceneID]).ThenBy(y => y.CreatedDate).ThenBy(y => y.CharacterKnowledgeID).Last())
|
||||
.ToList();
|
||||
|
||||
344
PlotLine/Sql/240_ParagraphManuscripts.sql
Normal file
344
PlotLine/Sql/240_ParagraphManuscripts.sql
Normal file
@ -0,0 +1,344 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
-- Additive, opt-in manuscript state. Accepted import captures/checkpoints and legacy scenes are not migrated here.
|
||||
IF OBJECT_ID('dbo.BookParagraphManuscripts','U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.BookParagraphManuscripts(BookID int NOT NULL PRIMARY KEY,ManuscriptID uniqueidentifier NOT NULL,Revision bigint NOT NULL,RequestID uniqueidentifier NOT NULL,Payload nvarchar(max) NOT NULL,UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),CONSTRAINT FK_ParagraphManuscript_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE,CONSTRAINT CK_ParagraphManuscript_Json CHECK(ISJSON(Payload)=1));
|
||||
CREATE TABLE dbo.ManuscriptEvidenceIndex(BookID int NOT NULL,EvidenceID uniqueidentifier NOT NULL,EventKind varchar(16) NOT NULL,EventID int NOT NULL,IsPrimary bit NOT NULL,EvidenceState nvarchar(20) NOT NULL,DerivedSceneID int NULL,CONSTRAINT PK_ManuscriptEvidence PRIMARY KEY(BookID,EvidenceID),CONSTRAINT FK_ManuscriptEvidence_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE,CONSTRAINT CK_ManuscriptEvidence_Kind CHECK(EventKind IN ('Knowledge','Relationship')),CONSTRAINT CK_ManuscriptEvidence_State CHECK(EvidenceState IN ('Verified','Needs review','Missing')));
|
||||
CREATE UNIQUE INDEX UX_ManuscriptEvidence_Primary ON dbo.ManuscriptEvidenceIndex(BookID,EventKind,EventID) WHERE IsPrimary=1;
|
||||
CREATE INDEX IX_ManuscriptEvidence_Event ON dbo.ManuscriptEvidenceIndex(EventKind,EventID,IsPrimary) INCLUDE(EvidenceState);
|
||||
END;
|
||||
GO
|
||||
IF OBJECT_ID('dbo.BookParagraphPositions','U') IS NULL
|
||||
CREATE TABLE dbo.BookParagraphPositions(BookID int NOT NULL,StartPosition int NOT NULL,EndPosition int NOT NULL,ChapterID int NULL,SceneID int NULL,Verified bit NOT NULL,CONSTRAINT PK_BookParagraphPositions PRIMARY KEY(BookID,StartPosition),CONSTRAINT FK_BookParagraphPositions_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE);
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ParagraphManuscript
|
||||
@Action varchar(16),@UserID int,@BookID int,@ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Payload nvarchar(max)=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL,@Position int=NULL,@Mode nvarchar(16)=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
DECLARE @ProjectID int;
|
||||
SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID;
|
||||
IF @ProjectID IS NULL THROW 51000,'Book access denied',1;
|
||||
IF @Action='position'
|
||||
BEGIN
|
||||
SELECT CAST(1 AS bit) AS HasSnapshot,m.Revision,p.ChapterID,p.SceneID
|
||||
FROM dbo.BookParagraphManuscripts m OUTER APPLY(SELECT TOP(1) position.ChapterID,position.SceneID FROM dbo.BookParagraphPositions position
|
||||
WHERE position.BookID=m.BookID AND position.Verified=1 AND position.StartPosition<=@Position AND position.EndPosition>@Position
|
||||
AND m.ManuscriptID=@ManuscriptID AND TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.Payload,'$.SessionId'))=@SessionID AND TRY_CONVERT(bigint,JSON_VALUE(m.Payload,'$.WordRevision'))=@WordRevision) p WHERE m.BookID=@BookID;RETURN;
|
||||
END;
|
||||
IF @Action='get' BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END;
|
||||
IF @Action='status' BEGIN SELECT BookID,ManuscriptID,Revision,JSON_VALUE(Payload,'$.SnapshotHash') AS SnapshotHash,JSON_VALUE(Payload,'$.Mode') AS Mode,TRY_CONVERT(uniqueidentifier,JSON_VALUE(Payload,'$.SessionId')) AS SessionId,TRY_CONVERT(bigint,JSON_VALUE(Payload,'$.WordRevision')) AS WordRevision,
|
||||
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THEN 1 ELSE 0 END AS bit) AS CanWrite,
|
||||
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.UserOnboardingState o WHERE o.BookID=@BookID AND o.OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j WHERE j.BookID=@BookID AND j.Status IN ('Pending','Queued','Running','Processing')) THEN 1 ELSE 0 END AS bit) AS Paused
|
||||
FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END;
|
||||
IF @Action='capture' BEGIN SELECT TOP(1) c.Payload FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.BookID=@BookID AND b.Status IN ('Complete','Built')) ORDER BY c.CreatedUtc DESC;RETURN;END;
|
||||
IF @Action='events'
|
||||
BEGIN
|
||||
SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID,CONCAT(c.CharacterName,N': ',COALESCE(k.Description,N'Knowledge event')) AS Description
|
||||
FROM dbo.CharacterKnowledge k JOIN dbo.Characters c ON c.CharacterID=k.CharacterID JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID
|
||||
UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,CONCAT(ca.CharacterName,N' / ',cb.CharacterName,N': ',COALESCE(r.Description,N'Relationship event'))
|
||||
FROM dbo.RelationshipEvents r JOIN dbo.CharacterRelationships rel ON rel.CharacterRelationshipID=r.CharacterRelationshipID JOIN dbo.Characters ca ON ca.CharacterID=rel.CharacterAID JOIN dbo.Characters cb ON cb.CharacterID=rel.CharacterBID JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID;RETURN;
|
||||
END;
|
||||
-- Conservative mutation contract: use the established project owner role, never expand collaborator permissions.
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole=N'Owner') THROW 51000,'Project owner authority required',1;
|
||||
IF @Action='mode'
|
||||
BEGIN
|
||||
IF COALESCE(@Mode,'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @PreferenceRevision bigint;
|
||||
SELECT @Payload=Payload,@PreferenceRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @PreferenceRevision IS NULL OR @PreferenceRevision<>@ExpectedRevision THROW 51000,'Manuscript changed; refresh before changing preferences',1;
|
||||
IF JSON_VALUE(@Payload,'$.Mode')<>@Mode BEGIN
|
||||
SET @RequestID=NEWID();SET @PreferenceRevision+=1;SET @Payload=JSON_MODIFY(@Payload,'$.Mode',@Mode);SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@PreferenceRevision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID));
|
||||
UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload,Revision=@PreferenceRevision,RequestID=@RequestID,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID;
|
||||
END;
|
||||
COMMIT;SELECT @Payload;RETURN;
|
||||
END;
|
||||
IF @Action<>'save' THROW 51000,'Unknown manuscript operation',1;
|
||||
IF ISJSON(@Payload)<>1 OR DATALENGTH(@Payload)>128*1024*1024 OR @RequestID IS NULL OR @ExpectedRevision IS NULL THROW 51000,'Invalid manuscript state',1;
|
||||
IF COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.BookId')),-1)<>@BookID OR COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.ProjectId')),-1)<>@ProjectID OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')) IS NULL THROW 51000,'Manuscript scope mismatch',1;
|
||||
IF COALESCE(JSON_VALUE(@Payload,'$.Mode'),'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1;
|
||||
-- Do not adopt or replace a book while its accepted import is still awaiting a completed build.
|
||||
IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND c.IsCurrent=1 AND COALESCE(JSON_VALUE(c.Payload,'$.ParagraphTracking'),'false')<>'true' AND NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.Status IN ('Complete','Built'))) THROW 51000,'Active import protected; finish the existing import before enabling paragraph tracking',1;
|
||||
IF @ExpectedRevision>=0 AND (EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing'))) THROW 51000,'Active import or analysis protected; synchronisation paused',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Revision bigint,@Previous nvarchar(max),@LastRequest uniqueidentifier;
|
||||
SELECT @Revision=Revision,@Previous=Payload,@LastRequest=RequestID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @LastRequest=@RequestID BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;COMMIT;RETURN;END;
|
||||
IF (@Revision IS NULL AND @ExpectedRevision<>-1) OR (@Revision IS NOT NULL AND @Revision<>@ExpectedRevision) THROW 51000,'Manuscript changed; refresh before retrying',1;
|
||||
DECLARE @Scenes table(JsonIndex int,Id uniqueidentifier PRIMARY KEY,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier);
|
||||
INSERT @Scenes SELECT CONVERT(int,j.[key]),s.Id,s.CanonicalId,s.ChapterId,s.Title,s.Retired,s.MergedInto FROM OPENJSON(@Payload,'$.Scenes') j CROSS APPLY OPENJSON(j.value) WITH(Id uniqueidentifier,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier) s;
|
||||
IF EXISTS(SELECT 1 FROM @Scenes x LEFT JOIN dbo.Chapters c ON c.ChapterID=x.ChapterId AND c.BookID=@BookID WHERE c.ChapterID IS NULL) OR EXISTS(SELECT 1 FROM @Scenes x WHERE x.CanonicalId>0 AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=x.CanonicalId AND c.BookID=@BookID)) THROW 51000,'Cross-book scene reference rejected',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.Scenes actual WHERE actual.IsArchived=0 AND EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.ChapterId=actual.ChapterID) AND NOT EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.CanonicalId=actual.SceneID)) THROW 51000,'This chapter contains a scene outside the accepted paragraph map; review it before synchronising',1;
|
||||
-- A snapshot is not authority to undo newer author archive/chapter decisions made elsewhere.
|
||||
IF @Previous IS NULL AND EXISTS(SELECT 1 FROM @Scenes state JOIN dbo.Scenes actual ON actual.SceneID=state.CanonicalId WHERE actual.IsArchived<>state.Retired) THROW 51000,'An imported scene was archived; review its association before adoption',1;
|
||||
IF @Previous IS NOT NULL AND EXISTS(SELECT 1 FROM OPENJSON(@Previous,'$.Scenes') WITH(CanonicalId int,ChapterId int,Retired bit) prior JOIN dbo.Scenes actual ON actual.SceneID=prior.CanonicalId WHERE actual.IsArchived<>prior.Retired OR actual.ChapterID<>prior.ChapterId) THROW 51000,'Canonical scene decisions changed after this snapshot; automatic replacement refused',1;
|
||||
DECLARE @Paragraphs table(Id uniqueidentifier PRIMARY KEY,Ordinal int UNIQUE,StartPosition int,EndPosition int,Text nvarchar(max),SceneId uniqueidentifier NULL,ChapterId int NULL,Story bit,Verified bit);
|
||||
INSERT @Paragraphs SELECT p.Id,p.Ordinal,p.StartPosition,p.EndPosition,p.Text,x.SceneId,x.ChapterId,x.Story,x.PositionVerified FROM OPENJSON(@Payload,'$.Paragraphs') WITH(Occurrence nvarchar(max) AS JSON,SceneId uniqueidentifier,ChapterId int,Story bit,PositionVerified bit) x CROSS APPLY OPENJSON(x.Occurrence) WITH(Id uniqueidentifier,Ordinal int,StartPosition int '$.Start',EndPosition int '$.End',Text nvarchar(max)) p;
|
||||
IF EXISTS(SELECT 1 FROM @Paragraphs p WHERE p.Story=1 AND NOT EXISTS(SELECT 1 FROM @Scenes s WHERE s.Id=p.SceneId AND s.Retired=0)) THROW 51000,'Story paragraph has no current scene',1;
|
||||
IF (SELECT COUNT(*) FROM @Paragraphs)>100000 OR EXISTS(SELECT 1 FROM @Paragraphs HAVING MIN(Ordinal)<>0 OR MAX(Ordinal)<>COUNT(*)-1) THROW 51000,'Invalid paragraph ordering',1;
|
||||
-- New scene identities materialise through the existing canonical scene table; existing metadata is not overwritten.
|
||||
DECLARE @SceneKey uniqueidentifier,@Chapter int,@Title nvarchar(200),@JsonIndex int,@NewID int;
|
||||
DECLARE createScenes CURSOR LOCAL FAST_FORWARD FOR SELECT Id,ChapterId,Title,JsonIndex FROM @Scenes WHERE CanonicalId=0 AND Retired=0;
|
||||
OPEN createScenes;FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex;
|
||||
WHILE @@FETCH_STATUS=0
|
||||
BEGIN
|
||||
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID)
|
||||
SELECT @Chapter,COALESCE((SELECT MAX(SceneNumber) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,@Title,COALESCE((SELECT MAX(SortOrder) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,COALESCE((SELECT TimeModeID FROM dbo.TimeModes WHERE TimeModeName=N'Unknown'),template.TimeModeID),template.TimeConfidenceID,template.RevisionStatusID FROM(SELECT TOP(1) TimeModeID,TimeConfidenceID,RevisionStatusID FROM dbo.Scenes WHERE ChapterID=@Chapter ORDER BY SceneID) template;
|
||||
IF @@ROWCOUNT<>1 THROW 51000,'A canonical source scene is required for splitting',1;
|
||||
SET @NewID=SCOPE_IDENTITY();UPDATE @Scenes SET CanonicalId=@NewID WHERE Id=@SceneKey;SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Scenes[',@JsonIndex,'].CanonicalId'),@NewID);
|
||||
FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex;
|
||||
END;CLOSE createScenes;DEALLOCATE createScenes;
|
||||
UPDATE existing SET ChapterID=state.ChapterId,IsArchived=state.Retired,UpdatedDate=SYSUTCDATETIME() FROM dbo.Scenes existing JOIN @Scenes state ON state.CanonicalId=existing.SceneID;
|
||||
;WITH ordering AS(SELECT s.CanonicalId,ROW_NUMBER() OVER(PARTITION BY s.ChapterId ORDER BY MIN(p.Ordinal),s.CanonicalId) AS Sequence FROM @Scenes s JOIN @Paragraphs p ON p.SceneId=s.Id WHERE s.Retired=0 GROUP BY s.CanonicalId,s.ChapterId)
|
||||
UPDATE scene SET SortOrder=o.Sequence,SceneNumber=o.Sequence FROM dbo.Scenes scene JOIN ordering o ON o.CanonicalId=scene.SceneID;
|
||||
DELETE dbo.BookParagraphPositions WHERE BookID=@BookID;
|
||||
INSERT dbo.BookParagraphPositions(BookID,StartPosition,EndPosition,ChapterID,SceneID,Verified)
|
||||
SELECT @BookID,p.StartPosition,p.EndPosition,COALESCE(s.ChapterId,p.ChapterId),s.CanonicalId,p.Verified FROM @Paragraphs p LEFT JOIN @Scenes s ON s.Id=p.SceneId;
|
||||
-- Explicit merge/undo positions, scoped to this book. Anchored verified primary passages take precedence below.
|
||||
;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int))
|
||||
UPDATE k SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN positions p ON p.Kind='Knowledge' AND p.Id=k.CharacterKnowledgeID JOIN dbo.Scenes old ON old.SceneID=k.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID;
|
||||
;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int))
|
||||
UPDATE r SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN positions p ON p.Kind='Relationship' AND p.Id=r.RelationshipEventID JOIN dbo.Scenes old ON old.SceneID=r.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID;
|
||||
DELETE dbo.ManuscriptEvidenceIndex WHERE BookID=@BookID;
|
||||
INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState,DerivedSceneID)
|
||||
SELECT @BookID,e.Id,e.EventKind,e.EventId,e.[Primary],e.State,CASE WHEN e.State=N'Verified' THEN s.CanonicalId END FROM OPENJSON(@Payload,'$.Evidence') WITH(Id uniqueidentifier,EventKind varchar(16),EventId int,[Primary] bit,State nvarchar(20),CurrentScene uniqueidentifier) e LEFT JOIN @Scenes s ON s.Id=e.CurrentScene;
|
||||
IF EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex e WHERE e.BookID=@BookID AND ((e.EventKind='Knowledge' AND NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE k.CharacterKnowledgeID=e.EventID AND c.BookID=@BookID)) OR(e.EventKind='Relationship' AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE r.RelationshipEventID=e.EventID AND c.BookID=@BookID)))) THROW 51000,'Evidence event does not belong to this book',1;
|
||||
UPDATE k SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Knowledge' AND e.EventID=k.CharacterKnowledgeID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0;
|
||||
UPDATE r SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Relationship' AND e.EventID=r.RelationshipEventID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0;
|
||||
-- Current prose projections remain in the established source service's tables. No planning/AI records are rewritten.
|
||||
DECLARE @Canonical int,@SceneText nvarchar(max),@First int,@Last int,@Words int,@Characters int;
|
||||
DECLARE sceneText CURSOR LOCAL FAST_FORWARD FOR SELECT s.CanonicalId,s.ChapterId,COALESCE(STRING_AGG(CONVERT(nvarchar(max),p.Text),N'') WITHIN GROUP(ORDER BY p.Ordinal),N''),MIN(p.Ordinal)+1,MAX(p.Ordinal)+1 FROM @Scenes s LEFT JOIN @Paragraphs p ON p.SceneId=s.Id AND p.Story=1 WHERE s.CanonicalId>0 AND s.Retired=0 AND NOT EXISTS(SELECT 1 FROM @Paragraphs unresolved WHERE unresolved.SceneId=s.Id AND unresolved.Story=1 AND unresolved.Verified=0) GROUP BY s.CanonicalId,s.ChapterId;
|
||||
OPEN sceneText;FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last;
|
||||
WHILE @@FETCH_STATUS=0
|
||||
BEGIN
|
||||
SET @Words=(SELECT COUNT(*) FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@SceneText,CHAR(13),N' '),CHAR(10),N' '),CHAR(9),N' '),N' ') WHERE value<>N'');
|
||||
SET @Characters=DATALENGTH(@SceneText)/2;
|
||||
EXEC dbo.SceneManuscriptSource_Save @ProjectID=@ProjectID,@BookID=@BookID,@ChapterID=@Chapter,@SceneID=@Canonical,@SourceText=@SceneText,@SourceWordCount=@Words,@SourceCharacterCount=@Characters,@SourceStartParagraph=@First,@SourceEndParagraph=@Last,@WordStartParagraphIndex=@First,@WordEndParagraphIndex=@Last,@SourceKind=N'ParagraphSync';
|
||||
FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last;
|
||||
END;CLOSE sceneText;DEALLOCATE sceneText;
|
||||
DECLARE @ActualEvents nvarchar(max)=(SELECT Kind,Id,SceneId,Description FROM(
|
||||
SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID AS SceneId,COALESCE(k.Description,N'') AS Description FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID
|
||||
UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,COALESCE(r.Description,N'') FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID) rows FOR JSON PATH);
|
||||
SET @Payload=JSON_MODIFY(@Payload,'$.EventPositions',JSON_QUERY(COALESCE(@ActualEvents,N'[]')));
|
||||
SET @Revision=COALESCE(@Revision,0)+1;SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@Revision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID));
|
||||
IF @Previous IS NULL INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@BookID,CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),@Revision,@RequestID,@Payload);
|
||||
ELSE UPDATE dbo.BookParagraphManuscripts SET ManuscriptID=CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),Revision=@Revision,RequestID=@RequestID,Payload=@Payload,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID;
|
||||
EXEC dbo.Dynamics_RunContinuityChecks @ProjectID=@ProjectID,@BookID=@BookID;
|
||||
COMMIT;SELECT @Payload;
|
||||
END;
|
||||
GO
|
||||
-- Presentation/continuity adapters use this narrow procedure; application code contains no inline SQL.
|
||||
CREATE OR ALTER PROCEDURE dbo.ParagraphEvidence_States @EventKind varchar(16),@EventIDs nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT e.EventID,e.EvidenceState FROM dbo.ManuscriptEvidenceIndex e JOIN OPENJSON(@EventIDs) ids ON TRY_CONVERT(int,ids.value)=e.EventID WHERE e.EventKind=@EventKind AND e.IsPrimary=1;
|
||||
END;
|
||||
GO
|
||||
|
||||
-- Existing deterministic continuity algorithm, with unverified primary evidence excluded before LAG.
|
||||
CREATE OR ALTER PROCEDURE dbo.Dynamics_RunContinuityChecks
|
||||
@ProjectID int,
|
||||
@BookID int = NULL,
|
||||
@SceneID int = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
-- Recompute only this deterministic warning type; retain author dismissals/intentional decisions.
|
||||
DELETE warning FROM dbo.ContinuityWarnings warning JOIN dbo.WarningTypes kind ON kind.WarningTypeID=warning.WarningTypeID
|
||||
WHERE warning.ProjectID=@ProjectID AND (@BookID IS NULL OR warning.BookID=@BookID) AND (@SceneID IS NULL OR warning.SceneID=@SceneID)
|
||||
AND kind.TypeName=N'Abrupt Relationship Change' AND warning.IsDismissed=0 AND warning.IsIntentional=0;
|
||||
|
||||
;WITH RelationshipSteps AS
|
||||
(
|
||||
SELECT cr.CharacterRelationshipID, cr.ProjectID, nso.BookID, nso.ChapterID, re.SceneID,
|
||||
ca.CharacterName AS CharacterAName, cb.CharacterName AS CharacterBName, re.Intensity,
|
||||
LAG(re.Intensity) OVER (PARTITION BY cr.CharacterRelationshipID ORDER BY nso.GlobalSceneIndex, re.RelationshipEventID) AS PreviousIntensity,
|
||||
LAG(nso.SceneTitle) OVER (PARTITION BY cr.CharacterRelationshipID ORDER BY nso.GlobalSceneIndex, re.RelationshipEventID) AS PreviousSceneTitle
|
||||
FROM (SELECT re.* FROM dbo.RelationshipEvents re WHERE NOT EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex evidence WHERE evidence.EventKind='Relationship' AND evidence.EventID=re.RelationshipEventID AND evidence.IsPrimary=1 AND evidence.EvidenceState<>N'Verified')) re
|
||||
INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID AND cr.IsArchived = 0
|
||||
INNER JOIN dbo.Characters ca ON ca.CharacterID = cr.CharacterAID
|
||||
INNER JOIN dbo.Characters cb ON cb.CharacterID = cr.CharacterBID
|
||||
INNER JOIN dbo.NarrativeSceneOrder nso ON nso.SceneID = re.SceneID
|
||||
WHERE cr.ProjectID = @ProjectID
|
||||
)
|
||||
INSERT dbo.ContinuityWarnings (ProjectID, BookID, ChapterID, SceneID, EntityType, EntityID, WarningTypeID, WarningSeverityID, Message, Details)
|
||||
SELECT rs.ProjectID, rs.BookID, rs.ChapterID, rs.SceneID, N'Relationship', rs.CharacterRelationshipID,
|
||||
wt.WarningTypeID, ws.WarningSeverityID,
|
||||
N'Possible emotional transition issue. Relationship intensity changes sharply between scenes.',
|
||||
CONCAT(rs.CharacterAName, N' / ', rs.CharacterBName, N' changes from ', rs.PreviousIntensity, N' to ', rs.Intensity, N'. Previous scene: ', rs.PreviousSceneTitle, N'.')
|
||||
FROM RelationshipSteps rs
|
||||
CROSS JOIN dbo.WarningTypes wt
|
||||
CROSS JOIN dbo.WarningSeverities ws
|
||||
WHERE wt.TypeName = N'Abrupt Relationship Change' AND ws.SeverityName = N'Info'
|
||||
AND rs.Intensity IS NOT NULL AND rs.PreviousIntensity IS NOT NULL AND ABS(rs.Intensity - rs.PreviousIntensity) >= 5
|
||||
AND (@BookID IS NULL OR rs.BookID = @BookID) AND (@SceneID IS NULL OR rs.SceneID = @SceneID)
|
||||
AND NOT EXISTS (SELECT 1 FROM dbo.ContinuityWarnings existing WHERE existing.ProjectID = rs.ProjectID AND existing.SceneID = rs.SceneID AND existing.EntityType = N'Relationship' AND existing.EntityID = rs.CharacterRelationshipID AND existing.WarningTypeID = wt.WarningTypeID AND existing.IsDismissed = 0 AND existing.IsIntentional = 0);
|
||||
|
||||
;WITH Appearances AS
|
||||
(
|
||||
SELECT sc.CharacterID, ch.CharacterName, nso.ProjectID, nso.BookID, nso.ChapterID, sc.SceneID, nso.GlobalSceneIndex,
|
||||
LAG(nso.GlobalSceneIndex) OVER (PARTITION BY sc.CharacterID ORDER BY nso.GlobalSceneIndex) AS PreviousIndex
|
||||
FROM dbo.SceneCharacters sc
|
||||
INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID
|
||||
INNER JOIN dbo.NarrativeSceneOrder nso ON nso.SceneID = sc.SceneID
|
||||
WHERE ch.ProjectID = @ProjectID AND ch.IsArchived = 0
|
||||
)
|
||||
INSERT dbo.ContinuityWarnings (ProjectID, BookID, ChapterID, SceneID, EntityType, EntityID, WarningTypeID, WarningSeverityID, Message, Details)
|
||||
SELECT ProjectID, BookID, ChapterID, SceneID, N'Character', CharacterID, wt.WarningTypeID, ws.WarningSeverityID,
|
||||
CONCAT(N'Possible review: ', CharacterName, N' is absent for ', GlobalSceneIndex - PreviousIndex - 1, N' narrative scenes.'),
|
||||
N'Long absences are sometimes useful, but this may be worth checking after a major beat.'
|
||||
FROM Appearances
|
||||
CROSS JOIN dbo.WarningTypes wt
|
||||
CROSS JOIN dbo.WarningSeverities ws
|
||||
WHERE wt.TypeName = N'Long Character Absence' AND ws.SeverityName = N'Info'
|
||||
AND PreviousIndex IS NOT NULL AND GlobalSceneIndex - PreviousIndex - 1 >= 12
|
||||
AND (@BookID IS NULL OR BookID = @BookID) AND (@SceneID IS NULL OR SceneID = @SceneID)
|
||||
AND NOT EXISTS (SELECT 1 FROM dbo.ContinuityWarnings existing WHERE existing.ProjectID = Appearances.ProjectID AND existing.SceneID = Appearances.SceneID AND existing.EntityType = N'Character' AND existing.EntityID = Appearances.CharacterID AND existing.WarningTypeID = wt.WarningTypeID AND existing.IsDismissed = 0 AND existing.IsIntentional = 0);
|
||||
|
||||
;WITH CharacterUsage AS
|
||||
(
|
||||
SELECT ch.ProjectID, ch.CharacterID, ch.CharacterName,
|
||||
COUNT(DISTINCT sc.SceneID) AS AppearanceCount,
|
||||
COUNT(DISTINCT cr.CharacterRelationshipID) AS RelationshipCount
|
||||
FROM dbo.Characters ch
|
||||
LEFT JOIN dbo.SceneCharacters sc ON sc.CharacterID = ch.CharacterID
|
||||
LEFT JOIN dbo.CharacterRelationships cr ON cr.ProjectID = ch.ProjectID
|
||||
AND cr.IsArchived = 0
|
||||
AND ch.CharacterID IN (cr.CharacterAID, cr.CharacterBID)
|
||||
WHERE ch.ProjectID = @ProjectID AND ch.IsArchived = 0 AND @SceneID IS NULL
|
||||
GROUP BY ch.ProjectID, ch.CharacterID, ch.CharacterName
|
||||
HAVING COUNT(DISTINCT cr.CharacterRelationshipID) >= 2 AND COUNT(DISTINCT sc.SceneID) <= 1
|
||||
)
|
||||
INSERT dbo.ContinuityWarnings (ProjectID, EntityType, EntityID, WarningTypeID, WarningSeverityID, Message, Details)
|
||||
SELECT ProjectID, N'Character', CharacterID, wt.WarningTypeID, ws.WarningSeverityID,
|
||||
CONCAT(N'Possible review: ', CharacterName, N' has several relationship links but very few scene appearances.'),
|
||||
N'This may be intentional, but the character could be underused relative to their story connections.'
|
||||
FROM CharacterUsage
|
||||
CROSS JOIN dbo.WarningTypes wt
|
||||
CROSS JOIN dbo.WarningSeverities ws
|
||||
WHERE wt.TypeName = N'Character Underused' AND ws.SeverityName = N'Info'
|
||||
AND NOT EXISTS (SELECT 1 FROM dbo.ContinuityWarnings existing WHERE existing.ProjectID = CharacterUsage.ProjectID AND existing.EntityType = N'Character' AND existing.EntityID = CharacterUsage.CharacterID AND existing.WarningTypeID = wt.WarningTypeID AND existing.IsDismissed = 0 AND existing.IsIntentional = 0);
|
||||
|
||||
;WITH SceneCounts AS
|
||||
(
|
||||
SELECT nso.ProjectID, nso.BookID, nso.ChapterID, nso.SceneID, nso.SceneTitle, COUNT(*) AS CharacterCount
|
||||
FROM dbo.SceneCharacters sc
|
||||
INNER JOIN dbo.NarrativeSceneOrder nso ON nso.SceneID = sc.SceneID
|
||||
WHERE nso.ProjectID = @ProjectID AND (@BookID IS NULL OR nso.BookID = @BookID) AND (@SceneID IS NULL OR nso.SceneID = @SceneID)
|
||||
GROUP BY nso.ProjectID, nso.BookID, nso.ChapterID, nso.SceneID, nso.SceneTitle
|
||||
HAVING COUNT(*) >= 7
|
||||
)
|
||||
INSERT dbo.ContinuityWarnings (ProjectID, BookID, ChapterID, SceneID, EntityType, EntityID, WarningTypeID, WarningSeverityID, Message, Details)
|
||||
SELECT ProjectID, BookID, ChapterID, SceneID, N'Scene', SceneID, wt.WarningTypeID, ws.WarningSeverityID,
|
||||
CONCAT(N'Possible review: this scene has ', CharacterCount, N' character appearances.'),
|
||||
N'Busy scenes can work well, but may need extra clarity around focus and blocking.'
|
||||
FROM SceneCounts
|
||||
CROSS JOIN dbo.WarningTypes wt
|
||||
CROSS JOIN dbo.WarningSeverities ws
|
||||
WHERE wt.TypeName = N'Scene Character Overload' AND ws.SeverityName = N'Info'
|
||||
AND NOT EXISTS (SELECT 1 FROM dbo.ContinuityWarnings existing WHERE existing.ProjectID = SceneCounts.ProjectID AND existing.SceneID = SceneCounts.SceneID AND existing.EntityType = N'Scene' AND existing.EntityID = SceneCounts.SceneID AND existing.WarningTypeID = wt.WarningTypeID AND existing.IsDismissed = 0 AND existing.IsIntentional = 0);
|
||||
|
||||
;WITH Knowledge AS
|
||||
(
|
||||
SELECT ck.CharacterID, ch.CharacterName, ck.StoryAssetID, ck.PlotThreadID, ck.SceneID, nso.ProjectID, nso.BookID, nso.ChapterID, nso.GlobalSceneIndex,
|
||||
MIN(nso.GlobalSceneIndex) OVER (PARTITION BY ck.CharacterID, ISNULL(ck.StoryAssetID, 0), ISNULL(ck.PlotThreadID, 0)) AS FirstKnownIndex
|
||||
FROM dbo.CharacterKnowledge ck
|
||||
INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID
|
||||
INNER JOIN dbo.NarrativeSceneOrder nso ON nso.SceneID = ck.SceneID
|
||||
WHERE ch.ProjectID = @ProjectID
|
||||
),
|
||||
Candidate AS
|
||||
(
|
||||
SELECT DISTINCT sc.CharacterID, ch.CharacterName, te.PlotThreadID, ae.StoryAssetID, nso.ProjectID, nso.BookID, nso.ChapterID, sc.SceneID, nso.GlobalSceneIndex
|
||||
FROM dbo.SceneCharacters sc
|
||||
INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID
|
||||
INNER JOIN dbo.NarrativeSceneOrder nso ON nso.SceneID = sc.SceneID
|
||||
LEFT JOIN dbo.ThreadEvents te ON te.SceneID = sc.SceneID
|
||||
LEFT JOIN dbo.AssetEvents ae ON ae.SceneID = sc.SceneID
|
||||
WHERE ch.ProjectID = @ProjectID AND (@BookID IS NULL OR nso.BookID = @BookID) AND (@SceneID IS NULL OR sc.SceneID = @SceneID)
|
||||
AND (te.PlotThreadID IS NOT NULL OR ae.StoryAssetID IS NOT NULL)
|
||||
)
|
||||
INSERT dbo.ContinuityWarnings (ProjectID, BookID, ChapterID, SceneID, EntityType, EntityID, WarningTypeID, WarningSeverityID, Message, Details)
|
||||
SELECT c.ProjectID, c.BookID, c.ChapterID, c.SceneID, N'Character', c.CharacterID, wt.WarningTypeID, ws.WarningSeverityID,
|
||||
CONCAT(N'Possible review: ', c.CharacterName, N' appears in a scene involving information without an earlier knowledge event.'),
|
||||
N'This is advisory only. Add a knowledge event if the character is meant to know this, or mark the warning intentional.'
|
||||
FROM Candidate c
|
||||
CROSS JOIN dbo.WarningTypes wt
|
||||
CROSS JOIN dbo.WarningSeverities ws
|
||||
WHERE wt.TypeName = N'Knowledge Continuity' AND ws.SeverityName = N'Info'
|
||||
AND NOT EXISTS
|
||||
(
|
||||
SELECT 1 FROM Knowledge k
|
||||
WHERE k.CharacterID = c.CharacterID
|
||||
AND ((c.StoryAssetID IS NOT NULL AND k.StoryAssetID = c.StoryAssetID) OR (c.PlotThreadID IS NOT NULL AND k.PlotThreadID = c.PlotThreadID))
|
||||
AND k.FirstKnownIndex <= c.GlobalSceneIndex
|
||||
)
|
||||
AND NOT EXISTS (SELECT 1 FROM dbo.ContinuityWarnings existing WHERE existing.ProjectID = c.ProjectID AND existing.SceneID = c.SceneID AND existing.EntityType = N'Character' AND existing.EntityID = c.CharacterID AND existing.WarningTypeID = wt.WarningTypeID AND existing.IsDismissed = 0 AND existing.IsIntentional = 0);
|
||||
END;
|
||||
GO
|
||||
|
||||
-- Staged foundation safeguard: legacy recovery must not silently omit or delete new evidence.
|
||||
CREATE OR ALTER PROCEDURE dbo.ProjectRecovery_State @ProjectID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts m JOIN dbo.Books b ON b.BookID=m.BookID WHERE b.ProjectID=@ProjectID) THROW 51000,'Paragraph manuscript recovery is not yet portable. Backup or replacement refused rather than omitting author evidence.',1;
|
||||
|
||||
SELECT r.* FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
SELECT r.* FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
|
||||
SELECT ReferencesJson FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID;
|
||||
END;
|
||||
GO
|
||||
|
||||
-- Staged foundation safeguard: legacy recovery must not silently omit or delete new evidence.
|
||||
CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson @ProjectID int,@SourceRestorePointID int=NULL,@SafetyRestorePointID int=NULL,@JsonData nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts m JOIN dbo.Books b ON b.BookID=m.BookID WHERE b.ProjectID=@ProjectID) THROW 51000,'Paragraph manuscript recovery is not yet portable. Backup or replacement refused rather than omitting author evidence.',1;
|
||||
SET XACT_ABORT ON;
|
||||
DECLARE @State nvarchar(max)=JSON_QUERY(@JsonData,'$.Recovery');
|
||||
IF @State IS NULL AND (EXISTS(SELECT 1 FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID) OR EXISTS(SELECT 1 FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID AND ReferencesJson<>N'[]') OR EXISTS(SELECT 1 FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID)) THROW 51000,'Older snapshot omits native or Intent author decisions. Replacement refused.',1;
|
||||
IF JSON_VALUE(@JsonData,'$.FormatVersion')='1.4' SET @JsonData=JSON_MODIFY(@JsonData,'$.FormatVersion','1.3');
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @PriorBooks nvarchar(max)=(SELECT BookID FROM dbo.Books WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID FOR JSON PATH);
|
||||
DECLARE @AppendOnly bit=CASE WHEN JSON_VALUE(@State,'$.AppendOnly')='true' THEN 1 ELSE 0 END;
|
||||
IF @AppendOnly=1 AND (@SourceRestorePointID IS NOT NULL OR NOT EXISTS(SELECT 1 FROM OPENJSON(@State,'$.AppendBooks')) OR EXISTS(SELECT 1 FROM OPENJSON(@PriorBooks) WITH(BookID int) p WHERE NOT EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.Books') WITH(BookID int) b WHERE b.BookID=p.BookID)) OR EXISTS(SELECT 1 FROM OPENJSON(@State,'$.AppendBooks') n WHERE EXISTS(SELECT 1 FROM OPENJSON(@PriorBooks) WITH(BookID int) p WHERE p.BookID=TRY_CONVERT(int,n.value)))) THROW 51000,'Append mode must preserve existing books and identify only new books',1;
|
||||
DECLARE @ReservationID uniqueidentifier=NULL;
|
||||
IF @SourceRestorePointID IS NOT NULL BEGIN
|
||||
DECLARE @Delta int=(SELECT COUNT(*) FROM OPENJSON(@JsonData,'$.Data.Books'))-(SELECT COUNT(*) FROM dbo.Books WHERE ProjectID=@ProjectID);
|
||||
IF @Delta>0 BEGIN
|
||||
DECLARE @Owner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1),@Now datetime2=SYSUTCDATETIME();
|
||||
DECLARE @Capacity table(Allowed bit,ReservationID uniqueidentifier,CurrentUsage int,MaximumAllowed int,Message nvarchar(max));
|
||||
INSERT @Capacity EXEC dbo.SubscriptionEntitlement_TryReserveBookSlots @Owner,@Delta,@Now;
|
||||
IF EXISTS(SELECT 1 FROM @Capacity WHERE Allowed=0) THROW 51000,'Not enough book capacity to rewind this project',1;
|
||||
SELECT @ReservationID=ReservationID FROM @Capacity;
|
||||
END;
|
||||
END;
|
||||
IF @State IS NOT NULL AND ISNULL(JSON_VALUE(@State,'$.Protected'),'false')<>'true' THROW 51000,'Recovery state must be validated and protected by the application',1;
|
||||
IF @State IS NOT NULL AND @AppendOnly=0 BEGIN
|
||||
DELETE r FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
DELETE r FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
|
||||
END;
|
||||
IF @AppendOnly=0 BEGIN
|
||||
-- Receipts are operational authority, not snapshot author data. Even matching IDs cannot prove old imports.
|
||||
DELETE FROM dbo.NativeReviewImports WHERE BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int));
|
||||
DELETE FROM dbo.NativeImportOperations WHERE BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int));
|
||||
END;
|
||||
EXEC dbo.ProjectRestore_ApplyGraph236 @ProjectID,@SourceRestorePointID,@SafetyRestorePointID,@JsonData;
|
||||
-- Protected state is supplied by the application after validating/decrypting the portable representation.
|
||||
IF @State IS NOT NULL AND JSON_VALUE(@State,'$.Protected')='true' EXEC dbo.ProjectRecovery_Apply @ProjectID,@State,@PriorBooks;
|
||||
ELSE BEGIN
|
||||
DELETE r FROM dbo.NativeReviewImports r WHERE r.BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int)) AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=r.ChapterID AND BookID=r.BookID);
|
||||
DELETE r FROM dbo.NativeImportOperations r WHERE r.BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int)) AND NOT EXISTS(SELECT 1 FROM dbo.NativeReviewImports WHERE BuildID=r.BuildID AND BookID=r.BookID);
|
||||
END;
|
||||
IF @ReservationID IS NOT NULL EXEC dbo.SubscriptionEntitlement_ReleaseBookSlots @ReservationID;
|
||||
COMMIT;
|
||||
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
|
||||
END;
|
||||
GO
|
||||
@ -1,3 +1,4 @@
|
||||
@inject Microsoft.Extensions.Configuration.IConfiguration ParagraphConfiguration
|
||||
@model BookDetailViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
@ -30,6 +31,7 @@
|
||||
<div>
|
||||
<p class="eyebrow"><a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a></p>
|
||||
<h1>Book @Model.Book.BookNumber: @Model.Book.BookTitle <help-icon key="books.overview" /></h1>
|
||||
@if(ParagraphConfiguration.GetValue<bool>("Features:ParagraphManuscripts")){<a asp-controller="ParagraphManuscript" asp-action="Index" asp-route-bookId="@Model.Book.BookID" class="btn btn-outline-secondary">Manuscript structure and evidence</a>}
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Book.Subtitle))
|
||||
{
|
||||
<p class="lead-text">@Model.Book.Subtitle</p>
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
@inject Microsoft.Extensions.Configuration.IConfiguration ParagraphConfiguration
|
||||
@model OnboardingWizardViewModel
|
||||
@using PlotLine.Models
|
||||
@{
|
||||
@ -345,6 +346,7 @@
|
||||
data-scan-status="@Model.ScanState.Status"
|
||||
aria-label="Manuscript scan">
|
||||
<p class="small text-muted">Import manuscript reads the linked Word document and saves a server-side capture. Review and confirm before story records are created. After PlotDirector acknowledges receipt, analysis and review no longer need Word or the Companion.</p>
|
||||
@if(ParagraphConfiguration.GetValue<bool>("Features:ParagraphManuscripts")){<label class="d-block mb-2"><input type="checkbox" data-paragraph-tracking/> Enable paragraph tracking after import, including updates after Word saves or reconnects. AI runs only through this import workflow.</label>}
|
||||
<div class="onboarding-scan-status">
|
||||
<span data-onboarding-scan-message>@ScanMessage(Model.ScanState)</span>
|
||||
<strong data-onboarding-scan-percent>@ScanPercent(Model.ScanState)</strong>
|
||||
|
||||
52
PlotLine/Views/ParagraphManuscript/Index.cshtml
Normal file
52
PlotLine/Views/ParagraphManuscript/Index.cshtml
Normal file
@ -0,0 +1,52 @@
|
||||
@model PlotLine.Models.ParagraphWorkspaceModel
|
||||
@{
|
||||
ViewData["Title"]="Manuscript structure and evidence";
|
||||
var state=Model.State;
|
||||
var scenePositions=state.Paragraphs.Where(p=>p.Story&&p.SceneId.HasValue).GroupBy(p=>p.SceneId!.Value).ToDictionary(g=>g.Key,g=>g.Min(p=>p.Occurrence.Ordinal));
|
||||
var current=state.Scenes.Where(s=>!s.Retired).OrderBy(s=>scenePositions.GetValueOrDefault(s.Id,int.MaxValue)).ToArray();
|
||||
var currentPage=Math.Clamp(Model.Page,1,Math.Max(1,(state.Paragraphs.Count+99)/100));
|
||||
var evidencePage=Math.Clamp(Model.EvidencePage,1,Math.Max(1,(state.Evidence.Count+19)/20));
|
||||
var rows=state.Paragraphs.Skip((currentPage-1)*100).Take(100).ToArray();
|
||||
}
|
||||
<div class="container-fluid py-3">
|
||||
<a asp-controller="Books" asp-action="Details" asp-route-id="@state.BookId">Back to @Model.BookTitle</a>
|
||||
<h1>Manuscript structure and evidence</h1>
|
||||
<div class="alert alert-warning">Preview feature: book backup and saved-point replacement are blocked for tracked books until paragraph evidence portability is qualified. Use isolated test books; keep your original Word document.</div>
|
||||
<p class="text-muted">Word remains the source of your prose. These tools organise saved paragraphs and story evidence; they never edit your Word document.</p>
|
||||
@if(Model.Message!=null){<div role="status" class="alert alert-info">@Model.Message</div>}
|
||||
@if(state.Paragraphs.Count==0){
|
||||
<div class="card p-3"><h2>Enable paragraph tracking</h2><p>After completing a native manuscript import, adopt its accepted paragraph map. Existing unfinished imports are protected. No content is sent from Word by this action.</p>
|
||||
<form asp-action="Enable" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="mode" type="hidden" value="Manual"/><button class="btn btn-primary">Use saved manuscript capture</button></form></div>
|
||||
}else{
|
||||
@if(state.Paragraphs.Any(p=>p.Story&&!p.PositionVerified)){<div class="alert alert-warning">Some scene groupings need review. Their latest Word paragraphs are saved below; existing scene prose is retained until you confirm or adjust the grouping. Uncertain passages are not used as verified story evidence.</div>}
|
||||
<div class="card p-3 mb-3"><h2>Saved manuscript</h2><p>@state.Paragraphs.Count.ToString("N0") paragraphs · @current.Length scenes · Updated @state.UpdatedUtc.ToString("u")</p>
|
||||
<form asp-action="Enable" method="post" class="d-flex flex-wrap gap-2 align-items-end"><input name="bookId" type="hidden" value="@state.BookId"/>
|
||||
<label>Synchronisation <select name="mode" class="form-select"><option value="Manual" selected="@(state.Mode=="Manual")">Only when requested</option><option value="OnSave" selected="@(state.Mode=="OnSave")">After Word saves or reconnects</option><option value="Off" selected="@(state.Mode=="Off")">Off</option></select></label><button class="btn btn-outline-primary">Save preference</button></form>
|
||||
<p class="small mt-2">Save/reconnect mode explicitly permits manuscript updates from this book's associated Word document. Only changed prose is transmitted when the agent has a matching snapshot. It never starts AI analysis.</p>
|
||||
<div class="d-flex gap-2 flex-wrap"><form asp-action="Snapshot" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-primary">Synchronise from Word</button></form><form asp-action="Cancel" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-outline-secondary">Cancel pending snapshot</button></form><a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@state.BookId" asp-route-page="@currentPage">Refresh saved snapshot</a></div>
|
||||
<p class="small mt-2">A different Word manuscript must be imported into a separate book. This preview never guesses evidence identity across documents.</p>
|
||||
</div>
|
||||
<div class="card p-3 mb-3"><h2>Scenes</h2><p>Split at a paragraph or move a boundary using the paragraph list. Move prose and reorder scenes in Word, then synchronise.</p>
|
||||
<form asp-action="Change" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="undo"/><button class="btn btn-outline-secondary" disabled="@(state.Undo.Count==0)">Undo last structure change</button></form>
|
||||
@foreach(var scene in current){var sceneIndex=Array.IndexOf(current,scene);var adjacent=sceneIndex+1<current.Length?current[sceneIndex+1]:null;<details class="mt-2"><summary>@scene.Title @if(scene.NeedsRefinement){<span class="badge text-bg-warning">Needs refinement</span>}</summary><p>@state.Paragraphs.Count(p=>p.SceneId==scene.Id) paragraphs</p>
|
||||
@if(scene.NeedsRefinement&&scenePositions.ContainsKey(scene.Id)){<form asp-action="Change" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="group"/><input name="target" type="hidden" value="@scene.Id"/><button class="btn btn-outline-primary">Confirm these paragraphs belong in @scene.Title</button></form>}
|
||||
@if(adjacent!=null&&adjacent.ChapterId==scene.ChapterId&&scenePositions.ContainsKey(scene.Id)&&scenePositions.ContainsKey(adjacent.Id)){<form asp-action="Change" method="post" class="d-flex flex-wrap gap-2"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="merge"/><input name="target" type="hidden" value="@scene.Id"/><input name="other" type="hidden" value="@adjacent.Id"/><button class="btn btn-outline-secondary">Merge with @adjacent.Title</button></form>}</details>}
|
||||
</div>
|
||||
<h2>Paragraphs</h2><p>Page @currentPage of @Math.Max(1,(state.Paragraphs.Count+99)/100). Paragraph numbers describe this saved snapshot, not permanent identities.</p>
|
||||
<nav class="d-flex gap-2 mb-3"><a asp-route-bookId="@state.BookId" asp-route-page="@Math.Max(1,currentPage-1)" class="btn btn-outline-secondary">Previous</a><a asp-route-bookId="@state.BookId" asp-route-page="@(currentPage+1)" class="btn btn-outline-secondary">Next</a></nav>
|
||||
@foreach(var row in rows){var scene=current.FirstOrDefault(s=>s.Id==row.SceneId);<article class="card p-3 mb-2"><div class="small text-muted">Paragraph @(row.Occurrence.Ordinal+1) · @(scene?.Title??"Heading / front matter") @if(!row.PositionVerified&&row.Story){<strong> · Position needs review</strong>}</div><p class="mb-1" style="white-space:pre-wrap;overflow-wrap:anywhere">@row.Occurrence.Text</p>
|
||||
@if(row.Story){var boundaryChoices=current.Where((s,i)=>i>0&&s.ChapterId==current[i-1].ChapterId&&scenePositions.ContainsKey(s.Id)&&scenePositions.ContainsKey(current[i-1].Id)&&(s.Id==row.SceneId||current[i-1].Id==row.SceneId)&&row.Occurrence.Ordinal>scenePositions[current[i-1].Id]).ToArray();<details><summary>Adjust structure</summary>@if(scenePositions.GetValueOrDefault(row.SceneId!.Value,-1)!=row.Occurrence.Ordinal){<form asp-action="Change" method="post" class="d-flex gap-2 flex-wrap"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="split"/><input name="target" type="hidden" value="@row.Occurrence.Id"/><label>New scene title <input name="text" maxlength="200" required class="form-control"/></label><button class="btn btn-outline-secondary">Start a scene here</button></form>}else{<p class="small">This paragraph already starts a scene.</p>}
|
||||
@if(boundaryChoices.Length>0){<form asp-action="Change" method="post" class="d-flex gap-2 flex-wrap mt-2"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="boundary"/><input name="other" type="hidden" value="@row.Occurrence.Id"/><label>First paragraph of <select name="target" class="form-select">@foreach(var s in boundaryChoices){<option value="@s.Id">@s.Title</option>}</select></label><button class="btn btn-outline-secondary">Move adjacent boundary here</button></form>}</details>}
|
||||
</article>}
|
||||
<h2 class="mt-4">Story evidence</h2><p>Evidence changes never delete knowledge or relationship events. Unconfirmed primary evidence is excluded from verified continuity facts.</p>
|
||||
@if(state.Evidence.Count==0){<p>No paragraph evidence attached yet. Existing scene-based events continue to work.</p>}
|
||||
<nav class="d-flex gap-2 mb-2"><a asp-route-bookId="@state.BookId" asp-route-page="@currentPage" asp-route-evidencePage="@Math.Max(1,evidencePage-1)">Previous evidence</a><span>Evidence page @evidencePage of @Math.Max(1,(state.Evidence.Count+19)/20)</span><a asp-route-bookId="@state.BookId" asp-route-page="@currentPage" asp-route-evidencePage="@(evidencePage+1)">Next evidence</a></nav>
|
||||
@foreach(var evidence in state.Evidence.OrderBy(e=>e.State=="Verified").Skip((evidencePage-1)*20).Take(20)){var item=Model.Events.FirstOrDefault(e=>e.Kind==evidence.EventKind&&e.Id==evidence.EventId);<article class="card p-3 mb-2"><h3 class="h5">@(item?.Description??"Saved event")</h3><p><strong>@evidence.State</strong> · @(evidence.Primary?"Primary evidence":"Supporting evidence")</p><p class="small">Originally: @evidence.OriginalPosition<br/>Now: @evidence.CurrentPosition</p><div class="row"><div class="col-md-6"><h4 class="h6">Original supporting passage</h4><blockquote style="white-space:pre-wrap">@evidence.OriginalText</blockquote></div><div class="col-md-6"><h4 class="h6">Current passage</h4><blockquote style="white-space:pre-wrap">@(evidence.State=="Missing"?"Passage no longer found. Relink it below; the saved event is retained.":evidence.CurrentText)</blockquote></div></div>
|
||||
<div class="d-flex gap-2 flex-wrap">@foreach(var action in new[]{"confirm","unlink"}){<form asp-action="Change" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="target" type="hidden" value="@evidence.Id"/><input name="action" type="hidden" value="@action"/><button class="btn btn-outline-secondary">@(action=="confirm"?"Confirm current evidence":"Detach evidence; keep event")</button></form>}@if(item!=null){<a asp-controller="Scenes" asp-action="Details" asp-route-id="@item.SceneId" class="btn btn-outline-secondary">Edit or remove event in scene</a>}</div>
|
||||
<details class="mt-2"><summary>Relink to another passage</summary><form asp-action="Change" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="target" type="hidden" value="@evidence.Id"/><input name="action" type="hidden" value="relink"/><label>From paragraph <input type="number" name="from" min="1" max="@state.Paragraphs.Count" required/></label><label>To paragraph <input type="number" name="to" min="1" max="@state.Paragraphs.Count" required/></label><button class="btn btn-outline-primary">Relink and confirm</button></form></details>
|
||||
</article>}
|
||||
<details class="card p-3"><summary>Attach evidence to an existing event</summary><form asp-action="Change" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="anchor"/>
|
||||
<label>Saved event <select name="eventKey" class="form-select">@foreach(var item in Model.Events){<option value="@(item.Kind+":"+item.Id)">@item.Kind · @item.Description</option>}</select></label><p class="small">The event type and account scope are validated together before saving.</p>
|
||||
<div class="d-flex gap-2 flex-wrap"><label>From paragraph <input name="from" type="number" min="1" max="@state.Paragraphs.Count" required class="form-control"/></label><label>To paragraph <input name="to" type="number" min="1" max="@state.Paragraphs.Count" required class="form-control"/></label><label>Start character (optional, from 0)<input name="startOffset" type="number" min="0" class="form-control"/></label><label>End character (optional, exclusive)<input name="endOffset" type="number" min="0" class="form-control"/></label></div><label><input name="primary" type="checkbox" value="true" checked/> Primary evidence; derive event scene when verified</label><button class="btn btn-primary d-block mt-2">Attach and confirm passage</button></form></details>
|
||||
}
|
||||
</div>
|
||||
@ -26,6 +26,7 @@
|
||||
<span class="scene-structure-marker">@item.KnowledgeStateName</span>
|
||||
</div>
|
||||
|
||||
@if(item.EvidenceState!="Verified"){<p class="text-warning">Manuscript evidence: @item.EvidenceState. Review the saved passage before treating this event as confirmed.</p>}
|
||||
@if (!string.IsNullOrWhiteSpace(item.Description))
|
||||
{
|
||||
<p>@item.Description</p>
|
||||
|
||||
@ -27,6 +27,7 @@
|
||||
</div>
|
||||
|
||||
<p class="muted">Intensity @(item.Intensity?.ToString() ?? "not set")@(item.IsKnownToOtherCharacter ? " / known to other character" : "")</p>
|
||||
@if(item.EvidenceState!="Verified"){<p class="text-warning">Manuscript evidence: @item.EvidenceState. Review the saved passage before treating this event as confirmed.</p>}
|
||||
@if (!string.IsNullOrWhiteSpace(item.Description))
|
||||
{
|
||||
<p>@item.Description</p>
|
||||
|
||||
@ -365,7 +365,7 @@
|
||||
button.disabled = true;
|
||||
applyScanState({ status: "Running", message: "Asking the Word Companion to scan...", percentComplete: 0 });
|
||||
try {
|
||||
const state = await connection.invoke("StartOnboardingManuscriptScan");
|
||||
const state = await connection.invoke(document.querySelector("[data-paragraph-tracking]")?.checked ? "StartParagraphManuscriptScan" : "StartOnboardingManuscriptScan");
|
||||
applyScanState(state);
|
||||
} catch (error) {
|
||||
applyScanState({
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user