@pmate/chat-sdk 0.13.0-profile.8 → 0.14.0-seq.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +57 -0
  2. package/lib/profile.d.ts +1 -1
  3. package/lib/profile.js +1 -1
  4. package/lib/runtime/profileChat.d.ts +7 -0
  5. package/lib/runtime/profileChat.js +105 -20
  6. package/lib/runtime/profileCommitQueue.js +3 -3
  7. package/lib/runtime/profileCoordinator.d.ts +25 -20
  8. package/lib/runtime/profileCoordinator.js +146 -128
  9. package/lib/runtime/profileDatabase.d.ts +6 -9
  10. package/lib/runtime/profileDatabase.js +10 -39
  11. package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
  12. package/lib/runtime/profileGenerationBuilder.js +23 -23
  13. package/lib/runtime/profileInboxFeed.js +3 -2
  14. package/lib/runtime/profileLegacyInbox.js +2 -1
  15. package/lib/runtime/profileMemoryStore.d.ts +9 -3
  16. package/lib/runtime/profileMemoryStore.js +50 -10
  17. package/lib/runtime/profileOutboxDispatcher.js +4 -1
  18. package/lib/runtime/profileOwner.d.ts +2 -7
  19. package/lib/runtime/profileOwner.js +18 -46
  20. package/lib/runtime/profileProjection.d.ts +19 -1
  21. package/lib/runtime/profileProjection.js +139 -18
  22. package/lib/runtime/profileStoreTypes.d.ts +4 -11
  23. package/lib/runtime/profileWindows.d.ts +2 -0
  24. package/lib/runtime/profileWindows.js +13 -3
  25. package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +9 -26
  26. package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +46 -97
  27. package/lib/runtime/profileWorkerHost.d.ts +3 -6
  28. package/lib/runtime/profileWorkerHost.js +23 -30
  29. package/lib/runtime/readSync.d.ts +1 -1
  30. package/lib/runtime/readSync.js +10 -6
  31. package/lib/runtime/sourceCursor.d.ts +6 -0
  32. package/lib/runtime/sourceCursor.js +7 -0
  33. package/package.json +2 -2
@@ -1,173 +1,191 @@
1
- import { ProfileReplica } from "./profileReplica.js";
1
+ import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
+ import { ProfileWorkerClient } from "./profileWorkerClient.js";
2
3
  import { openProfileWorker, profileChannelName } from "./profileWorkerHost.js";
3
- /** A WebView owns a stable memory replica, not necessarily the writer Worker.
4
- * Every context may acquire an expired lease; fencing decides the sole writer. */
4
+ import { SocialReadClient } from "./socialReadClient.js";
5
+ /** One application document, one dedicated Worker and one stable UI memory store.
6
+ * A failed Worker is terminated before its replacement is created. */
5
7
  export class ProfileCoordinator {
6
8
  options;
7
- replica;
8
- channel;
9
+ memory;
9
10
  worker;
11
+ connection;
10
12
  host;
11
- acquiring;
12
- timer;
13
- closed = false;
14
- needsOwner = false;
15
13
  starting;
16
- startupRetry;
14
+ restarting;
15
+ openingAbort;
16
+ closed = false;
17
+ groupRequests = new Map();
18
+ groupAbort = new AbortController();
17
19
  get identity() { return this.options.configuration.identity; }
18
- get memory() { return this.replica.memory; }
19
- submit(operation, immediate = false) { return this.replica.submit(operation, immediate); }
20
- synchronize() { return this.replica.synchronize(); }
21
- waitForCommand(id) { return this.replica.waitForCommand(id); }
22
- voiceAttachment(id) { return this.replica.voiceAttachment(id); }
20
+ get client() { if (!this.connection)
21
+ throw Error("PROFILE_WORKER_NOT_STARTED"); return this.connection; }
23
22
  constructor(options) {
24
23
  this.options = options;
25
- const scope = profileChannelName(options.configuration.identity);
26
- this.channel = options.channel?.(scope) ?? new BroadcastChannel(scope);
27
- this.channel.addEventListener("message", this.workerMessage);
28
- this.replica = new ProfileReplica(this.channel, scope, error => {
29
- this.report(error);
30
- if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
31
- this.needsOwner = true;
32
- void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
33
- }
34
- }, options.requestTimeoutMs ?? 5000, options.configuration.identity.profileId);
24
+ this.memory = new ProfileMemoryStore(error => this.report(error), this.identity.profileId);
35
25
  }
36
26
  report(error) { try {
37
27
  this.options.onError?.(error);
38
28
  }
39
29
  catch { } }
40
30
  workerMessage = (event) => {
41
- if (event.data?.profileControl === "credentials" && typeof event.data.token === "string" && event.data.token && event.data.token.length <= 65536) {
42
- const configuration = this.options.configuration;
43
- if (configuration.network)
44
- configuration.network = { ...configuration.network, token: event.data.token };
45
- }
46
- if (event.data?.profileControl === "progress") {
31
+ const data = event.data;
32
+ if (data?.profileControl === "credentials" && typeof data.token === "string" && data.token && data.token.length <= 65536 && this.options.configuration.network)
33
+ this.options.configuration.network = { ...this.options.configuration.network, token: data.token };
34
+ if (data?.profileControl === "progress") {
47
35
  try {
48
- this.options.onProgress?.(event.data.progress);
36
+ this.options.onProgress?.(data.progress);
49
37
  }
50
38
  catch { }
51
39
  }
52
- if (event.data?.profileControl === "error") {
53
- this.report(Error(event.data.error));
54
- if (event.data.error === "PROFILE_WRITER_FENCED") {
55
- this.needsOwner = true;
56
- void this.acquire().then(() => this.replica.repair()).catch(error => this.report(error));
57
- }
40
+ if (data?.profileControl === "error") {
41
+ this.report(Error(data.error));
42
+ if (["PROFILE_REVISION_CONFLICT", "PROFILE_GENERATION_MISMATCH"].includes(data.error))
43
+ this.workerFailed();
58
44
  }
59
45
  };
46
+ workerFailed = () => { void this.restart().catch(error => this.report(error)); };
47
+ listenFailure(worker, add) {
48
+ // Dedicated Workers have error/messageerror; structural test ports may omit them.
49
+ const target = worker;
50
+ const method = add ? "addEventListener" : "removeEventListener";
51
+ target[method]("error", this.workerFailed);
52
+ target[method]("messageerror", this.workerFailed);
53
+ }
60
54
  start() {
55
+ if (this.closed)
56
+ return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
57
+ if (this.restarting)
58
+ return this.restarting;
61
59
  if (this.starting)
62
60
  return this.starting;
63
- const task = this.initialize().catch(error => { this.starting = undefined; throw error; });
61
+ if (this.connection)
62
+ return Promise.resolve();
63
+ const task = this.initialize().catch(error => {
64
+ if (this.starting === task)
65
+ this.starting = undefined;
66
+ if (!this.closed)
67
+ this.report(error);
68
+ throw error;
69
+ });
64
70
  this.starting = task;
65
71
  return task;
66
72
  }
67
73
  async initialize() {
68
- for (;;) {
69
- if (this.closed)
74
+ const worker = this.options.createWorker();
75
+ this.worker = worker;
76
+ const abort = new AbortController();
77
+ this.openingAbort = abort;
78
+ worker.addEventListener("message", this.workerMessage);
79
+ this.listenFailure(worker, true);
80
+ try {
81
+ const host = await openProfileWorker(worker, this.options.configuration, this.options.requestTimeoutMs, abort.signal);
82
+ if (this.closed || this.worker !== worker)
70
83
  throw Error("PROFILE_COORDINATOR_CLOSED");
71
- try {
72
- await this.acquire();
73
- await this.replica.start(false);
74
- break;
75
- }
76
- catch (error) {
77
- if (this.closed)
78
- throw Error("PROFILE_COORDINATOR_CLOSED");
79
- if (!["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE", "PROFILE_WORKER_TIMEOUT"].includes(error?.message))
80
- throw error;
84
+ this.host = host;
85
+ const client = new ProfileWorkerClient(worker, profileChannelName(this.identity), error => {
81
86
  this.report(error);
82
- this.needsOwner = true;
83
- await new Promise(resolve => {
84
- const timer = setTimeout(() => { this.startupRetry = undefined; resolve(); }, this.options.retryMs ?? 10000);
85
- this.startupRetry = { timer, resolve };
86
- });
87
- }
87
+ this.workerFailed();
88
+ }, this.options.requestTimeoutMs, this.identity.profileId, this.memory);
89
+ this.connection = client;
90
+ await client.start();
91
+ if (this.closed || this.worker !== worker)
92
+ throw Error("PROFILE_COORDINATOR_CLOSED");
93
+ }
94
+ catch (error) {
95
+ if (this.worker === worker)
96
+ this.disposeWorker();
97
+ throw error;
98
+ }
99
+ }
100
+ disposeWorker() {
101
+ this.openingAbort?.abort(Error("PROFILE_WORKER_CLIENT_CLOSED"));
102
+ this.openingAbort = undefined;
103
+ this.connection?.close();
104
+ this.connection = undefined;
105
+ this.host = undefined;
106
+ const worker = this.worker;
107
+ this.worker = undefined;
108
+ if (worker) {
109
+ worker.removeEventListener("message", this.workerMessage);
110
+ this.listenFailure(worker, false);
111
+ worker.terminate();
88
112
  }
89
- if (!this.timer)
90
- this.timer = setInterval(() => {
91
- void this.replica.check().catch(error => {
92
- this.report(error);
93
- if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
94
- this.needsOwner = true;
95
- void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
96
- }
97
- });
98
- }, this.options.retryMs ?? 10000);
99
113
  }
100
- acquire() {
114
+ restart() {
101
115
  if (this.closed)
102
116
  return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
103
- if (this.acquiring)
104
- return this.acquiring;
105
- if (this.host && !this.needsOwner)
106
- return Promise.resolve();
117
+ if (this.restarting)
118
+ return this.restarting;
119
+ const previous = this.starting;
120
+ this.disposeWorker();
121
+ this.starting = undefined;
107
122
  const task = (async () => {
108
- if (this.worker) {
109
- this.worker.removeEventListener("message", this.workerMessage);
110
- this.worker.terminate();
111
- this.worker = undefined;
112
- this.host = undefined;
113
- }
114
- const worker = this.options.createWorker();
115
- worker.addEventListener("message", this.workerMessage);
116
- try {
117
- const host = await openProfileWorker(worker, this.options.configuration);
118
- if (this.closed) {
119
- await host.close();
120
- worker.terminate();
121
- return;
122
- }
123
- this.worker = worker;
124
- this.host = host;
125
- this.needsOwner = false;
126
- }
127
- catch (error) {
128
- worker.removeEventListener("message", this.workerMessage);
129
- worker.terminate();
130
- if (error?.message !== "PROFILE_OWNER_UNAVAILABLE")
131
- throw error;
132
- // Another healthy writer serves this replica through the shared channel.
133
- this.needsOwner = false;
134
- }
123
+ await previous?.catch(() => { });
124
+ if (this.closed)
125
+ throw Error("PROFILE_COORDINATOR_CLOSED");
126
+ await this.initialize();
135
127
  })();
136
- this.acquiring = task;
137
- void task.finally(() => { if (this.acquiring === task)
138
- this.acquiring = undefined; }).catch(() => { });
128
+ this.restarting = task;
129
+ void task.finally(() => {
130
+ if (this.restarting === task) {
131
+ this.restarting = undefined;
132
+ this.starting = undefined;
133
+ }
134
+ }).catch(() => { });
135
+ return task;
136
+ }
137
+ async invoke(call) {
138
+ await this.start();
139
+ try {
140
+ return await call(this.client);
141
+ }
142
+ catch (error) {
143
+ if (!["PROFILE_WORKER_TIMEOUT", "PROFILE_WORKER_CLIENT_CLOSED"].includes(error?.message) || this.closed)
144
+ throw error;
145
+ await this.restart();
146
+ // Commands retain their original message/command IDs, making replay safe
147
+ // when the old Worker committed before its response was interrupted.
148
+ return call(this.client);
149
+ }
150
+ }
151
+ submit(operation, immediate = false) { return this.invoke(client => client.submit(operation, immediate)); }
152
+ synchronize() { return this.invoke(client => client.synchronize()); }
153
+ waitForCommand(id) { return this.invoke(client => client.waitForCommand(id)); }
154
+ voiceAttachment(id) { return this.invoke(client => client.voiceAttachment(id)); }
155
+ /** Current group authority comes from Hub, independently of Inbox history. */
156
+ readGroup(groupId, teamId) {
157
+ if (this.closed)
158
+ return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
159
+ const key = JSON.stringify([teamId, groupId]), pending = this.groupRequests.get(key);
160
+ if (pending)
161
+ return pending;
162
+ const network = this.options.configuration.network;
163
+ if (!network)
164
+ return Promise.reject(Error("PROFILE_NETWORK_UNAVAILABLE"));
165
+ const task = new SocialReadClient({ ...this.identity, token: network.token, hubHttpUrl: network.hubHttpUrl.replace(/^ws/, "http"), fetch: this.options.fetch })
166
+ .group({ groupId, teamId }, this.groupAbort.signal);
167
+ this.groupRequests.set(key, task);
168
+ void task.finally(() => { if (this.groupRequests.get(key) === task)
169
+ this.groupRequests.delete(key); }).catch(() => { });
139
170
  return task;
140
171
  }
141
172
  async updateToken(token) {
142
- const configuration = this.options.configuration;
143
- if (!configuration.network)
173
+ if (!this.options.configuration.network)
144
174
  return;
145
- configuration.network = { ...configuration.network, token };
146
- if (this.starting) {
147
- await this.starting;
148
- await this.replica.updateCredentials(token);
149
- }
175
+ this.options.configuration.network = { ...this.options.configuration.network, token };
176
+ if (this.starting || this.connection)
177
+ await this.invoke(client => client.updateCredentials(token));
150
178
  }
151
179
  async close() {
180
+ if (this.closed)
181
+ return;
152
182
  this.closed = true;
153
- clearInterval(this.timer);
154
- if (this.startupRetry) {
155
- clearTimeout(this.startupRetry.timer);
156
- this.startupRetry.resolve();
157
- this.startupRetry = undefined;
158
- }
159
- this.replica.close();
160
- this.channel.removeEventListener("message", this.workerMessage);
161
- this.channel.close();
162
- await this.acquiring;
163
- try {
164
- await this.host?.close();
165
- }
166
- finally {
167
- this.worker?.removeEventListener("message", this.workerMessage);
168
- this.worker?.terminate();
169
- this.worker = undefined;
170
- this.host = undefined;
171
- }
183
+ this.groupAbort.abort();
184
+ this.groupRequests.clear();
185
+ // Stop the port immediately so requests cannot outlive the Profile.
186
+ this.disposeWorker();
187
+ await this.starting?.catch(() => { });
188
+ await this.restarting?.catch(() => { });
189
+ this.memory.dispose();
172
190
  }
173
191
  }
@@ -1,5 +1,5 @@
1
1
  import Dexie, { type Table } from "dexie";
2
- import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch, ProfileWriterLease } from "./profileStoreTypes.js";
2
+ import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch } from "./profileStoreTypes.js";
3
3
  export declare function profileDatabaseName(identity: ProfileIdentity): string;
4
4
  /** One Profile, five stores, one transaction boundary. No page-facing read API:
5
5
  * restoration is explicit and normal queries belong to the in-memory view. */
@@ -14,10 +14,7 @@ export declare class ProfileDatabase extends Dexie {
14
14
  indexedDB?: IDBFactory;
15
15
  name?: string;
16
16
  });
17
- claimWriter(ownerId: string, now?: number, ttlMs?: number, writerLock?: string): Promise<ProfileWriterLease | undefined>;
18
- private assertWriter;
19
- releaseWriter(ownerId: string, fence: number): Promise<void>;
20
- initialize(ownerId: string, fence: number, state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
17
+ initialize(state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
21
18
  commit(batch: ProfileWriteBatch): Promise<ProfileCurrentState>;
22
19
  /** Restore from one consistent transaction, never mix data across a switch. */
23
20
  restore(): Promise<{
@@ -27,19 +24,19 @@ export declare class ProfileDatabase extends Dexie {
27
24
  messages: ProfileMessage[];
28
25
  outbox: ProfileOutboxCommand[];
29
26
  }>;
30
- saveGeneration(ownerId: string, fence: number, build: ProfileGenerationState, rows: {
27
+ saveGeneration(build: ProfileGenerationState, rows: {
31
28
  threads?: ProfileThread[];
32
29
  windows?: ProfileWindow[];
33
30
  messages?: ProfileMessage[];
34
31
  }): Promise<void>;
35
- /** Bounded maintenance, fenced in the same transaction as deletion. Building
32
+ /** Bounded maintenance on the serial Worker queue. Building
36
33
  * and validated generations remain resumable; outbox is never involved. */
37
- cleanupGenerations(ownerId: string, fence: number, limit?: number): Promise<number>;
34
+ cleanupGenerations(limit?: number): Promise<number>;
38
35
  restoreGeneration(generation: string): Promise<{
39
36
  build: ProfileGenerationState | undefined;
40
37
  threads: ProfileThread[];
41
38
  windows: ProfileWindow[];
42
39
  messages: ProfileMessage[];
43
40
  }>;
44
- activateGeneration(ownerId: string, fence: number, generation: string, expectedRevision: number): Promise<ProfileCurrentState>;
41
+ activateGeneration(generation: string, expectedRevision: number): Promise<ProfileCurrentState>;
45
42
  }
@@ -1,3 +1,4 @@
1
+ import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
1
2
  import Dexie, {} from "dexie";
2
3
  import { inboxSequence } from "./inboxStore.js";
3
4
  export function profileDatabaseName(identity) {
@@ -22,40 +23,14 @@ export class ProfileDatabase extends Dexie {
22
23
  inboxState: "key",
23
24
  outbox: "commandId,[state+createdAt],threadId,messageId",
24
25
  });
26
+ // Additive upgrade: retain projections, reading facts and outbox; retire only
27
+ // the old TTL lease. The lifetime browser lock is acquired before opening.
28
+ this.version(2).stores({}).upgrade(transaction => transaction.table("inboxState").delete("lease"));
25
29
  this.on("versionchange", () => { this.close(); return false; });
26
30
  }
27
- async claimWriter(ownerId, now = Date.now(), ttlMs = 30000, writerLock) {
28
- if (!ownerId || !Number.isSafeInteger(ttlMs) || ttlMs < 1)
29
- throw Error("INVALID_PROFILE_LEASE");
30
- return this.transaction("rw", this.inboxState, async () => {
31
- const old = await this.inboxState.get("lease");
32
- if (old && old.ownerId !== ownerId && old.expiresAt > now && (!writerLock || old.writerLock !== writerLock))
33
- return undefined;
34
- const fence = old ? old.ownerId === ownerId && old.expiresAt > now ? old.fence : old.fence + 1 : 1;
35
- if (!Number.isSafeInteger(fence))
36
- throw Error("PROFILE_FENCE_EXHAUSTED");
37
- const lease = { key: "lease", ownerId, fence, expiresAt: now + ttlMs, ...(writerLock ? { writerLock } : {}) };
38
- await this.inboxState.put(lease);
39
- return lease;
40
- });
41
- }
42
- async assertWriter(ownerId, fence) {
43
- const lease = await this.inboxState.get("lease");
44
- if (!lease || lease.ownerId !== ownerId || lease.fence !== fence || lease.expiresAt <= Date.now())
45
- throw Error("PROFILE_WRITER_FENCED");
46
- }
47
- async releaseWriter(ownerId, fence) {
48
- await this.transaction("rw", this.inboxState, async () => {
49
- const lease = await this.inboxState.get("lease");
50
- // Keep the counter: deleting it would allow a stale producer to reuse fence 1.
51
- if (lease?.ownerId === ownerId && lease.fence === fence)
52
- await this.inboxState.put({ ...lease, expiresAt: 0 });
53
- });
54
- }
55
- async initialize(ownerId, fence, state) {
31
+ async initialize(state) {
56
32
  inboxSequence(state.committedSeq);
57
33
  return this.transaction("rw", this.inboxState, async () => {
58
- await this.assertWriter(ownerId, fence);
59
34
  const previous = await this.inboxState.get("current");
60
35
  if (previous)
61
36
  return previous;
@@ -71,7 +46,6 @@ export class ProfileDatabase extends Dexie {
71
46
  throw Error("PROFILE_GENERATION_MISMATCH");
72
47
  }
73
48
  return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
74
- await this.assertWriter(batch.ownerId, batch.fence);
75
49
  const current = await this.inboxState.get("current");
76
50
  if (!current || current.activeGeneration !== batch.generation || current.epoch !== batch.epoch)
77
51
  throw Error("PROFILE_GENERATION_MISMATCH");
@@ -125,7 +99,7 @@ export class ProfileDatabase extends Dexie {
125
99
  };
126
100
  });
127
101
  }
128
- async saveGeneration(ownerId, fence, build, rows) {
102
+ async saveGeneration(build, rows) {
129
103
  inboxSequence(build.committedSeq);
130
104
  for (const row of [...rows.threads ?? [], ...rows.windows ?? [], ...rows.messages ?? []])
131
105
  if (row.generation !== build.generation)
@@ -133,7 +107,6 @@ export class ProfileDatabase extends Dexie {
133
107
  if (build.key !== `build:${build.generation}`)
134
108
  throw Error("PROFILE_GENERATION_MISMATCH");
135
109
  await this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
136
- await this.assertWriter(ownerId, fence);
137
110
  const current = await this.inboxState.get("current");
138
111
  if (current?.activeGeneration === build.generation)
139
112
  throw Error("PROFILE_BUILD_IS_ACTIVE");
@@ -146,18 +119,17 @@ export class ProfileDatabase extends Dexie {
146
119
  await this.inboxState.put(build);
147
120
  });
148
121
  }
149
- /** Bounded maintenance, fenced in the same transaction as deletion. Building
122
+ /** Bounded maintenance on the serial Worker queue. Building
150
123
  * and validated generations remain resumable; outbox is never involved. */
151
- async cleanupGenerations(ownerId, fence, limit = 200) {
124
+ async cleanupGenerations(limit = 200) {
152
125
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)
153
126
  throw Error("INVALID_PROFILE_CLEANUP_LIMIT");
154
127
  return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
155
- await this.assertWriter(ownerId, fence);
156
128
  const current = await this.inboxState.get("current");
157
129
  if (!current)
158
130
  return 0;
159
131
  const builds = (await this.inboxState.toArray()).filter((row) => row.key.startsWith("build:"));
160
- const protectedGenerations = new Set([current.activeGeneration, ...builds.filter(row => row.status === "building" || row.status === "validated").map(row => row.generation)]);
132
+ const protectedGenerations = new Set([current.activeGeneration, ...builds.filter(row => row.projectionVersion === PROFILE_PROJECTION_VERSION && (row.status === "building" || row.status === "validated")).map(row => row.generation)]);
161
133
  let removed = 0;
162
134
  for (const table of [this.messages, this.windows, this.threads]) {
163
135
  if (removed === limit)
@@ -189,9 +161,8 @@ export class ProfileDatabase extends Dexie {
189
161
  messages: await this.messages.where("generation").equals(generation).toArray(),
190
162
  }));
191
163
  }
192
- async activateGeneration(ownerId, fence, generation, expectedRevision) {
164
+ async activateGeneration(generation, expectedRevision) {
193
165
  return this.transaction("rw", this.inboxState, async () => {
194
- await this.assertWriter(ownerId, fence);
195
166
  const current = await this.inboxState.get("current");
196
167
  const build = await this.inboxState.get(`build:${generation}`);
197
168
  if (!current || current.commitRevision !== expectedRevision || build?.sourceRevision !== expectedRevision)
@@ -1,14 +1,13 @@
1
1
  import { ProfileDatabase } from "./profileDatabase.js";
2
2
  import { ProfileProjection, type ProfileOperation } from "./profileProjection.js";
3
3
  import { type InboxBootstrap } from "./inboxStore.js";
4
- import type { ProfileGenerationState, ProfileWriterLease } from "./profileStoreTypes.js";
4
+ import type { ProfileGenerationState } from "./profileStoreTypes.js";
5
5
  /** Called only by the owner's serial commit queue. Network catch-up happens
6
6
  * outside this class; each staged page is one bounded local transaction. */
7
7
  export declare class ProfileGenerationBuilder {
8
8
  private database;
9
- private lease;
10
9
  private cache;
11
- constructor(database: ProfileDatabase, lease: () => ProfileWriterLease);
10
+ constructor(database: ProfileDatabase);
12
11
  private persist;
13
12
  private load;
14
13
  begin(generation: string, bootstrap: InboxBootstrap, sourceRevision: number): Promise<void>;
@@ -1,22 +1,19 @@
1
1
  import { ProfileDatabase } from "./profileDatabase.js";
2
- import { ProfileProjection } from "./profileProjection.js";
3
- import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
+ import { profileDiscussionId, ProfileProjection } from "./profileProjection.js";
3
+ import { ProfileMemoryStore, PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
4
4
  import { inboxSequence } from "./inboxStore.js";
5
5
  /** Called only by the owner's serial commit queue. Network catch-up happens
6
6
  * outside this class; each staged page is one bounded local transaction. */
7
7
  export class ProfileGenerationBuilder {
8
8
  database;
9
- lease;
10
9
  cache = new Map();
11
- constructor(database, lease) {
10
+ constructor(database) {
12
11
  this.database = database;
13
- this.lease = lease;
14
12
  }
15
13
  async persist(build, projection, events) {
16
14
  const prepared = projection.prepare(events);
17
15
  const next = { ...build, committedSeq: prepared.current.committedSeq, buildRevision: prepared.current.commitRevision, receiptsReady: prepared.current.receiptsReady };
18
- const lease = this.lease();
19
- await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
16
+ await this.database.saveGeneration(next, prepared);
20
17
  projection.accept(prepared);
21
18
  this.cache.set(build.generation, { build: next, projection });
22
19
  return { build: next, projection };
@@ -41,18 +38,20 @@ export class ProfileGenerationBuilder {
41
38
  throw Error("INVALID_INBOX_BOOTSTRAP");
42
39
  const saved = await this.database.restoreGeneration(generation);
43
40
  if (saved.build) {
41
+ if (saved.build.projectionVersion !== PROFILE_PROJECTION_VERSION)
42
+ throw Error("PROFILE_BUILD_INCOMPATIBLE");
44
43
  if (saved.build.epoch !== bootstrap.epoch || saved.build.throughSeq !== bootstrap.headSeq || saved.build.windowStart !== bootstrap.windowStart)
45
44
  throw Error("PROFILE_BUILD_ID_COLLISION");
46
45
  return;
47
46
  }
48
47
  const build = { key: `build:${generation}`, generation, epoch: bootstrap.epoch,
49
- committedSeq: (start - 1n).toString(), projectionVersion: 1, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
48
+ committedSeq: (start - 1n).toString(), projectionVersion: PROFILE_PROJECTION_VERSION, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
50
49
  windowStart: bootstrap.windowStart, buildRevision: 0 };
51
50
  const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
52
- epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
53
- const prepared = projection.prepareBasis(bootstrap), lease = this.lease();
51
+ epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: PROFILE_PROJECTION_VERSION, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
52
+ const prepared = projection.prepareBasis(bootstrap);
54
53
  const next = { ...build, buildRevision: prepared.current.commitRevision };
55
- await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
54
+ await this.database.saveGeneration(next, prepared);
56
55
  projection.accept(prepared);
57
56
  this.cache.set(generation, { build: next, projection });
58
57
  }
@@ -102,15 +101,17 @@ export class ProfileGenerationBuilder {
102
101
  for (const intent of intents)
103
102
  operations.push({ type: "restoreReadingIntent", threadId: thread.threadId, messageId, ...intent, defer: true });
104
103
  }
105
- if (!projection.threads.has(thread.threadId))
106
- continue;
107
- for (const source of thread.readingSources) {
108
- if (!source.pendingReadThroughSeq && !source.pendingExplicitReadMessageIds?.length)
109
- continue;
110
- operations.push({ type: "restoreReading", data: { appId: this.database.identity.appId, profileId: this.database.identity.profileId,
111
- threadId: source.sourceThreadId, threadRootId: thread.rootMessageId,
112
- readThroughSeq: source.pendingReadThroughSeq ?? 0, explicitReadMessageIds: source.pendingExplicitReadMessageIds ?? [] } });
113
- }
104
+ const parentId = thread.parentThreadId ?? thread.threadId;
105
+ const parent = projection.threads.get(parentId);
106
+ const canonical = parent?.internal?.assignments?.[parentId] ?? parentId;
107
+ const destination = thread.rootMessageId ? profileDiscussionId(canonical, thread.rootMessageId) : canonical;
108
+ if (projection.threads.has(destination) && thread.readingSources.length)
109
+ operations.push({ type: "restoreReadingSources", threadId: destination, sources: thread.readingSources });
110
+ }
111
+ for (const message of active.messages.values()) {
112
+ const facts = message.explicitReadingFacts.filter(fact => fact.profileId === this.database.identity.profileId);
113
+ if (facts.length && projection.messages.has(message.messageId))
114
+ operations.push({ type: "restoreMessageReadingFacts", messageId: message.messageId, facts });
114
115
  }
115
116
  for (const command of active.outbox.values())
116
117
  if (command.kind !== "message")
@@ -135,10 +136,9 @@ export class ProfileGenerationBuilder {
135
136
  await flush();
136
137
  const snapshot = projection.snapshot();
137
138
  new ProfileMemoryStore().restore(snapshot);
138
- const lease = this.lease();
139
139
  const validated = { ...build, status: "validated", sourceRevision: active.current.commitRevision };
140
- await this.database.saveGeneration(lease.ownerId, lease.fence, validated, {});
141
- const current = await this.database.activateGeneration(lease.ownerId, lease.fence, generation, active.current.commitRevision);
140
+ await this.database.saveGeneration(validated, {});
141
+ const current = await this.database.activateGeneration(generation, active.current.commitRevision);
142
142
  const result = new ProfileProjection(this.database.identity, { ...snapshot, current, outbox: [...active.outbox.values()] }, build.windowStart ?? 0);
143
143
  this.cache.delete(generation);
144
144
  return result;
@@ -1,3 +1,4 @@
1
+ import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
1
2
  import { inboxSequence } from "./inboxStore.js";
2
3
  /** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
3
4
  * backpressured by durable owner commits; long requests never hold its queue. */
@@ -114,7 +115,7 @@ export class ProfileInboxFeed {
114
115
  }
115
116
  async rebuild() {
116
117
  const bootstrap = await this.request("bootstrap");
117
- const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch);
118
+ const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch && build.projectionVersion === PROFILE_PROJECTION_VERSION);
118
119
  const generation = pending?.generation ?? await this.options.owner.beginGeneration(bootstrap);
119
120
  const build = await this.options.owner.generationProgress(generation);
120
121
  this.building = { generation, epoch: build.epoch, target: build.throughSeq ?? bootstrap.headSeq };
@@ -146,7 +147,7 @@ export class ProfileInboxFeed {
146
147
  await this.options.prepare?.();
147
148
  if (this.building)
148
149
  await this.resumeBuild();
149
- if (this.options.owner.current.epoch === "uninitialized")
150
+ if (this.options.owner.current.epoch === "uninitialized" || this.options.owner.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
150
151
  await this.rebuild();
151
152
  let current = this.options.owner.current;
152
153
  let page = await this.request("check", { afterSeq: current.committedSeq, epoch: current.epoch });
@@ -1,3 +1,4 @@
1
+ import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
1
2
  import { inboxSequence } from "./inboxStore.js";
2
3
  export async function openLegacyDatabase(factory, name) {
3
4
  return new Promise((resolve, reject) => {
@@ -50,7 +51,7 @@ export async function migrateLegacyInbox(owner, options = {}) {
50
51
  if (!cursor?.initialized || !cursor.epoch)
51
52
  return false;
52
53
  const seq = inboxSequence(cursor.seq);
53
- const generation = `legacy-inbox:${JSON.stringify([cursor.epoch, cursor.seq])}`;
54
+ const generation = `legacy-inbox:v${PROFILE_PROJECTION_VERSION}:${JSON.stringify([cursor.epoch, cursor.seq])}`;
54
55
  await owner.beginGeneration({ ...identity, epoch: cursor.epoch, startSeq: (seq + 1n).toString(), headSeq: cursor.seq,
55
56
  windowStart: cursor.windowStart, basis: [] }, generation);
56
57
  if ((await owner.generationProgress(generation)).status === "validated") {