@allbluecn/collab-server 0.0.0-stage → 0.1.7

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 (39) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +126 -2
  3. package/package.json +64 -3
  4. package/src/__tests__/clients.test.ts +93 -0
  5. package/src/__tests__/embed.test.ts +227 -0
  6. package/src/__tests__/env-setup.ts +33 -0
  7. package/src/__tests__/exporters-bug.test.ts +552 -0
  8. package/src/__tests__/exporters-case.test.ts +356 -0
  9. package/src/__tests__/exporters-design.test.ts +356 -0
  10. package/src/__tests__/exporters-knowledge.test.ts +366 -0
  11. package/src/__tests__/exporters-stats.test.ts +105 -0
  12. package/src/__tests__/exporters-story.test.ts +519 -0
  13. package/src/__tests__/internal-apply-channel.test.ts +233 -0
  14. package/src/__tests__/internal-apply-race.test.ts +165 -0
  15. package/src/__tests__/internal-apply.test.ts +418 -0
  16. package/src/__tests__/multiplex.test.ts +166 -0
  17. package/src/__tests__/persistence-retry.test.ts +262 -0
  18. package/src/__tests__/persistence.test.ts +302 -0
  19. package/src/__tests__/server.test.ts +145 -0
  20. package/src/__tests__/share-room-limit.test.ts +183 -0
  21. package/src/__tests__/shutdown.test.ts +130 -0
  22. package/src/__tests__/test-utils.ts +176 -0
  23. package/src/auth.ts +84 -0
  24. package/src/clients.ts +133 -0
  25. package/src/embed.ts +156 -0
  26. package/src/exporters/bug.ts +454 -0
  27. package/src/exporters/case.ts +317 -0
  28. package/src/exporters/design.ts +268 -0
  29. package/src/exporters/entity-shared.ts +75 -0
  30. package/src/exporters/knowledge.ts +259 -0
  31. package/src/exporters/story.ts +483 -0
  32. package/src/exporters.ts +173 -0
  33. package/src/index.ts +354 -0
  34. package/src/internal-apply-limit.ts +99 -0
  35. package/src/internal-apply.ts +888 -0
  36. package/src/metrics.ts +82 -0
  37. package/src/persistence.ts +409 -0
  38. package/src/rooms.ts +32 -0
  39. package/src/share-room-limit.ts +73 -0
@@ -0,0 +1,519 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ // Story 回写导出器 + /internal/apply entity room 集成测试(Yjs 多人协作
19
+ // §5.2 回写 / §5.3 写入路由 / §10.2 持久来源,任务 21;真实 WS + 真实共享
20
+ // 开发库,test-exp- 前缀精确清理——结构对齐任务 16/17 的 knowledge 先例):
21
+ //
22
+ // 1. 协同落库后 Story 各列与 Y 状态一致:description({html,markdown} JSON
23
+ // 串)+ 8 字段(含 StoryLabel diff 同步、yyyy-MM-dd → UTC 午夜 Date)
24
+ // 2. 活动记录归属正确:StoryActivity 写归属作者 userId(无 actorType 字段,
25
+ // 零 schema 改动)+ metadata 变更流水(changedFields/perAuthor)
26
+ // 3. 交接锚点 M②:CollabDocument.updatedAt ≥ story.updatedAt(同事务显式
27
+ // touch,防 T14 判定误触发重种子化炸掉协同历史)
28
+ // 4. /internal/apply entity:story:在线 → content 整文档 replace + fields
29
+ // merge 进 Y 并广播(归属 actor);离线 → collab 直落业务列(含活动)+
30
+ // 不触碰快照行(旁路写 → 重种子化判定成立)
31
+ // 5. 幽灵 room:装载拒绝 / 落库检出断开;删除后不复活
32
+
33
+ import { afterEach, beforeEach, describe, expect, test } from "vitest";
34
+ import * as Y from "yjs";
35
+ import { HocuspocusProvider } from "@hocuspocus/provider";
36
+ import { buildRoomName } from "@allbluecn/collab-core/rooms";
37
+ import {
38
+ INTERNAL_DOMAIN_APPLY,
39
+ INTERNAL_SIGNATURE_HEADER,
40
+ signInternalRequest,
41
+ } from "@allbluecn/collab-core/internal";
42
+ import { seedYDocFromHtml } from "@allbluecn/collab-core/tiptap-export";
43
+ import { createKnowledgeExtensions } from "@allbluecn/collab-core/knowledge-schema";
44
+ import { createKnowledgeDocAdditions } from "@allbluecn/collab-core/knowledge-additions";
45
+ import { prisma } from "@allbluecn/database";
46
+ import {
47
+ TEST_SECRET,
48
+ connectProvider,
49
+ issueTicket,
50
+ sleep,
51
+ startCollabServer,
52
+ waitUntil,
53
+ type ProviderSession,
54
+ type StartedServer,
55
+ } from "./test-utils";
56
+ import { ensureServerDom, registerKnowledgeCollab } from "../exporters/knowledge";
57
+ import { registerStoryCollab } from "../exporters/story";
58
+ import { resetExporters, resetRoomGuards } from "../exporters";
59
+
60
+ /** 测试资源前缀(storyId / userId / projectId / labelId 共用) */
61
+ const PREFIX = "test-exp-";
62
+ /** room 名清理前缀(entity:story:test-exp-*) */
63
+ const ROOM_LIKE = `entity:story:${PREFIX}`;
64
+
65
+ interface TestStory {
66
+ actorId: string;
67
+ otherUserId: string;
68
+ projectId: string;
69
+ storyId: string;
70
+ parentStoryId: string;
71
+ labelIds: string[];
72
+ room: string;
73
+ }
74
+
75
+ function rand(): string {
76
+ return Math.random().toString(36).slice(2, 10);
77
+ }
78
+
79
+ /** 建需求测试行:双 User → Project → 父/子 Story → 3 Label + 子 Story 挂 Label[0] */
80
+ async function createStoryFixture(): Promise<TestStory> {
81
+ const suffix = rand();
82
+ const actorId = `${PREFIX}user-${suffix}`;
83
+ const otherUserId = `${PREFIX}user-${suffix}-b`;
84
+ const projectId = `${PREFIX}proj-${suffix}`;
85
+ const storyId = `${PREFIX}story-${suffix}`;
86
+ const parentStoryId = `${PREFIX}story-${suffix}-p`;
87
+ for (const [id, email] of [
88
+ [actorId, `${suffix}@collab-story.test`],
89
+ [otherUserId, `${suffix}-b@collab-story.test`],
90
+ ] as const) {
91
+ await prisma.user.create({
92
+ data: { id, email, username: `collab-story-${id.slice(PREFIX.length)}`, password: "test-only" },
93
+ });
94
+ }
95
+ await prisma.project.create({
96
+ data: { id: projectId, name: "协同回写测试项目", ownerId: actorId },
97
+ });
98
+ await prisma.story.create({
99
+ data: {
100
+ id: parentStoryId,
101
+ sequenceId: 1,
102
+ identifier: `STORY-P-${suffix}`,
103
+ projectId,
104
+ name: "父需求",
105
+ createdById: actorId,
106
+ },
107
+ });
108
+ await prisma.story.create({
109
+ data: {
110
+ id: storyId,
111
+ sequenceId: 2,
112
+ identifier: `STORY-C-${suffix}`,
113
+ projectId,
114
+ name: "旧名",
115
+ description: JSON.stringify({ html: "<p>旧描述</p>", markdown: "旧描述" }),
116
+ createdById: actorId,
117
+ parentId: parentStoryId,
118
+ },
119
+ });
120
+ const labelIds: string[] = [];
121
+ for (let i = 0; i < 3; i++) {
122
+ const labelId = `${PREFIX}label-${suffix}-${i}`;
123
+ await prisma.label.create({
124
+ data: { id: labelId, name: `协同测试标签-${suffix}-${i}`, createdById: actorId },
125
+ });
126
+ labelIds.push(labelId);
127
+ }
128
+ await prisma.storyLabel.create({ data: { storyId, labelId: labelIds[0]! } });
129
+ const room = buildRoomName({ kind: "entity-story", storyId });
130
+ return { actorId, otherUserId, projectId, storyId, parentStoryId, labelIds, room };
131
+ }
132
+
133
+ async function cleanOwnRows(): Promise<void> {
134
+ await prisma.collabUpdate.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
135
+ await prisma.collabClient.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
136
+ await prisma.collabDocument.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
137
+ await prisma.storyActivity.deleteMany({ where: { storyId: { startsWith: PREFIX } } });
138
+ await prisma.storyLabel.deleteMany({ where: { storyId: { startsWith: PREFIX } } });
139
+ await prisma.story.deleteMany({ where: { id: { startsWith: PREFIX } } });
140
+ await prisma.label.deleteMany({ where: { id: { startsWith: PREFIX } } });
141
+ await prisma.project.deleteMany({ where: { id: { startsWith: PREFIX } } });
142
+ await prisma.user.deleteMany({ where: { id: { startsWith: PREFIX } } });
143
+ const residue =
144
+ (await prisma.collabDocument.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
145
+ (await prisma.collabUpdate.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
146
+ (await prisma.story.count({ where: { id: { startsWith: PREFIX } } })) +
147
+ (await prisma.user.count({ where: { id: { startsWith: PREFIX } } }));
148
+ expect(residue).toBe(0);
149
+ }
150
+
151
+ /** 与种子化同一扩展组合(默认集 + 追加集)把 HTML 变成 Y update */
152
+ function htmlToUpdates(html: string): Uint8Array {
153
+ const yDoc = seedYDocFromHtml(html, [
154
+ ...createKnowledgeExtensions(),
155
+ ...createKnowledgeDocAdditions(),
156
+ ]);
157
+ return Y.encodeStateAsUpdate(yDoc);
158
+ }
159
+
160
+ function htmlToState(html: string): Uint8Array<ArrayBuffer> {
161
+ return new Uint8Array(htmlToUpdates(html));
162
+ }
163
+
164
+ /** 内部应用请求(信封签名) */
165
+ async function postApply(
166
+ ctx: StartedServer,
167
+ payload: Record<string, unknown>,
168
+ ): Promise<Response> {
169
+ const signed = signInternalRequest({
170
+ secret: TEST_SECRET,
171
+ domain: INTERNAL_DOMAIN_APPLY,
172
+ payload,
173
+ });
174
+ return fetch(`http://127.0.0.1:${ctx.port}/internal/apply`, {
175
+ method: "POST",
176
+ headers: {
177
+ "content-type": "application/json",
178
+ [INTERNAL_SIGNATURE_HEADER]: signed.headers[INTERNAL_SIGNATURE_HEADER]!,
179
+ },
180
+ body: signed.body,
181
+ });
182
+ }
183
+
184
+ /** 轮询 DB 断言(异步落库无法同步等待) */
185
+ async function pollDb(check: () => Promise<boolean>, label: string, timeoutMs = 8000): Promise<void> {
186
+ const deadline = Date.now() + timeoutMs;
187
+ while (!(await check())) {
188
+ if (Date.now() > deadline) throw new Error(`pollDb 超时(${label})`);
189
+ await sleep(50);
190
+ }
191
+ }
192
+
193
+ describe("story exporter + /internal/apply entity room(真实 WS + 真实库)", () => {
194
+ let ctx: StartedServer;
195
+ let session: ProviderSession | null = null;
196
+
197
+ beforeEach(async () => {
198
+ await ensureServerDom();
199
+ registerKnowledgeCollab();
200
+ registerStoryCollab();
201
+ ctx = await startCollabServer({ persistence: {}, debounceMs: 300 });
202
+ });
203
+
204
+ afterEach(async () => {
205
+ session?.destroy();
206
+ session = null;
207
+ await ctx?.stop();
208
+ resetExporters();
209
+ resetRoomGuards();
210
+ await cleanOwnRows();
211
+ });
212
+
213
+ test("场景 1:协同落库后 Story 各列与 Y 状态一致(description 双轨 + 8 字段 + 标签 diff)", async () => {
214
+ const fx = await createStoryFixture();
215
+ // 模拟协同已开启:先有快照行(provider 装载即得该态)
216
+ await prisma.collabDocument.create({
217
+ data: { roomName: fx.room, state: htmlToState("<p>旧描述</p>") },
218
+ });
219
+
220
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
221
+ const doc = session.provider.document as Y.Doc;
222
+ // description fragment 编辑(并发追加段落)
223
+ Y.applyUpdate(doc, htmlToUpdates("<p>协同新描述</p>"));
224
+ // 8 字段写 Y(与任务 20 写端同形:JSON 兼容原值)
225
+ const fields = doc.getMap("fields");
226
+ doc.transact(() => {
227
+ fields.set("name", "协同新名");
228
+ fields.set("state", "in_progress");
229
+ fields.set("priority", "high");
230
+ fields.set("assigneeId", fx.otherUserId);
231
+ fields.set("startDate", "2026-03-01");
232
+ fields.set("targetDate", "2026-03-15");
233
+ fields.set("labelIds", [fx.labelIds[1], fx.labelIds[2]]);
234
+ fields.set("parentId", null);
235
+ });
236
+
237
+ await pollDb(async () => {
238
+ const row = await prisma.story.findUnique({ where: { id: fx.storyId } });
239
+ return row?.name === "协同新名" && row?.state === "in_progress";
240
+ }, "字段落库");
241
+
242
+ const row = await prisma.story.findUnique({
243
+ where: { id: fx.storyId },
244
+ include: { labels: true },
245
+ });
246
+ expect(row!.name).toBe("协同新名");
247
+ expect(row!.state).toBe("in_progress");
248
+ expect(row!.priority).toBe("high");
249
+ expect(row!.assigneeId).toBe(fx.otherUserId);
250
+ // yyyy-MM-dd → UTC 午夜 Date(口径注释见 exporters/story.ts dateFromYmd)
251
+ expect(row!.startDate!.toISOString()).toBe("2026-03-01T00:00:00.000Z");
252
+ expect(row!.targetDate!.toISOString()).toBe("2026-03-15T00:00:00.000Z");
253
+ // parentId 显式 null 清空(fixture 里挂了父需求)
254
+ expect(row!.parentId).toBeNull();
255
+ // description {html, markdown} 双轨 JSON 串(Text 列,与 parseStoryDescription 对称)
256
+ const desc = JSON.parse(row!.description!) as { html: string; markdown: string };
257
+ expect(desc.html).toContain("协同新描述");
258
+ expect(desc.markdown).toContain("协同新描述");
259
+ // labels diff 同步:原 [label0] → [label1, label2](增删 StoryLabel 子行)
260
+ expect(row!.labels.map((l) => l.labelId).sort()).toEqual(
261
+ [fx.labelIds[1], fx.labelIds[2]].sort(),
262
+ );
263
+ });
264
+
265
+ test("场景 2:活动记录归属正确——StoryActivity 写归属作者 userId + 变更流水(零 schema 改动)", async () => {
266
+ const fx = await createStoryFixture();
267
+ await prisma.collabDocument.create({
268
+ data: { roomName: fx.room, state: htmlToState("<p>起点</p>") },
269
+ });
270
+
271
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
272
+ const doc = session.provider.document as Y.Doc;
273
+ Y.applyUpdate(doc, htmlToUpdates("<p>归属作者的活动</p>"));
274
+ const fields = doc.getMap("fields");
275
+ fields.set("state", "done");
276
+
277
+ await pollDb(async () => {
278
+ const rows = await prisma.storyActivity.findMany({
279
+ where: { storyId: fx.storyId, action: "collab_update" },
280
+ });
281
+ return rows.length > 0;
282
+ }, "协同活动落库");
283
+
284
+ const activities = await prisma.storyActivity.findMany({
285
+ where: { storyId: fx.storyId, action: "collab_update" },
286
+ });
287
+ expect(activities).toHaveLength(1);
288
+ const activity = activities[0]!;
289
+ // 归属作者:主作者 userId 直写(StoryActivity 无 actorType 字段——计划复审口径)
290
+ expect(activity.userId).toBe(fx.actorId);
291
+ const meta = activity.metadata as {
292
+ source?: string;
293
+ summary?: string;
294
+ changedFields?: string[];
295
+ };
296
+ expect(meta.source).toBe("collab");
297
+ expect(meta.summary).toBe("更新了需求");
298
+ expect(meta.changedFields).toContain("description");
299
+ expect(meta.changedFields).toContain("state");
300
+ });
301
+
302
+ test("场景 3(锚点 M②):CollabDocument.updatedAt ≥ story.updatedAt——同事务显式 touch", async () => {
303
+ const fx = await createStoryFixture();
304
+ await prisma.collabDocument.create({
305
+ data: { roomName: fx.room, state: htmlToState("<p>起点</p>") },
306
+ });
307
+
308
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
309
+ const doc = session.provider.document as Y.Doc;
310
+ Y.applyUpdate(doc, htmlToUpdates("<p>touch 断言</p>"));
311
+
312
+ await pollDb(async () => {
313
+ const row = await prisma.story.findUnique({ where: { id: fx.storyId } });
314
+ return Boolean(row?.description?.includes("touch 断言"));
315
+ }, "导出器回写 description");
316
+
317
+ const row = await prisma.story.findUnique({ where: { id: fx.storyId } });
318
+ const snap = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
319
+ // 下次协同打开的 T14 判定输入:story.updatedAt ≤ collab.updatedAt → 直读快照
320
+ // (不 touch 或毫秒倒挂都会让判定误判旁路写 → 重种子化炸协同历史)
321
+ expect(row!.updatedAt.getTime()).toBeLessThanOrEqual(snap!.updatedAt.getTime());
322
+ // 无字段 diff 时(本轮只有 description 变化)also holds——任何变更路径都 touch
323
+ });
324
+
325
+ test("场景 4:per-author 占比——双作者并发编辑,主作者落 StoryActivity.userId", async () => {
326
+ const fx = await createStoryFixture();
327
+ await prisma.collabDocument.create({
328
+ data: { roomName: fx.room, state: htmlToState("<p>空</p>") },
329
+ });
330
+
331
+ const editorA = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
332
+ Y.applyUpdate(editorA.provider.document, htmlToUpdates("<p>甲的段落</p>"));
333
+ const editorB = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.otherUserId }));
334
+ await waitUntil(() => editorB.provider.document.getXmlFragment("default").length > 0, "B 同步");
335
+ Y.applyUpdate(editorB.provider.document, htmlToUpdates("<p>乙的更长的段落内容</p>"));
336
+
337
+ await pollDb(async () => {
338
+ const rows = await prisma.storyActivity.findMany({
339
+ where: { storyId: fx.storyId, action: "collab_update" },
340
+ });
341
+ return rows.some((row) => {
342
+ const meta = row.metadata as { perAuthor?: Array<{ authorId: string | null }> };
343
+ return (meta.perAuthor?.length ?? 0) >= 2;
344
+ });
345
+ }, "双作者归属统计");
346
+
347
+ const rows = await prisma.storyActivity.findMany({
348
+ where: { storyId: fx.storyId, action: "collab_update" },
349
+ });
350
+ const merged = rows.find((row) => {
351
+ const meta = row.metadata as { perAuthor?: Array<{ authorId: string | null }> };
352
+ return (meta.perAuthor?.length ?? 0) >= 2;
353
+ })!;
354
+ const meta = merged.metadata as {
355
+ perAuthor?: Array<{ authorId: string | null; share: number }>;
356
+ };
357
+ const authors = meta.perAuthor!.map((p) => p.authorId).sort();
358
+ expect(authors).toEqual([fx.actorId, fx.otherUserId].sort());
359
+ // 主作者 = 占比最高者,落 StoryActivity.userId
360
+ const top = meta.perAuthor!.slice().sort((a, b) => b.share - a.share)[0]!;
361
+ expect(merged.userId).toBe(top.authorId);
362
+ editorA.destroy();
363
+ editorB.destroy();
364
+ });
365
+
366
+ test("场景 5:/internal/apply entity room 在线 → content 整文档 replace + fields merge 进 Y(归属 actor)", async () => {
367
+ const fx = await createStoryFixture();
368
+ await prisma.collabDocument.create({
369
+ data: { roomName: fx.room, state: htmlToState("<p>初始</p>") },
370
+ });
371
+
372
+ session = await connectProvider(ctx.url, fx.room, issueTicket(fx.room, { sub: fx.actorId }));
373
+ const res = await postApply(ctx, {
374
+ roomName: fx.room,
375
+ docId: fx.storyId,
376
+ actor: fx.actorId,
377
+ patch: {
378
+ content: { html: "<p>外部权威描述</p>", markdown: "外部权威描述" },
379
+ fields: { state: "todo", labelIds: [fx.labelIds[2]] },
380
+ },
381
+ });
382
+ expect(res.status).toBe(202);
383
+ // 同 exporters-case:容忍在线判定握手窗口的离线误判(db + reapplied 补偿)终态
384
+ const appliedBody = (await res.json()) as { applied: string; reapplied?: string };
385
+ if (appliedBody.applied === "db") {
386
+ expect(appliedBody.reapplied).toBe("ydoc");
387
+ } else {
388
+ expect(appliedBody.applied).toBe("ydoc");
389
+ }
390
+
391
+ // 广播:fields merge 可见 + fragment 整文档替换(初始内容被覆盖)
392
+ const doc = session.provider.document as Y.Doc;
393
+ await waitUntil(() => doc.getMap("fields").get("state") === "todo", "fields 未广播");
394
+ await waitUntil(() => {
395
+ const json = JSON.stringify(doc.getXmlFragment("default").toJSON());
396
+ return json.includes("外部权威描述") && !json.includes("初始");
397
+ }, "description 未广播");
398
+
399
+ // 落库走 onStoreDocument 统一链路:exporter 把 Y 态回写业务列 + 活动归属 actor
400
+ await pollDb(async () => {
401
+ const row = await prisma.story.findUnique({ where: { id: fx.storyId } });
402
+ return row?.state === "todo";
403
+ }, "字段经 exporter 落库");
404
+ const row = await prisma.story.findUnique({ where: { id: fx.storyId }, include: { labels: true } });
405
+ expect(row!.labels.map((l) => l.labelId)).toEqual([fx.labelIds[2]]);
406
+ expect(row!.description).toContain("外部权威描述");
407
+ const activity = await prisma.storyActivity.findFirst({
408
+ where: { storyId: fx.storyId, action: "collab_update" },
409
+ });
410
+ expect(activity?.userId).toBe(fx.actorId);
411
+
412
+ // 顺序不变式(锚点 M②/T17 同口径):story.updatedAt ≤ 快照 updatedAt。
413
+ // internal-apply 在线段被误判离线时,上面的 pollDb 会被直落提前满足,而补偿 Y 变更的
414
+ // onStoreDocument(2s debounce)尚未 touch 快照——以收敛式等待终态(不变式语义不弱化)
415
+ await pollDb(async () => {
416
+ const r = await prisma.story.findUnique({ where: { id: fx.storyId } });
417
+ const s = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
418
+ return Boolean(r && s && r.updatedAt.getTime() <= s.updatedAt.getTime());
419
+ }, "顺序不变式收敛(story ≤ 快照)");
420
+ });
421
+
422
+ test("场景 6:/internal/apply entity room 离线 → collab 直落业务列(含活动)+ 快照行不触碰(重种子化判定成立)", async () => {
423
+ const fx = await createStoryFixture();
424
+ const oldState = htmlToState("<p>旧描述</p>");
425
+ await prisma.collabDocument.create({ data: { roomName: fx.room, state: oldState } });
426
+ const snapBefore = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
427
+
428
+ const res = await postApply(ctx, {
429
+ roomName: fx.room,
430
+ docId: fx.storyId,
431
+ actor: fx.actorId,
432
+ patch: {
433
+ content: { html: "<p>旁路权威描述</p>", markdown: "旁路权威描述" },
434
+ fields: { state: "todo", name: "旁路新名" },
435
+ },
436
+ });
437
+ expect(res.status).toBe(202);
438
+ expect(await res.json()).toMatchObject({ applied: "db" });
439
+
440
+ const row = await prisma.story.findUnique({ where: { id: fx.storyId }, include: { labels: true } });
441
+ expect(row!.state).toBe("todo");
442
+ expect(row!.name).toBe("旁路新名");
443
+ expect(row!.description).toContain("旁路权威描述");
444
+ // 离线直落也写活动(与 web 直写同语义的 DB 终态)
445
+ const activity = await prisma.storyActivity.findFirst({
446
+ where: { storyId: fx.storyId, action: "collab_update" },
447
+ });
448
+ expect(activity?.userId).toBe(fx.actorId);
449
+
450
+ // 快照行不触碰(旁路写 → 下次协同打开重种子化兜底)
451
+ const snapAfter = await prisma.collabDocument.findUnique({ where: { roomName: fx.room } });
452
+ expect(Buffer.from(snapAfter!.state).equals(Buffer.from(oldState))).toBe(true);
453
+ expect(snapAfter!.updatedAt).toEqual(snapBefore!.updatedAt);
454
+ expect(row!.updatedAt.getTime()).toBeGreaterThan(snapAfter!.updatedAt.getTime());
455
+ });
456
+
457
+ test("场景 7:幽灵 room——story 不存在拒绝装载;已删实体 409 且不落库;删除后不复活", async () => {
458
+ // 7a:装载防御——storyId 从未存在
459
+ const ghostRoom = buildRoomName({ kind: "entity-story", storyId: `${PREFIX}ghost-${rand()}` });
460
+ let rejected = false;
461
+ const ghostProvider = new HocuspocusProvider({
462
+ url: ctx.url,
463
+ name: ghostRoom,
464
+ token: issueTicket(ghostRoom, { sub: `${PREFIX}user-ghost` }),
465
+ });
466
+ ghostProvider.on("authenticationFailed", () => {
467
+ rejected = true;
468
+ });
469
+ await pollDb(() => Promise.resolve(rejected), "幽灵 story room 被拒绝装载");
470
+ expect(ctx.server.hocuspocus.documents.has(ghostRoom)).toBe(false);
471
+ ghostProvider.destroy();
472
+
473
+ // 7b:离线 apply 打在已删实体 → 409 且零写入
474
+ const fx = await createStoryFixture();
475
+ await prisma.story.delete({ where: { id: fx.storyId } });
476
+ const res = await postApply(ctx, {
477
+ roomName: fx.room,
478
+ docId: fx.storyId,
479
+ actor: fx.actorId,
480
+ patch: { fields: { state: "todo" } },
481
+ });
482
+ expect(res.status).toBe(409);
483
+
484
+ // 7c:room 存活期间实体被删 → 下次落库检出幽灵:不回写、快照不重建
485
+ const fx2 = await createStoryFixture();
486
+ const editor = await connectProvider(ctx.url, fx2.room, issueTicket(fx2.room, { sub: fx2.actorId }));
487
+ Y.applyUpdate(editor.provider.document, htmlToUpdates("<p>第一次导出</p>"));
488
+ await pollDb(
489
+ async () => (await prisma.collabDocument.count({ where: { roomName: fx2.room } })) > 0,
490
+ "首轮快照",
491
+ );
492
+ await prisma.story.delete({ where: { id: fx2.storyId } });
493
+ await prisma.collabDocument.deleteMany({ where: { roomName: fx2.room } });
494
+
495
+ const closedPromise = new Promise<void>((resolve) => {
496
+ editor.provider.on("close", () => resolve());
497
+ });
498
+ Y.applyUpdate(editor.provider.document, htmlToUpdates("<p>删除后的复活尝试</p>"));
499
+ await Promise.race([closedPromise, sleep(6000)]);
500
+
501
+ await pollDb(
502
+ async () => (await prisma.story.count({ where: { id: fx2.storyId } })) === 0,
503
+ "story 未被复活",
504
+ );
505
+ expect(await prisma.collabDocument.count({ where: { roomName: fx2.room } })).toBe(0);
506
+ editor.destroy();
507
+ });
508
+
509
+ test("场景 8:载荷非法——entity room 无 content 也无 fields → 400", async () => {
510
+ const fx = await createStoryFixture();
511
+ const res = await postApply(ctx, {
512
+ roomName: fx.room,
513
+ docId: fx.storyId,
514
+ actor: fx.actorId,
515
+ patch: {},
516
+ });
517
+ expect(res.status).toBe(400);
518
+ });
519
+ });