Capture accepted writing activity atomically with private retention and native retry queue
This commit is contained in:
parent
0520326b2a
commit
a1c616fbb6
38
Docs/Sprints/Writer2/Implementation.md
Normal file
38
Docs/Sprints/Writer2/Implementation.md
Normal file
@ -0,0 +1,38 @@
|
||||
# Writer 2.0 implementation sprint
|
||||
|
||||
Authorisation: attached overnight implementation instructions, following the approved Writer2_Spec.md and complete Writer2Audit. Work remains on `codex/word-companion-native-phase1-20261104`; fetch at start found no divergence. Existing untracked CanonicalManuscriptArchitectureAssessment.md is not part of this sprint.
|
||||
|
||||
## Capture decisions
|
||||
|
||||
The first increment retains counts and identifiers, not a second manuscript or historical prose archive. The existing paragraph manuscript and chapter acceptance engine remain authoritative. `ParagraphManuscriptRepository` holds the canonical row lock and commits the established stored-procedure save and activity append together. A failed append rolls back that acceptance; Word's document is unchanged and the caller may retry. No unchanged chapter validation is counted as writing output.
|
||||
|
||||
Events have server receipt UTC, optional native observation UTC, source/provenance, request/event identity, schema/metric version, manuscript/book/project, optional transport session/chapter and old/new paragraph/scene associations. Snapshot references are hashes/revisions; old prose cannot be reconstructed from this ledger. Initial or explicit current baseline contributes no new writing output. Existing manuscripts receive a baseline on their first recorded change, or an owner can explicitly record the current accepted baseline. No historical backfill is fabricated.
|
||||
|
||||
Word changes use whitespace-v1 tokens and paragraph-local LCS; recognised moved paragraphs retain identity without new words, unmatched splits/merges are compared together. Very large replacement comparisons use an explicitly labelled partial minimum token-balance estimate to bound processing. Additions minus removals always equals the comparable word-count difference; these are sampled accepted differences, not keystrokes. Formatting not present in capture cannot be measured. No sessions or continuous focus duration are inferred.
|
||||
|
||||
### Retention/privacy defaults for Development
|
||||
|
||||
- Capture metadata is enabled by default; author can pause per book without stopping manuscript synchronisation.
|
||||
- Events default to 365 days, configurable from 30 to 3650 days. A daily worker expires events; shortening retention applies immediately.
|
||||
- Activity is owner-private in this increment. Existing broad project collaborators are not granted the new activity views/export/controls.
|
||||
- Explicit confirmed erase removes retained events and pauses capture; manuscript data remains intact.
|
||||
- Compact request/hash receipts survive event expiry/erasure until permanent book deletion to prevent replay inflation. They retain no prose. Book hard deletion cascades both metadata tables/settings. Normal APIs never update activity events; retention/erasure are deliberate exceptions to append-only storage.
|
||||
- JSON evidence export is bounded and cursor-paged. Activity is operational history, not part of the current manuscript/project portable recovery format. Existing database backups may contain separate copies; erasing live history does not erase prior backups or downloaded exports. Restore/copy is not certified as a continuous provenance chain. Production retention/backup policy remains a separate deployment decision.
|
||||
|
||||
### Native delivery
|
||||
|
||||
The agent's existing DPAPI-protected installation state now holds up to 128 source observations with immutable event identities, server/account scope and original UTC. No prose is queued. Known unsaved chapter-change signals use this queue; delivery waits for normal authenticated connection recovery, runs independently of manuscript synchronisation and acknowledges exact request identity. Entries survive a restart, transient failures and sign-out/account switching without being reassigned to another account. Failed deliveries back off and remain pending; queue/storage failures expose incomplete observation coverage rather than changing sync behaviour.
|
||||
|
||||
The old coalescing DeferredWorkQueue is deliberately not connected as a prose sender: it cannot preserve exact activity observations and contains no text. Final saved offline changes still reconcile via the established synchronisation path; the new queue does not claim to capture edits that were never observed, survive every Word crash, or reconstruct offline sessions. Observations outside the server's 30-day/five-minute-future window are retained locally pending resolution, not falsely timestamped at receipt. A blocked or full queue needs attention; it does not stop normal manuscript synchronisation.
|
||||
|
||||
Native source/portable qualification is distinct from Windows installer/COM acceptance. No Windows execution, real monitor placement or signed installer is claimed by this sprint.
|
||||
|
||||
## Migration compatibility review
|
||||
|
||||
259 is additive: new metadata/settings/receipt tables and stored procedures; no existing canonical procedure or numbered migration is edited. It contains no manuscript backfill or existing text update. New tables cascade only on intentional book deletion; no new chapter/scene foreign key prevents existing reorganisation. Existing binaries can run with this added schema. Rolling back to an old binary stops new activity capture and therefore creates a coverage gap; it does not remove manuscript data. Application rollback is not SQL rollback.
|
||||
|
||||
Before any Development application deployment, apply and verify the qualified additive migration against the verified effective Development database after backup. The disposable clone is `PlotDirector_Writer2_Synthetic_20261114`; it was restored to new files from the copy-only/checksum-verified backup `writer2-before-259-20261114.bak`. Existing Development was not restored/reset.
|
||||
|
||||
## Qualification and delivery
|
||||
|
||||
Actual final results, commits and deployment evidence are recorded in SprintResults.md when complete. The implementation preserves old endpoints and full/selective chapter reconciliation. The complete six-destination Writer product, flexible planning wizard, measured sessions, parallel passes, insights/collaboration and signed reports remain separate gates unless explicitly listed as delivered.
|
||||
@ -35,7 +35,7 @@ public sealed partial class CloudGateway
|
||||
public async Task RunConnectionLoop(CancellationToken cancellation)
|
||||
{
|
||||
using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellation,lifetime.Token);
|
||||
try{while(!stop.IsCancellationRequested){try{await DrainRevocations();bool approved;lock(gate)approved=saved.Active!=null;if(approved&&Now>=retryAfter){await EnsureAccess(authenticationContext);if(health.State!="Connected"||Now.UtcDateTime>=nextCheck)await CheckConnection();else if(health.State=="Connected"&&Now.UtcDateTime-health.VerifiedUtc>=TimeSpan.FromSeconds(25)){var context=authenticationContext;var beat=await Post<HeartbeatReply>("api/native-companion/heartbeat",new{},context);await ObserveCatalog(beat.CatalogVersion,context);}}}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}await Task.Delay(TimeSpan.FromSeconds(2),stop.Token);}}
|
||||
try{while(!stop.IsCancellationRequested){try{await DrainRevocations();bool approved;lock(gate)approved=saved.Active!=null;if(approved&&Now>=retryAfter){await EnsureAccess(authenticationContext);if(health.State!="Connected"||Now.UtcDateTime>=nextCheck)await CheckConnection();else if(health.State=="Connected"&&Now.UtcDateTime-health.VerifiedUtc>=TimeSpan.FromSeconds(25)){var context=authenticationContext;var beat=await Post<HeartbeatReply>("api/native-companion/heartbeat",new{},context);await ObserveCatalog(beat.CatalogVersion,context);}if(health.State=="Connected")_ = DrainWritingObservations();}}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}await Task.Delay(TimeSpan.FromSeconds(2),stop.Token);}}
|
||||
catch(OperationCanceledException)when(stop.IsCancellationRequested){}
|
||||
}
|
||||
public async Task ReconnectAsync(){if(storageUnavailable)RestoreState();lock(gate){retryAfter=DateTimeOffset.MinValue;nextCheck=DateTime.MinValue;}try{await EnsureAccess(authenticationContext);await CheckConnection();}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}}
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
public sealed class QueuedWritingObservation
|
||||
{
|
||||
public string Site { get; set; } = "";
|
||||
public int Account { get; set; }
|
||||
public WritingObservation Observation { get; set; } = new();
|
||||
}
|
||||
public sealed partial class CloudGateway
|
||||
{
|
||||
private DateTimeOffset activityRetryUtc;
|
||||
private readonly SemaphoreSlim activityDelivery=new(1,1);
|
||||
public async Task<bool> QueueWritingObservation(int book,Guid manuscript,int chapter,Guid session,long revision,Guid context)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock(gate)
|
||||
{
|
||||
if(storage==null||!stateLoaded||saved.Active==null||authenticationContext!=context||book<=0||manuscript==Guid.Empty||chapter<=0)return false;
|
||||
var hash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{manuscript:D}|{chapter}|{session:D}|{revision}")));
|
||||
if(saved.WritingObservations.Any(q=>q.Site==saved.Active.Site&&q.Account==saved.Active.AccountId&&q.Observation.PayloadHash==hash))return true;
|
||||
if(saved.WritingObservations.Count>=128){health.Explanation="Activity observation queue is full. Manuscript synchronisation remains available; some observation coverage is unavailable.";return false;}
|
||||
saved.WritingObservations.Add(new(){Site=saved.Active.Site,Account=saved.Active.AccountId,Observation=new(){BookID=book,ManuscriptID=manuscript,ChapterID=chapter,ObservedUtc=Now.UtcDateTime,PayloadHash=hash}});
|
||||
}
|
||||
await FlushSettingsAsync();return true;
|
||||
}
|
||||
catch(Exception e)when(StorageFailure(e)){lock(gate)health.Explanation="Activity observations could not be saved securely; observation coverage may be incomplete. Manuscript synchronisation is unchanged.";return false;}
|
||||
}
|
||||
public async Task DrainWritingObservations()
|
||||
{
|
||||
if(!await activityDelivery.WaitAsync(0))return;
|
||||
try
|
||||
{
|
||||
QueuedWritingObservation? item;Guid context;
|
||||
lock(gate){if(Now<activityRetryUtc)return;context=authenticationContext;item=saved.Active==null?null:saved.WritingObservations.FirstOrDefault(q=>q.Site==saved.Active.Site&&q.Account==saved.Active.AccountId);}
|
||||
if(item==null)return;
|
||||
var receipt=await Post<WritingObservation>("api/native-companion/writing-activity",item.Observation,context);
|
||||
if(receipt.RequestID!=item.Observation.RequestID)throw new InvalidDataException("Activity acknowledgement identity differs.");
|
||||
lock(gate){if(context!=authenticationContext)return;saved.WritingObservations.Remove(item);}
|
||||
await FlushSettingsAsync();
|
||||
}
|
||||
catch(Exception e)when(AuthFailure(e)){lock(gate){activityRetryUtc=Now.AddMinutes(1);health.Explanation="Activity observations are waiting for delivery. Manuscript synchronisation remains independent.";}}
|
||||
finally{activityDelivery.Release();}
|
||||
}
|
||||
}
|
||||
@ -18,6 +18,7 @@ public sealed class CompanionPreferences
|
||||
}
|
||||
public sealed class CompanionState
|
||||
{
|
||||
public List<QueuedWritingObservation> WritingObservations {get;set;}=[];
|
||||
public int Version {get;set;}=1;public string Server {get;set;}="";public int AccountId {get;set;}public string AccountName {get;set;}="";public TrustedInstallation? Active {get;set;}public List<TrustedInstallation> Revocations {get;set;}=[];public Dictionary<string,int> Bindings {get;set;}=[];public CompanionPreferences Preferences {get;set;}=new();
|
||||
}
|
||||
public sealed class CompanionStorageException(string message,Exception? inner=null):IOException(message,inner);
|
||||
@ -46,7 +47,7 @@ public sealed class ProtectedCompanionStateStore(string path,IStateProtection pr
|
||||
private readonly object gate=new();private FileStream? owner;
|
||||
private void Own(){if(owner!=null)return;Directory.CreateDirectory(Path.GetDirectoryName(path)!);owner=new(path+".lock",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);}
|
||||
private static byte[] Entropy(string site,int account)=>SHA256.HashData(Encoding.UTF8.GetBytes("PlotDirector.Companion.State.v1|"+site+"|"+account));
|
||||
public CompanionState Load(){lock(gate){Own();if(!File.Exists(path))return new();if(new FileInfo(path).Length>2*1024*1024)throw new CryptographicException("Invalid Companion settings size.");var envelope=JsonSerializer.Deserialize<Envelope>(File.ReadAllBytes(path))??throw new CryptographicException("Invalid protected settings.");if(envelope.Version!=1||envelope.Protected==null)throw new CryptographicException("Unsupported protected settings.");var clear=protection.Unprotect(envelope.Protected,Entropy(envelope.Site,envelope.Account));try{var state=JsonSerializer.Deserialize<CompanionState>(clear)??throw new CryptographicException("Invalid protected settings.");if(state.Version!=1||state.Server!=envelope.Site||state.AccountId!=envelope.Account||state.Revocations.Count>16||state.Bindings.Count>2048)throw new CryptographicException("Settings scope mismatch.");return state;}finally{CryptographicOperations.ZeroMemory(clear);}}}
|
||||
public CompanionState Load(){lock(gate){Own();if(!File.Exists(path))return new();if(new FileInfo(path).Length>2*1024*1024)throw new CryptographicException("Invalid Companion settings size.");var envelope=JsonSerializer.Deserialize<Envelope>(File.ReadAllBytes(path))??throw new CryptographicException("Invalid protected settings.");if(envelope.Version!=1||envelope.Protected==null)throw new CryptographicException("Unsupported protected settings.");var clear=protection.Unprotect(envelope.Protected,Entropy(envelope.Site,envelope.Account));try{var state=JsonSerializer.Deserialize<CompanionState>(clear)??throw new CryptographicException("Invalid protected settings.");if(state.Version!=1||state.Server!=envelope.Site||state.AccountId!=envelope.Account||state.Revocations.Count>16||state.Bindings.Count>2048||state.WritingObservations==null||state.WritingObservations.Count>128)throw new CryptographicException("Settings scope mismatch.");return state;}finally{CryptographicOperations.ZeroMemory(clear);}}}
|
||||
public void Save(CompanionState state){lock(gate){Own();var clear=JsonSerializer.SerializeToUtf8Bytes(state);try{if(clear.Length>1024*1024)throw new IOException("Companion settings capacity exceeded.");var bytes=JsonSerializer.SerializeToUtf8Bytes(new Envelope(1,state.Server,state.AccountId,protection.Protect(clear,Entropy(state.Server,state.AccountId))));var temp=path+"."+Guid.NewGuid().ToString("N")+".tmp";try{using(var file=new FileStream(temp,FileMode.CreateNew,FileAccess.Write,FileShare.None,4096,FileOptions.WriteThrough)){file.Write(bytes);file.Flush(true);}File.Move(temp,path,true);}finally{if(File.Exists(temp))File.Delete(temp);}}finally{CryptographicOperations.ZeroMemory(clear);}}}
|
||||
public void Dispose(){lock(gate){owner?.Dispose();owner=null;}}
|
||||
}
|
||||
|
||||
@ -246,7 +246,7 @@ public sealed partial class TrayCoordinator
|
||||
if(message.Kind=="chapter-observe")
|
||||
{
|
||||
if(!work.ObserveOnly||message.ChapterId!=work.ExpectedProbeChapter||message.ChapterId==null||work.Manifest==null)return;
|
||||
if(message.Action=="changed")work.Dirty.Add(message.ChapterId.Value);else work.Dirty.Remove(message.ChapterId.Value);
|
||||
if(message.Action=="changed"){if(work.Dirty.Add(message.ChapterId.Value))_ = cloud.QueueWritingObservation(doc.Book,doc.Manuscript,message.ChapterId.Value,doc.Session,doc.Revision,doc.Authentication);}else work.Dirty.Remove(message.ChapterId.Value);
|
||||
work.Visited.Add(message.ChapterId.Value);work.Calculated++;work.Busy=false;work.Processing=false;work.Command=Guid.Empty;
|
||||
AdvanceChapter(doc,work);return;
|
||||
}
|
||||
|
||||
11
PlotDirector.NativeCompanion/Protocol/WritingObservation.cs
Normal file
11
PlotDirector.NativeCompanion/Protocol/WritingObservation.cs
Normal file
@ -0,0 +1,11 @@
|
||||
namespace PlotDirector.Companion.Protocol;
|
||||
// Metadata only. A change signal is not accepted prose or a measured focus session.
|
||||
public sealed class WritingObservation
|
||||
{
|
||||
public Guid RequestID { get; set; } = Guid.NewGuid();
|
||||
public int BookID { get; set; }
|
||||
public Guid ManuscriptID { get; set; }
|
||||
public int? ChapterID { get; set; }
|
||||
public DateTime ObservedUtc { get; set; }
|
||||
public string PayloadHash { get; set; } = "";
|
||||
}
|
||||
@ -14,12 +14,19 @@ internal static class PersistentConnectionTests
|
||||
cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");
|
||||
cloud.RememberBinding(manuscript,3);cloud.SavePreferences(new(){AdvancedMode=true,Width=975,Height=725,RememberInDocument=true,LastManuscript=manuscript});await cloud.FlushSettingsAsync();
|
||||
check(approvals==1&&store.Load().Active!=null,"first pairing saves approved installation, not a four-hour-only sign-in");
|
||||
server.Offline=true;
|
||||
check(await cloud.QueueWritingObservation(3,manuscript,10,manuscript,1,cloud.Status().AuthenticationContext),"native activity observation persists before offline delivery");
|
||||
var queuedID=store.Load().WritingObservations.Single().Observation.RequestID;
|
||||
await cloud.QueueWritingObservation(3,manuscript,10,manuscript,1,cloud.Status().AuthenticationContext);
|
||||
await cloud.DrainWritingObservations();check(store.Load().WritingObservations.Count==1&&store.Load().WritingObservations[0].Observation.RequestID==queuedID,"offline retries preserve immutable identity without duplicate queue entries");
|
||||
check(!JsonSerializer.Serialize(store.Load()).Contains("access:"),"short-lived access tokens are never persisted in settings");
|
||||
}
|
||||
check(!server.Revoked&&store.Load().Active!=null,"normal process disposal preserves trust and settings");
|
||||
server.Offline=true;using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
|
||||
using var stop=new CancellationTokenSource();var loop=cloud.RunConnectionLoop(stop.Token);await Until(()=>cloud.Status().Health?.State=="Reconnecting");await Task.Delay(200);check(server.RenewAttempts==1,"offline startup makes a bounded renewal attempt without browser approval");
|
||||
server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await Until(()=>cloud.Status().Health?.State=="Connected");stop.Cancel();await loop;
|
||||
await Until(()=>store.Load().WritingObservations.Count==0);
|
||||
check(server.ActivityIDs.Count==1,"native restart recovers and acknowledges durable observation without prose upload");
|
||||
check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument&&cloud.Preferences.AdvancedMode,"process/network recovery restores scoped association and preferences without interaction");
|
||||
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);
|
||||
var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();
|
||||
@ -75,7 +82,7 @@ internal static class PersistentConnectionTests
|
||||
private sealed class Clock:TimeProvider{public DateTimeOffset Time=new(2026,11,6,12,0,0,TimeSpan.Zero);public override DateTimeOffset GetUtcNow()=>Time;public void Advance(TimeSpan elapsed)=>Time+=elapsed;}
|
||||
private sealed class Server(Clock clock):HttpMessageHandler
|
||||
{
|
||||
public bool Offline,Revoked,AllowBook=true,LoseRenewalResponse;public int Account=7,RenewAttempts,ProseRequests;private Guid installation,connection,lastRotation;private string current="",previous="";private Guid pairingConnection;
|
||||
public HashSet<Guid> ActivityIDs=[];public bool Offline,Revoked,AllowBook=true,LoseRenewalResponse;public int Account=7,RenewAttempts,ProseRequests;private Guid installation,connection,lastRotation;private string current="",previous="";private Guid pairingConnection;
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
||||
{
|
||||
var action=request.RequestUri!.AbsolutePath.Split('/').Last();if(action=="renew")RenewAttempts++;if(Offline)throw new HttpRequestException("Synthetic offline");
|
||||
@ -92,6 +99,7 @@ internal static class PersistentConnectionTests
|
||||
if(LoseRenewalResponse){LoseRenewalResponse=false;throw new HttpRequestException("Synthetic response lost after commit");}result=Tokens(false);
|
||||
}
|
||||
else if(action=="revoke"){var credential=payload.GetProperty("credential").GetString();if(credential==current||credential==previous)Revoked=true;return new(HttpStatusCode.NoContent);}
|
||||
else if(action=="writing-activity"){var id=payload.GetProperty("requestID").GetGuid();ActivityIDs.Add(id);result=new{requestID=id};}
|
||||
else if(action=="books")result=AllowBook?new[]{new CompanionBook{BookId=Account==7?3:4,Title="Allowed synthetic book"}}:[];
|
||||
else result=new ConnectionHealth{Server="online",Authentication="verified",ExpiresUtc=clock.Time.AddMinutes(10).UtcDateTime,VerifiedUtc=clock.Time.UtcDateTime};
|
||||
return Reply(HttpStatusCode.OK,result);
|
||||
|
||||
@ -25,6 +25,8 @@ if(args.Contains("--geography-database")){await GeographyDatabaseTests.Run();ret
|
||||
if(args.Contains("--geography")){await GeographyTests.Run();return;}
|
||||
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--writing-activity-database")){await WritingActivityDatabaseTests.Run();return;}
|
||||
if(args.Contains("--writing-activity")){WritingActivityTests.Run();return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
|
||||
if(args.Contains("--manuscript-reader")){await ManuscriptReaderTests.Run();return;}
|
||||
#pragma warning disable CS8321
|
||||
@ -166,6 +168,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()),
|
||||
("Writing activity measurement", WritingActivityTests.Run),
|
||||
("Manuscript Reader", () => ManuscriptReaderTests.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()),
|
||||
|
||||
60
PlotLine.Tests/WritingActivityDatabaseTests.cs
Normal file
60
PlotLine.Tests/WritingActivityDatabaseTests.cs
Normal file
@ -0,0 +1,60 @@
|
||||
using System.Diagnostics;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
internal static class WritingActivityDatabaseTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
// This test may only target the explicitly provisioned disposable clone, never Development.
|
||||
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
|
||||
using var process=Process.Start(start)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Configuration inaccessible");
|
||||
var raw=environment.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
|
||||
var builder=new SqlConnectionStringBuilder(raw);if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Unexpected configured database");builder.InitialCatalog="PlotDirector_Writer2_Synthetic_20261114";
|
||||
using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=builder.InitialCatalog)throw new Exception("Wrong synthetic target");
|
||||
void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS writing activity database "+name);}
|
||||
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{["ConnectionStrings:DefaultConnection"]=builder.ConnectionString}).Build();
|
||||
var factory=new SqlConnectionFactory(config);var repository=new ParagraphManuscriptRepository(factory);var activity=new WritingActivityRepository(factory);
|
||||
var fixture=await db.QuerySingleAsync<(int UserID,int ProjectID,int BookID)>("""
|
||||
DECLARE @u int,@p int,@b int,@l int;
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@writer.invalid','Synthetic Writer','not-a-credential');SET @u=SCOPE_IDENTITY();
|
||||
INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),'Writer fixture',10,100,100,100,100,0,0,0);SET @l=SCOPE_IDENTITY();
|
||||
INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@u,@l,1,1,'2030-01-01');
|
||||
INSERT dbo.Projects(ProjectName) VALUES('Synthetic Writer activity');SET @p=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@p,@u,'Owner',1);
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Synthetic Writer activity',1,1);SET @b=SCOPE_IDENTITY();
|
||||
SELECT @u UserID,@p ProjectID,@b BookID;
|
||||
""");
|
||||
var manuscript=Guid.NewGuid();var paragraph=Guid.NewGuid();
|
||||
ParagraphManuscript State(string text)=>new(){BookId=fixture.BookID,ProjectId=fixture.ProjectID,ManuscriptId=manuscript,Mode="Manual",SnapshotHash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text))),Paragraphs=[new(){Occurrence=new(){Id=paragraph,Text=text,Ordinal=0,Start=0,End=text.Length}}]};
|
||||
try
|
||||
{
|
||||
var id=Guid.NewGuid();var first=await repository.Save(fixture.UserID,State("one two three\r"),-1,id);
|
||||
Check(first.Revision==1&&(await activity.Read(fixture.UserID,fixture.BookID)).Events.Single().Kind=="Baseline","initialisation stores baseline without growth");
|
||||
var nextID=Guid.NewGuid();var next=await repository.Save(fixture.UserID,State("one new three four\r"),1,nextID);
|
||||
var page=await activity.Read(fixture.UserID,fixture.BookID);Check(page.Added==2&&page.Removed==1,"accepted transition and counts committed");
|
||||
await repository.Save(fixture.UserID,State("one new three four\r"),1,nextID);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==2,"exact retry is not counted twice");
|
||||
var observation=new WritingObservation{BookID=fixture.BookID,ManuscriptID=manuscript,ObservedUtc=DateTime.UtcNow,PayloadHash=new string('A',64)};
|
||||
await activity.Observe(fixture.UserID,observation);await activity.Observe(fixture.UserID,observation);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==3,"queued observation retry is idempotent");
|
||||
observation.PayloadHash=new string('B',64);var rejected=false;try{await activity.Observe(fixture.UserID,observation);}catch(SqlException){rejected=true;}Check(rejected,"same observation identity with conflicting payload rejected");
|
||||
var wrongDocument=new WritingObservation{BookID=fixture.BookID,ManuscriptID=Guid.NewGuid(),ObservedUtc=DateTime.UtcNow,PayloadHash=new string('C',64)};
|
||||
rejected=false;try{await activity.Observe(fixture.UserID,wrongDocument);}catch(SqlException){rejected=true;}Check(rejected,"document switching cannot attach activity to another manuscript");
|
||||
rejected=false;try{await activity.Read(int.MaxValue,fixture.BookID);}catch(SqlException){rejected=true;}Check(rejected,"foreign account cannot read activity");
|
||||
wrongDocument.ManuscriptID=manuscript;wrongDocument.ObservedUtc=DateTime.UtcNow.AddHours(1);
|
||||
rejected=false;try{await activity.Observe(fixture.UserID,wrongDocument);}catch(SqlException){rejected=true;}Check(rejected,"future client clock is not accepted as precise evidence");
|
||||
var submissions=await Task.WhenAll(Enumerable.Range(0,2).Select(async i=>{try{await repository.Save(fixture.UserID,State("concurrent "+i+"\r"),next.Revision,Guid.NewGuid());return true;}catch(SqlException){return false;}}));Check(submissions.Count(x=>x)==1,"concurrent expected revisions accept only one transition");
|
||||
var current=(await repository.Get(fixture.UserID,fixture.BookID))!;
|
||||
await db.ExecuteAsync($"CREATE OR ALTER TRIGGER dbo.Writer2_TestReject ON dbo.WritingActivityEvents AFTER INSERT AS IF EXISTS(SELECT 1 FROM inserted WHERE BookID={fixture.BookID}) THROW 51000,'Synthetic append failure',1;");
|
||||
try{rejected=false;try{await repository.Save(fixture.UserID,State("must roll back\r"),current.Revision,Guid.NewGuid());}catch(SqlException){rejected=true;}Check(rejected&&(await repository.Get(fixture.UserID,fixture.BookID))!.SnapshotHash==current.SnapshotHash,"partial activity failure rolls back canonical acceptance");}finally{await db.ExecuteAsync("DROP TRIGGER dbo.Writer2_TestReject");}
|
||||
await activity.Configure(fixture.UserID,fixture.BookID,false,30);var count=(await activity.Read(fixture.UserID,fixture.BookID)).Events.Count;await repository.Save(fixture.UserID,State("capture paused\r"),current.Revision,Guid.NewGuid());Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==count,"privacy pause does not block manuscript sync or record activity");
|
||||
await activity.Erase(fixture.UserID,fixture.BookID);Check((await activity.Read(fixture.UserID,fixture.BookID)).Events.Count==0,"owner erasure leaves manuscript intact and capture paused");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.ExecuteAsync("DELETE dbo.Books WHERE BookID=@BookID;DELETE dbo.ProjectUserAccess WHERE ProjectID=@ProjectID;DELETE dbo.Projects WHERE ProjectID=@ProjectID;DECLARE @l int=(SELECT SubscriptionLevelID FROM dbo.UserSubscription WHERE UserID=@UserID);DELETE dbo.UserSubscription WHERE UserID=@UserID;DELETE dbo.SubscriptionLevel WHERE SubscriptionLevelID=@l;DELETE dbo.AppUser WHERE UserID=@UserID",new{fixture.UserID,fixture.ProjectID,fixture.BookID});
|
||||
}
|
||||
}
|
||||
}
|
||||
21
PlotLine.Tests/WritingActivityTests.cs
Normal file
21
PlotLine.Tests/WritingActivityTests.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.WritingActivity;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
internal static class WritingActivityTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS writing activity "+message);}
|
||||
ParagraphManuscript State(params (Guid Id,string Text)[] rows)=>new(){Paragraphs=rows.Select((r,i)=>new StoryParagraph{ChapterId=10,Occurrence=new ParagraphOccurrence{Id=r.Id,Ordinal=i,Text=r.Text}}).ToList()};
|
||||
var id=Guid.NewGuid();var other=Guid.NewGuid();var before=State((id,"one two three\r"),(other,"four five\r"));
|
||||
var baseline=WritingChangeCalculator.Compare(null,before);Check(baseline.AfterWords==5&&baseline.Added==0&&baseline.Removed==0,"baseline excludes pre-existing words");
|
||||
var after=State((id,"one new three\r"),(other,"four five\r"));var c=WritingChangeCalculator.Compare(before,after);
|
||||
Check(c.Added==1&&c.Removed==1&&c.Net==0,"zero-net replacement retains both sides");
|
||||
c=WritingChangeCalculator.Compare(before,State((other,"four five\r"),(id,"one two three\r")));Check(c.Added==0&&c.Removed==0,"moving stable paragraphs has no word growth");
|
||||
c=WritingChangeCalculator.Compare(before,State((id,"one\t two three\n"),(other,"four five\r")));Check(c.Net==0&&c.Added==0,"whitespace-only change has no word growth");
|
||||
c=WritingChangeCalculator.Compare(before,State((other,"four five\r")));Check(c.Removed==3&&c.Added==0&&c.Scopes.Single().BeforeChapterID==10,"deletion preserves old paragraph scope");
|
||||
c=WritingChangeCalculator.Compare(before,State((Guid.NewGuid(),"one two\r"),(Guid.NewGuid(),"three\r"),(other,"four five\r")));Check(c.Added==0&&c.Removed==0,"paragraph split does not invent growth");
|
||||
c=WritingChangeCalculator.Compare(before,State((id,"one two three six seven\r"),(other,"four five\r")));Check(c.Added==2&&c.Net==c.AfterWords-c.BeforeWords,"gross and net reconcile");
|
||||
c=WritingChangeCalculator.Compare(State((id,string.Join(' ',Enumerable.Repeat("a",2000)))),State((id,string.Join(' ',Enumerable.Repeat("b",2000)))));Check(c.Coverage.StartsWith("Partial")&&c.Added==2000&&c.Removed==2000,"large replacement explicitly qualifies token balance");
|
||||
}
|
||||
}
|
||||
50
PlotLine/Controllers/WritingActivityController.cs
Normal file
50
PlotLine/Controllers/WritingActivityController.cs
Normal file
@ -0,0 +1,50 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
namespace PlotLine.Controllers;
|
||||
[Authorize]
|
||||
public sealed class WritingActivityController(WritingActivityRepository activity,IBookRepository books):Controller
|
||||
{
|
||||
private int Actor => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpGet("Writer/Activity")]
|
||||
public async Task<IActionResult> Index(int bookId,long? before=null)
|
||||
{
|
||||
try { var page=await activity.Read(Actor,bookId,before);page.Book=await books.GetAsync(bookId);return View(page); }
|
||||
catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
}
|
||||
[HttpPost("Writer/Activity/Baseline"),ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Baseline(int bookId)
|
||||
{
|
||||
try{await activity.Baseline(Actor,bookId);return RedirectToAction(nameof(Index),new{bookId});}
|
||||
catch(SqlException e)when(e.Number==51000){return NotFound();}catch(InvalidOperationException e){return BadRequest(e.Message);}
|
||||
}
|
||||
[HttpPost("Writer/Activity/Settings"),ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Settings(int bookId,bool enabled,int retentionDays)
|
||||
{
|
||||
if(retentionDays is <30 or >3650)return BadRequest("Choose retention between 30 and 3650 days.");
|
||||
try{await activity.Configure(Actor,bookId,enabled,retentionDays);return RedirectToAction(nameof(Index),new{bookId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
}
|
||||
[HttpPost("Writer/Activity/Erase"),ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Erase(int bookId,bool confirm)
|
||||
{
|
||||
if(!confirm)return BadRequest("Confirm deletion of activity history.");
|
||||
try{await activity.Erase(Actor,bookId);return RedirectToAction(nameof(Index),new{bookId});}catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
}
|
||||
[HttpGet("Writer/Activity/Export")]
|
||||
public async Task<IActionResult> Export(int bookId,long? before=null)
|
||||
{
|
||||
try{var page=await activity.Read(Actor,bookId,before);return File(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new{coverage="Up to 500 retained records; use before cursor for earlier pages",page.BookID,page.Events})),"application/json","writing-activity.json");}catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
}
|
||||
[HttpPost("api/native-companion/writing-activity"),Authorize(AuthenticationSchemes=DesktopPairing.Scheme),RequestSizeLimit(4096)]
|
||||
public async Task<IActionResult> Observe([FromBody]WritingObservation observation)
|
||||
{
|
||||
if(observation==null||observation.RequestID==Guid.Empty||observation.ManuscriptID==Guid.Empty||observation.BookID<=0||observation.PayloadHash==null||observation.PayloadHash.Length!=64||!observation.PayloadHash.All(Uri.IsHexDigit))return BadRequest();
|
||||
try{await activity.Observe(Actor,observation);return Ok(new{observation.RequestID});}catch(SqlException e)when(e.Number==51000){return Conflict(new{code="activity_scope_or_clock",message="Observation could not be accepted for this book and clock window."});}
|
||||
}
|
||||
}
|
||||
@ -10,6 +10,7 @@ public interface IParagraphManuscriptRepository
|
||||
Task<ParagraphManuscript> SetMode(int user,int book,long expected,string mode);
|
||||
Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request);
|
||||
Task<ParagraphManuscript> SaveChapter(int user,ParagraphManuscript state,long expected,Guid request,int chapter)=>Save(user,state,expected,request);
|
||||
Task<ParagraphManuscript> SaveChapterWithActivity(int user,ParagraphManuscript state,long expected,Guid request,int chapter,Guid session)=>SaveChapter(user,state,expected,request,chapter);
|
||||
Task<ManuscriptScanPreview?> Capture(int user,int book);
|
||||
Task<ParagraphSyncStatus?> Status(int user,int book);
|
||||
Task<IReadOnlyList<ManuscriptEventOption>> Events(int user,int book);
|
||||
@ -19,8 +20,23 @@ public sealed class ParagraphManuscriptRepository(ISqlConnectionFactory factory)
|
||||
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<ParagraphManuscript> SaveChapter(int user,ParagraphManuscript state,long expected,Guid request,int chapter){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,ChangedChapterID=chapter,Payload=JsonSerializer.Serialize(state)},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
|
||||
public Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request) => SaveCore(user,state,expected,request,null);
|
||||
public Task<ParagraphManuscript> SaveChapter(int user,ParagraphManuscript state,long expected,Guid request,int chapter) => SaveCore(user,state,expected,request,chapter);
|
||||
public Task<ParagraphManuscript> SaveChapterWithActivity(int user,ParagraphManuscript state,long expected,Guid request,int chapter,Guid session)=>SaveCore(user,state,expected,request,chapter,session);
|
||||
private async Task<ParagraphManuscript> SaveCore(int user,ParagraphManuscript state,long expected,Guid request,int? chapter,Guid? session=null)
|
||||
{
|
||||
using var db=factory.CreateConnection(); db.Open(); using var transaction=db.BeginTransaction();
|
||||
var previousJson=await db.QuerySingleOrDefaultAsync<string>("dbo.WritingActivity",new{Action="lock",UserID=user,BookID=state.BookId},transaction,commandType:CommandType.StoredProcedure);
|
||||
var previous=previousJson==null?null:JsonSerializer.Deserialize<ParagraphManuscript>(previousJson);
|
||||
var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="save",UserID=user,BookID=state.BookId,ExpectedRevision=expected,RequestID=request,ChangedChapterID=chapter,Payload=JsonSerializer.Serialize(state)},transaction,commandType:CommandType.StoredProcedure);
|
||||
var accepted=JsonSerializer.Deserialize<ParagraphManuscript>(json)!;
|
||||
if(previous?.LastRequestId!=request)
|
||||
{
|
||||
var change=PlotLine.Services.WritingActivity.WritingChangeCalculator.Compare(previous,accepted);
|
||||
await db.ExecuteAsync("dbo.WritingActivity",new{Action="append",UserID=user,BookID=state.BookId,RequestID=request,Source=change.Scopes.Count>0||previous==null?"WordCompanion":"PlotDirector",PayloadHash=accepted.SnapshotHash,ManuscriptID=accepted.ManuscriptId,Revision=accepted.Revision,SessionID=session??(accepted.SessionId==Guid.Empty?(Guid?)null:accepted.SessionId),Kind=previous==null?"Baseline":change.Scopes.Count>0?"Change":"Structure",WordsAfter=change.AfterWords,BeforeWords=change.BeforeWords,BeforeHash=previous?.SnapshotHash,BeforeRevision=previous?.Revision,change.Added,change.Removed,change.Coverage,ChapterID=chapter,Scopes=JsonSerializer.Serialize(change.Scopes)},transaction,commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
transaction.Commit(); return accepted;
|
||||
}
|
||||
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();}
|
||||
|
||||
35
PlotLine/Data/WritingActivityRepository.cs
Normal file
35
PlotLine/Data/WritingActivityRepository.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Data;
|
||||
public sealed class WritingActivityRepository(ISqlConnectionFactory factory)
|
||||
{
|
||||
public async Task<WritingActivityPage> Read(int user,int book,long? before=null)
|
||||
{
|
||||
using var db=factory.CreateConnection();
|
||||
var settings=await db.QuerySingleAsync<WritingActivitySettings>("dbo.WritingActivity",new{Action="settings",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);
|
||||
var events=(await db.QueryAsync<WritingActivityEvent>("dbo.WritingActivity",new{Action="list",UserID=user,BookID=book,AfterSequence=before},commandType:CommandType.StoredProcedure)).ToArray();
|
||||
return new(){BookID=book,Settings=settings,Events=events,CanManage=true};
|
||||
}
|
||||
public async Task Baseline(int user,int book)
|
||||
{
|
||||
using var db=factory.CreateConnection();db.Open();using var transaction=db.BeginTransaction();
|
||||
var json=await db.QuerySingleOrDefaultAsync<string>("dbo.WritingActivity",new{Action="lock",UserID=user,BookID=book},transaction,commandType:CommandType.StoredProcedure);
|
||||
if(json==null)throw new InvalidOperationException("No accepted manuscript is available. Link and synchronise the existing Word manuscript first.");
|
||||
var state=JsonSerializer.Deserialize<ParagraphManuscript>(json)!;var change=PlotLine.Services.WritingActivity.WritingChangeCalculator.Compare(null,state);
|
||||
await db.ExecuteAsync("dbo.WritingActivity",new{Action="append",UserID=user,BookID=book,RequestID=Guid.NewGuid(),Source="PlotDirector",PayloadHash=state.SnapshotHash,ManuscriptID=state.ManuscriptId,Revision=state.Revision,Kind="Baseline",WordsAfter=change.AfterWords,Coverage=change.Coverage},transaction,commandType:CommandType.StoredProcedure);
|
||||
transaction.Commit();
|
||||
}
|
||||
public async Task Configure(int user,int book,bool enabled,int retentionDays)
|
||||
{ using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WritingActivity",new{Action="configure",UserID=user,BookID=book,Enabled=enabled,RetentionDays=retentionDays},commandType:CommandType.StoredProcedure); }
|
||||
public async Task Erase(int user,int book)
|
||||
{ using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WritingActivity",new{Action="erase",UserID=user,BookID=book},commandType:CommandType.StoredProcedure); }
|
||||
public async Task Observe(int user,PlotDirector.Companion.Protocol.WritingObservation value)
|
||||
{
|
||||
using var db=factory.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.WritingActivity",new{Action="observe",UserID=user,value.BookID,value.RequestID,Source="WordCompanion",PayloadHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value)))),value.ManuscriptID,value.ChapterID,value.ObservedUtc},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
43
PlotLine/Models/WritingActivityModels.cs
Normal file
43
PlotLine/Models/WritingActivityModels.cs
Normal file
@ -0,0 +1,43 @@
|
||||
namespace PlotLine.Models;
|
||||
|
||||
public sealed class WritingActivityEvent
|
||||
{
|
||||
public long Sequence { get; set; }
|
||||
public Guid EventID { get; set; }
|
||||
public int BookID { get; set; }
|
||||
public Guid ManuscriptID { get; set; }
|
||||
public string Kind { get; set; } = "";
|
||||
public string Source { get; set; } = "";
|
||||
public string Provenance { get; set; } = "Observed";
|
||||
public DateTime ReceivedUtc { get; set; }
|
||||
public DateTime? ObservedUtc { get; set; }
|
||||
public long Revision { get; set; }
|
||||
public int WordsAfter { get; set; }
|
||||
public int Added { get; set; }
|
||||
public int Removed { get; set; }
|
||||
public int Net => Added - Removed;
|
||||
public string Coverage { get; set; } = "Accepted snapshots; writing time unknown";
|
||||
public int? ChapterID { get; set; }
|
||||
public string? ChapterTitle { get; set; }
|
||||
}
|
||||
public sealed class WritingActivitySettings
|
||||
{
|
||||
public bool Enabled { get; set; } = true;
|
||||
public int RetentionDays { get; set; } = 365;
|
||||
}
|
||||
public sealed class WritingActivityPage
|
||||
{
|
||||
public int BookID { get; set; }
|
||||
public Book? Book { get; set; }
|
||||
public bool CanManage { get; set; }
|
||||
public WritingActivitySettings Settings { get; set; } = new();
|
||||
public IReadOnlyList<WritingActivityEvent> Events { get; set; } = [];
|
||||
public int Added => Events.Where(e => e.Kind == "Change").Sum(e => e.Added);
|
||||
public int Removed => Events.Where(e => e.Kind == "Change").Sum(e => e.Removed);
|
||||
public int ActiveDays => Events.Where(e => e.Kind == "Change").Select(e => e.ReceivedUtc.Date).Distinct().Count();
|
||||
}
|
||||
public sealed record WritingActivityScope(Guid ParagraphID, int? BeforeChapterID, int? ChapterID, Guid? BeforeSceneID, Guid? SceneID);
|
||||
public sealed record WritingChange(int BeforeWords, int AfterWords, int Added, int Removed, string Coverage, IReadOnlyList<WritingActivityScope> Scopes)
|
||||
{
|
||||
public int Net => Added - Removed;
|
||||
}
|
||||
@ -198,6 +198,8 @@ public class Program
|
||||
builder.Services.AddScoped<IArchiveRepository, ArchiveRepository>();
|
||||
builder.Services.AddScoped<IImportRepository, ImportRepository>();
|
||||
builder.Services.AddScoped<IWordCompanionRepository, WordCompanionRepository>();
|
||||
builder.Services.AddScoped<WritingActivityRepository>();
|
||||
builder.Services.AddHostedService<PlotLine.Services.WritingActivity.WritingActivityRetention>();
|
||||
builder.Services.AddScoped<IOnboardingRepository, OnboardingRepository>();
|
||||
builder.Services.AddScoped<IOnboardingBuildRepository, OnboardingBuildRepository>();
|
||||
builder.Services.AddScoped<ICoreImportBasicLocationReviewRepository, CoreImportBasicLocationReviewRepository>();
|
||||
|
||||
@ -79,7 +79,7 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re
|
||||
ParagraphManuscriptEngine.Reconcile(state,rows);
|
||||
// Logical positions after a partial repair are not a claim that every physical Word offset was validated.
|
||||
state.SessionId=Guid.Empty;state.WordRevision=-1;
|
||||
return await Save(user,state,proof.BaseRevision,proof.RequestId,proof.ChapterId);
|
||||
return await Save(user,state,proof.BaseRevision,proof.RequestId,proof.ChapterId,proof.SessionId);
|
||||
}
|
||||
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)
|
||||
{
|
||||
@ -105,9 +105,9 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re
|
||||
// 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,int? chapter=null)
|
||||
private async Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request,int? chapter=null,Guid? activitySession=null)
|
||||
{
|
||||
ParagraphManuscriptEngine.Validate(state);if(state.Chapters.Count>0)state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,expected+1).ToList();var result=chapter.HasValue?await repository.SaveChapter(user,state,expected,request,chapter.Value):await repository.Save(user,state,expected,request);
|
||||
ParagraphManuscriptEngine.Validate(state);if(state.Chapters.Count>0)state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,expected+1).ToList();var result=chapter.HasValue?await repository.SaveChapterWithActivity(user,state,expected,request,chapter.Value,activitySession??Guid.Empty):await repository.Save(user,state,expected,request);
|
||||
// Reuse deterministic continuity/statistics; never schedule whole-book AI.
|
||||
try{if(chapter.HasValue)await statistics.RecalculateChapterAsync(chapter.Value);else 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;
|
||||
|
||||
@ -0,0 +1,17 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
using PlotLine.Data;
|
||||
namespace PlotLine.Services.WritingActivity;
|
||||
public sealed class WritingActivityRetention(IServiceScopeFactory scopes,ILogger<WritingActivityRetention> logger):BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while(!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try { using var scope=scopes.CreateScope();using var db=scope.ServiceProvider.GetRequiredService<ISqlConnectionFactory>().CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.WritingActivity_Prune",commandType:CommandType.StoredProcedure,cancellationToken:stoppingToken)); }
|
||||
catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}
|
||||
catch(Exception e){logger.LogWarning("Writing activity retention could not run ({FailureKind}); retrying on next daily pass.",e.GetType().Name);}
|
||||
try{await Task.Delay(TimeSpan.FromDays(1),stoppingToken);}catch(OperationCanceledException)when(stoppingToken.IsCancellationRequested){break;}
|
||||
}
|
||||
}
|
||||
}
|
||||
51
PlotLine/Services/WritingActivity/WritingChangeCalculator.cs
Normal file
51
PlotLine/Services/WritingActivity/WritingChangeCalculator.cs
Normal file
@ -0,0 +1,51 @@
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.WritingActivity;
|
||||
|
||||
// whitespace-v1 / paragraph LCS. No prose is retained in activity storage.
|
||||
public static class WritingChangeCalculator
|
||||
{
|
||||
public static string[] Tokens(string text) => text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
|
||||
public static WritingChange Compare(ParagraphManuscript? before, ParagraphManuscript after)
|
||||
{
|
||||
var old = before?.Paragraphs.ToDictionary(p => p.Occurrence.Id) ?? [];
|
||||
var next = after.Paragraphs.ToDictionary(p => p.Occurrence.Id);
|
||||
var added = 0; var removed = 0; var exact = true;
|
||||
var scopes = new List<WritingActivityScope>();
|
||||
var unmatchedOld = new List<string>(); var unmatchedNew = new List<string>();
|
||||
foreach (var row in after.Paragraphs)
|
||||
{
|
||||
if (old.TryGetValue(row.Occurrence.Id, out var prior))
|
||||
{
|
||||
if (prior.Occurrence.Text == row.Occurrence.Text) continue;
|
||||
var a = Tokens(prior.Occurrence.Text); var b = Tokens(row.Occurrence.Text);
|
||||
var common = Common(a, b, ref exact); added += b.Length - common; removed += a.Length - common;
|
||||
scopes.Add(new(row.Occurrence.Id, prior.ChapterId, row.ChapterId, prior.SceneId, row.SceneId));
|
||||
}
|
||||
else { unmatchedNew.AddRange(Tokens(row.Occurrence.Text)); scopes.Add(new(row.Occurrence.Id, null, row.ChapterId, null, row.SceneId)); }
|
||||
}
|
||||
foreach (var row in before?.Paragraphs ?? []) if (!next.ContainsKey(row.Occurrence.Id))
|
||||
{ unmatchedOld.AddRange(Tokens(row.Occurrence.Text)); scopes.Add(new(row.Occurrence.Id, row.ChapterId, null, row.SceneId, null)); }
|
||||
var shared = Common(unmatchedOld.ToArray(), unmatchedNew.ToArray(), ref exact);
|
||||
added += unmatchedNew.Count - shared; removed += unmatchedOld.Count - shared;
|
||||
var beforeWords = before?.Paragraphs.Sum(p => Tokens(p.Occurrence.Text).Length) ?? 0;
|
||||
var afterWords = after.Paragraphs.Sum(p => Tokens(p.Occurrence.Text).Length);
|
||||
return new(beforeWords, afterWords, before == null ? 0 : added, before == null ? 0 : removed,
|
||||
before == null ? "Baseline; earlier activity unavailable" : exact ? "Accepted snapshot difference; whitespace-v1/paragraph-lcs; writing time unknown" : "Partial: minimum token-balance difference for large replacement; writing time unknown", scopes);
|
||||
}
|
||||
private static int Common(string[] a, string[] b, ref bool exact)
|
||||
{
|
||||
var start = 0; while (start < a.Length && start < b.Length && a[start] == b[start]) start++;
|
||||
var ae = a.Length; var be = b.Length;
|
||||
while (ae > start && be > start && a[ae - 1] == b[be - 1]) { ae--; be--; }
|
||||
if ((long)(ae - start) * (be - start) > 2_000_000)
|
||||
{
|
||||
exact = false;
|
||||
var counts = a[start..ae].GroupBy(t => t, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);
|
||||
var common = 0; foreach (var token in b[start..be]) if (counts.TryGetValue(token, out var n) && n > 0) { common++; counts[token] = n - 1; }
|
||||
return start + a.Length - ae + common;
|
||||
}
|
||||
var row = new int[be - start + 1];
|
||||
for (var i = start; i < ae; i++) { var diagonal = 0; for (var j = start; j < be; j++) { var previous = row[j - start + 1]; row[j - start + 1] = a[i] == b[j] ? diagonal + 1 : Math.Max(row[j - start + 1], row[j - start]); diagonal = previous; } }
|
||||
return start + a.Length - ae + row[^1];
|
||||
}
|
||||
}
|
||||
99
PlotLine/Sql/259_WritingActivityFoundation.sql
Normal file
99
PlotLine/Sql/259_WritingActivityFoundation.sql
Normal file
@ -0,0 +1,99 @@
|
||||
-- Additive, metadata-only writing history. Does not replace manuscript synchronisation.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID('dbo.WritingActivitySettings','U') IS NULL
|
||||
CREATE TABLE dbo.WritingActivitySettings(BookID int NOT NULL PRIMARY KEY REFERENCES dbo.Books(BookID) ON DELETE CASCADE,Enabled bit NOT NULL DEFAULT 1,RetentionDays int NOT NULL DEFAULT 365 CHECK(RetentionDays BETWEEN 30 AND 3650));
|
||||
IF OBJECT_ID('dbo.WritingActivityReceipts','U') IS NULL
|
||||
CREATE TABLE dbo.WritingActivityReceipts(BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,RequestID uniqueidentifier NOT NULL,Source varchar(32) NOT NULL,PayloadHash char(64) NOT NULL,ReceivedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),CONSTRAINT PK_WritingActivityReceipts PRIMARY KEY(BookID,RequestID,Source));
|
||||
IF OBJECT_ID('dbo.WritingActivityEvents','U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.WritingActivityEvents(
|
||||
Sequence bigint IDENTITY PRIMARY KEY,EventID uniqueidentifier NOT NULL DEFAULT NEWID() UNIQUE,
|
||||
BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,ProjectID int NOT NULL,ManuscriptID uniqueidentifier NOT NULL,
|
||||
UserID int NOT NULL,RequestID uniqueidentifier NOT NULL,Kind varchar(20) NOT NULL,Source varchar(32) NOT NULL,Provenance varchar(20) NOT NULL DEFAULT 'Observed',
|
||||
ReceivedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),ObservedUtc datetime2 NULL,Revision bigint NOT NULL,
|
||||
SchemaVersion tinyint NOT NULL DEFAULT 1,SessionID uniqueidentifier NULL,MetricVersion varchar(64) NOT NULL DEFAULT 'whitespace-v1/paragraph-lcs',
|
||||
WordsAfter int NOT NULL CHECK(WordsAfter>=0),Added int NOT NULL CHECK(Added>=0),Removed int NOT NULL CHECK(Removed>=0),
|
||||
Coverage nvarchar(200) NOT NULL,ChapterID int NULL,SnapshotHash char(64) NOT NULL,Scopes nvarchar(max) NULL,
|
||||
CONSTRAINT CK_WritingActivityScopes CHECK(Scopes IS NULL OR ISJSON(Scopes)=1));
|
||||
CREATE INDEX IX_WritingActivity_BookTime ON dbo.WritingActivityEvents(BookID,ReceivedUtc DESC,Sequence DESC) INCLUDE(Kind,Added,Removed,WordsAfter);
|
||||
END;
|
||||
IF COL_LENGTH('dbo.WritingActivityEvents','SessionID') IS NULL ALTER TABLE dbo.WritingActivityEvents ADD SessionID uniqueidentifier NULL;
|
||||
IF COL_LENGTH('dbo.WritingActivityEvents','SchemaVersion') IS NULL ALTER TABLE dbo.WritingActivityEvents ADD SchemaVersion tinyint NOT NULL DEFAULT 1;
|
||||
IF COL_LENGTH('dbo.WritingActivityEvents','MetricVersion') IS NULL ALTER TABLE dbo.WritingActivityEvents ADD MetricVersion varchar(64) NOT NULL DEFAULT 'whitespace-v1/paragraph-lcs';
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingActivity
|
||||
@Action varchar(16),@UserID int,@BookID int,@RequestID uniqueidentifier=NULL,@Source varchar(32)='WordCompanion',@PayloadHash char(64)=NULL,
|
||||
@ManuscriptID uniqueidentifier=NULL,@Revision bigint=0,@Kind varchar(20)='Change',@WordsAfter int=0,@BeforeWords int=0,@Added int=0,@Removed int=0,
|
||||
@SessionID uniqueidentifier=NULL,@BeforeHash char(64)=NULL,@BeforeRevision bigint=NULL,@Coverage nvarchar(200)=N'Accepted snapshots; writing time unknown',@ChapterID int=NULL,@Scopes nvarchar(max)=NULL,@ObservedUtc datetime2=NULL,
|
||||
@Enabled bit=1,@RetentionDays int=365,@AfterSequence bigint=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
DECLARE @ProjectID int=(SELECT ProjectID FROM dbo.Books WHERE BookID=@BookID AND IsArchived=0);
|
||||
IF @ProjectID IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1) THROW 51000,'Book access denied',1;
|
||||
-- Activity is author-private until a dedicated contributor visibility policy exists.
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole='Owner') THROW 51000,'Owner authority required',1;
|
||||
IF @Action='list'
|
||||
BEGIN
|
||||
SELECT TOP(500) e.Sequence,e.EventID,e.BookID,e.ManuscriptID,e.Kind,e.Source,e.Provenance,e.ReceivedUtc,e.ObservedUtc,e.Revision,e.WordsAfter,e.Added,e.Removed,e.Coverage,e.ChapterID,c.ChapterTitle
|
||||
FROM dbo.WritingActivityEvents e LEFT JOIN dbo.Chapters c ON c.ChapterID=e.ChapterID AND c.BookID=e.BookID
|
||||
WHERE e.BookID=@BookID AND (@AfterSequence IS NULL OR e.Sequence<@AfterSequence) ORDER BY e.Sequence DESC;
|
||||
RETURN;
|
||||
END;
|
||||
IF @Action='settings' BEGIN SELECT COALESCE(s.Enabled,1) Enabled,COALESCE(s.RetentionDays,365) RetentionDays FROM(SELECT 1 n) x LEFT JOIN dbo.WritingActivitySettings s ON s.BookID=@BookID;RETURN;END;
|
||||
IF @Action='configure'
|
||||
BEGIN
|
||||
IF @RetentionDays NOT BETWEEN 30 AND 3650 THROW 51000,'Retention must be 30 to 3650 days',1;
|
||||
BEGIN TRANSACTION;
|
||||
UPDATE dbo.WritingActivitySettings WITH(UPDLOCK,SERIALIZABLE) SET Enabled=@Enabled,RetentionDays=@RetentionDays WHERE BookID=@BookID;
|
||||
IF @@ROWCOUNT=0 INSERT dbo.WritingActivitySettings VALUES(@BookID,@Enabled,@RetentionDays);
|
||||
DELETE dbo.WritingActivityEvents WHERE BookID=@BookID AND ReceivedUtc<DATEADD(day,-@RetentionDays,SYSUTCDATETIME());
|
||||
COMMIT;RETURN;
|
||||
END;
|
||||
IF @Action='erase' BEGIN BEGIN TRANSACTION;DELETE dbo.WritingActivityEvents WHERE BookID=@BookID;UPDATE dbo.WritingActivitySettings SET Enabled=0 WHERE BookID=@BookID;IF @@ROWCOUNT=0 INSERT dbo.WritingActivitySettings VALUES(@BookID,0,365);COMMIT;RETURN;END;
|
||||
IF @Action='lock'
|
||||
BEGIN
|
||||
-- Must share caller's transaction with the established canonical save and activity append.
|
||||
IF @@TRANCOUNT=0 THROW 51000,'Activity lock requires a transaction',1;
|
||||
SELECT Payload FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
RETURN;
|
||||
END;
|
||||
IF @Action NOT IN('append','observe') THROW 51000,'Unknown activity operation',1;
|
||||
IF @RequestID IS NULL OR @RequestID='00000000-0000-0000-0000-000000000000' OR @PayloadHash IS NULL OR LEN(@PayloadHash)<>64 OR @Source NOT IN('WordCompanion','PlotDirector','Editor') THROW 51000,'Invalid activity identity',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @CurrentManuscript uniqueidentifier;
|
||||
SELECT @CurrentManuscript=ManuscriptID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @CurrentManuscript IS NULL OR @CurrentManuscript<>@ManuscriptID THROW 51000,'Manuscript identity changed',1;
|
||||
DECLARE @PriorHash char(64);
|
||||
SELECT @PriorHash=PayloadHash FROM dbo.WritingActivityReceipts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID AND RequestID=@RequestID AND Source=@Source;
|
||||
IF @PriorHash IS NOT NULL BEGIN IF @PriorHash<>@PayloadHash THROW 51000,'Activity identity conflict',1;COMMIT;RETURN;END;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID AND ManuscriptID=@ManuscriptID) THROW 51000,'Manuscript identity changed',1;
|
||||
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@BookID AND ChapterID=@ChapterID) THROW 51000,'Chapter scope mismatch',1;
|
||||
IF @Action='observe'
|
||||
BEGIN
|
||||
IF @ObservedUtc IS NULL OR @ObservedUtc>DATEADD(minute,5,SYSUTCDATETIME()) OR @ObservedUtc<DATEADD(day,-30,SYSUTCDATETIME()) THROW 51000,'Observation outside supported clock/retention window',1;
|
||||
SET @Added=0;SET @Removed=0;SET @WordsAfter=0;SET @Kind='Observation';SET @Coverage=N'Native change observation; not an accepted text change or measured writing time';
|
||||
END;
|
||||
IF @Kind='Baseline' AND EXISTS(SELECT 1 FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND ManuscriptID=@ManuscriptID) BEGIN COMMIT;RETURN;END;
|
||||
IF @Action='append' AND @Kind<>'Baseline' AND @Added-@Removed<>@WordsAfter-@BeforeWords THROW 51000,'Word changes do not reconcile',1;
|
||||
INSERT dbo.WritingActivityReceipts(BookID,RequestID,Source,PayloadHash) VALUES(@BookID,@RequestID,@Source,@PayloadHash);
|
||||
IF COALESCE((SELECT Enabled FROM dbo.WritingActivitySettings WHERE BookID=@BookID),1)=1
|
||||
BEGIN
|
||||
IF @Action='append' AND @Kind<>'Baseline' AND NOT EXISTS(SELECT 1 FROM dbo.WritingActivityEvents WHERE BookID=@BookID AND ManuscriptID=@ManuscriptID)
|
||||
INSERT dbo.WritingActivityEvents(BookID,ProjectID,ManuscriptID,UserID,RequestID,Kind,Source,Revision,WordsAfter,Added,Removed,Coverage,SnapshotHash)
|
||||
VALUES(@BookID,@ProjectID,@ManuscriptID,@UserID,NEWID(),'Baseline','PlotDirector',COALESCE(@BeforeRevision,0),@BeforeWords,0,0,N'Current accepted baseline; earlier activity unavailable',COALESCE(@BeforeHash,@PayloadHash));
|
||||
INSERT dbo.WritingActivityEvents(BookID,ProjectID,ManuscriptID,UserID,RequestID,Kind,Source,ObservedUtc,Revision,WordsAfter,Added,Removed,Coverage,ChapterID,SnapshotHash,Scopes,SessionID)
|
||||
VALUES(@BookID,@ProjectID,@ManuscriptID,@UserID,@RequestID,@Kind,@Source,@ObservedUtc,@Revision,@WordsAfter,@Added,@Removed,@Coverage,@ChapterID,@PayloadHash,@Scopes,@SessionID);
|
||||
END;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WritingActivity_Prune
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
DELETE e FROM dbo.WritingActivityEvents e LEFT JOIN dbo.WritingActivitySettings s ON s.BookID=e.BookID WHERE e.ReceivedUtc<DATEADD(day,-COALESCE(s.RetentionDays,365),SYSUTCDATETIME());
|
||||
END;
|
||||
GO
|
||||
35
PlotLine/Views/WritingActivity/Index.cshtml
Normal file
35
PlotLine/Views/WritingActivity/Index.cshtml
Normal file
@ -0,0 +1,35 @@
|
||||
@model PlotLine.Models.WritingActivityPage
|
||||
@{
|
||||
ViewData["Title"] = "Writing activity";
|
||||
ViewData["ProjectSection"] = "Writer";
|
||||
}
|
||||
<div class="page-heading" data-pwa-header>
|
||||
<div><p class="eyebrow">Writer · Evidence</p><h1>Writing activity</h1><p class="lead-text">@(Model.Book?.BookDisplayTitle ?? "Selected manuscript")</p></div>
|
||||
<a class="btn btn-outline-primary" asp-controller="Writer" asp-action="Index" asp-route-projectId="@Model.Book?.ProjectID" asp-route-bookId="@Model.BookID">Back to Writer</a>
|
||||
</div>
|
||||
<p>These are accepted snapshot differences and separately labelled native observations. They do not measure writing time or prove authorship. Earlier writing and changes between observations may be unavailable.</p>
|
||||
@if(Model.Events.Count == 0)
|
||||
{
|
||||
<section class="story-bible-section"><h2>Begin with the manuscript you have</h2><p>No retained activity is available. Record the current accepted manuscript as a baseline; its existing words will not count as new writing.</p>
|
||||
<form asp-action="Baseline" method="post"><input type="hidden" name="bookId" value="@Model.BookID" /><button class="btn btn-primary" disabled="@(!Model.Settings.Enabled)">Record current baseline</button></form></section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<section class="story-bible-section"><h2>Retained evidence</h2><p>Up to 500 records per page. Times below are server receipt times in UTC; source observation time is shown separately when available.</p>
|
||||
<div class="table-responsive"><table class="table"><thead><tr><th>Received (UTC)</th><th>Evidence</th><th>Scope</th><th>Added</th><th>Removed</th><th>Net</th></tr></thead><tbody>
|
||||
@foreach(var e in Model.Events)
|
||||
{
|
||||
<tr><td>@e.ReceivedUtc.ToString("dd MMM yyyy HH:mm:ss")@if(e.ObservedUtc.HasValue){<div class="small">Observed @e.ObservedUtc.Value.ToString("dd MMM yyyy HH:mm:ss") UTC</div>}</td><td><strong>@e.Kind</strong> · @e.Source<div class="small">@e.Provenance · @e.Coverage</div></td><td>@if(e.ChapterID.HasValue){<a asp-controller="Writer" asp-action="Chapter" asp-route-id="@e.ChapterID">@(e.ChapterTitle ?? "Chapter")</a>}else{<span>Manuscript</span>}<div class="small">Accepted revision @e.Revision</div></td><td>@(e.Kind=="Change"?e.Added.ToString("N0"):"—")</td><td>@(e.Kind=="Change"?e.Removed.ToString("N0"):"—")</td><td>@(e.Kind=="Change"?e.Net.ToString("+0;-0;0"):"—")</td></tr>
|
||||
}
|
||||
</tbody></table></div>
|
||||
<a class="btn btn-outline-primary" asp-action="Export" asp-route-bookId="@Model.BookID">Export recent evidence (JSON)</a>
|
||||
@if(Model.Events.Count==500){<a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-before="@Model.Events.Last().Sequence">Earlier evidence</a>}
|
||||
</section>
|
||||
}
|
||||
<section class="story-bible-section"><h2>Privacy and retention</h2><p>Activity stores counts, identifiers and evidence metadata, never a second copy of your prose. Default retention is 365 days. Compact retry receipts remain until the book is permanently deleted to prevent duplicate delivery. Retention runs daily; reducing it also removes older records now. Pausing leaves manuscript synchronisation available.</p>
|
||||
<form asp-action="Settings" method="post"><input type="hidden" name="bookId" value="@Model.BookID" />
|
||||
<label class="form-check"><input class="form-check-input" type="checkbox" name="enabled" value="true" checked="@Model.Settings.Enabled" /> Record activity for this book</label>
|
||||
<label>Keep activity for <input class="form-control" type="number" name="retentionDays" min="30" max="3650" value="@Model.Settings.RetentionDays" /> days (30–3650)</label>
|
||||
<button class="btn btn-primary mt-2">Save privacy settings</button></form>
|
||||
<details class="mt-3"><summary>Delete retained activity</summary><p>This removes retained activity and pauses capture. It does not change your manuscript. Previously exported files and existing backups are separate copies.</p><form asp-action="Erase" method="post"><input type="hidden" name="bookId" value="@Model.BookID" /><label><input type="checkbox" name="confirm" value="true" required /> Delete this book's activity and pause capture</label><button class="btn btn-outline-danger ms-2">Delete activity</button></form></details>
|
||||
</section>
|
||||
Loading…
x
Reference in New Issue
Block a user