@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,366 @@
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
+ // 知识库回写导出器集成测试(Yjs 多人协作 §5.2 回写 / §10.2 持久来源,任务 16):
19
+ // 1. 编辑落库后 KnowledgeDocument.content 等于导出器产物({html, markdown} 双轨,
20
+ // 与种子化同一扩展组合——默认集 + web 自定义追加集)
21
+ // 2. 向量索引重建通知被触发(spy 通知器;生产为 HTTP 通知 web,任务 16 报告口径)
22
+ // 3. 归属统计写入 AuditLog(per-author 占比经 CollabClient 映射,主作者落 userId,
23
+ // payload 摘要「X 更新了文档」粒度——X 即 userId,由渲染方拼接)
24
+ // 4. 幽灵 room 装载防御(交接锚点 J):实体已不存在 → 返回空 doc + 断开连接 +
25
+ // 不落快照行
26
+ // 5. 删除后不复活:协同 room 存活期间实体被删 → 下次落库检出幽灵 → 内容不回写、
27
+ // 快照行不重建、连接断开
28
+ // 6. 未配置通知器:内容照常回写,不抛错(降级可见 warn-once)
29
+ //
30
+ // 数据卫生:真实 WS + 真实共享开发库(任务 6 模式)——User/KnowledgeBase/
31
+ // KnowledgeDocument/AuditLog 与 collab 三表全部 test-exp- 前缀,afterEach 精确
32
+ // 清理并断言零残留。
33
+
34
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
35
+ import * as Y from "yjs";
36
+ import { HocuspocusProvider } from "@hocuspocus/provider";
37
+ import { buildRoomName } from "@allbluecn/collab-core/rooms";
38
+ import { seedYDocFromHtml } from "@allbluecn/collab-core/tiptap-export";
39
+ import { createKnowledgeExtensions } from "@allbluecn/collab-core/knowledge-schema";
40
+ import { createKnowledgeDocAdditions } from "@allbluecn/collab-core/knowledge-additions";
41
+ import { prisma } from "@allbluecn/database";
42
+ import {
43
+ connectProvider,
44
+ issueTicket,
45
+ sleep,
46
+ startCollabServer,
47
+ waitUntil,
48
+ type StartedServer,
49
+ } from "./test-utils";
50
+ import {
51
+ ensureServerDom,
52
+ registerKnowledgeCollab,
53
+ resetKnowledgeReindexNotifier,
54
+ setKnowledgeReindexNotifier,
55
+ } from "../exporters/knowledge";
56
+ import { resetExporters, resetRoomGuards } from "../exporters";
57
+
58
+ /** 测试资源前缀(docId / userId / kbId / AuditLog.resourceId 共用) */
59
+ const PREFIX = "test-exp-";
60
+ /** room 名清理前缀 */
61
+ const ROOM_LIKE = `doc:knowledge:${PREFIX}`;
62
+
63
+ interface TestDoc {
64
+ userId: string;
65
+ kbId: string;
66
+ docId: string;
67
+ room: string;
68
+ }
69
+
70
+ const trackedRooms: string[] = [];
71
+ const trackedDocs: TestDoc[] = [];
72
+
73
+ function rand(): string {
74
+ return Math.random().toString(36).slice(2, 10);
75
+ }
76
+
77
+ /** 建知识库测试行:User → KnowledgeBase → KnowledgeDocument(软删字段全默认) */
78
+ async function createDocFixture(sentinel: unknown): Promise<TestDoc> {
79
+ const suffix = rand();
80
+ const userId = `${PREFIX}user-${suffix}`;
81
+ const kbId = `${PREFIX}kb-${suffix}`;
82
+ const docId = `${PREFIX}doc-${suffix}`;
83
+ await prisma.user.create({
84
+ data: {
85
+ id: userId,
86
+ email: `${suffix}@collab-exporter.test`,
87
+ username: `collab-exp-${suffix}`,
88
+ password: "test-only",
89
+ },
90
+ });
91
+ await prisma.knowledgeBase.create({
92
+ data: { id: kbId, name: "协同回写测试库", userId },
93
+ });
94
+ await prisma.knowledgeDocument.create({
95
+ data: { id: docId, kbId, title: "协同回写测试文档", createdBy: userId, content: sentinel as object },
96
+ });
97
+ const room = buildRoomName({ kind: "knowledge-doc", docId });
98
+ trackedRooms.push(room);
99
+ const doc = { userId, kbId, docId, room };
100
+ trackedDocs.push(doc);
101
+ return doc;
102
+ }
103
+
104
+ async function cleanOwnRows(): Promise<void> {
105
+ await prisma.collabUpdate.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
106
+ await prisma.collabClient.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
107
+ await prisma.collabDocument.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
108
+ await prisma.auditLog.deleteMany({ where: { resourceId: { startsWith: PREFIX }, action: "document.collab_update" } });
109
+ await prisma.knowledgeDocument.deleteMany({ where: { id: { startsWith: PREFIX } } });
110
+ await prisma.knowledgeBase.deleteMany({ where: { id: { startsWith: PREFIX } } });
111
+ await prisma.user.deleteMany({ where: { id: { startsWith: PREFIX } } });
112
+ const residue =
113
+ (await prisma.collabDocument.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
114
+ (await prisma.collabUpdate.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
115
+ (await prisma.knowledgeDocument.count({ where: { id: { startsWith: PREFIX } } })) +
116
+ (await prisma.user.count({ where: { id: { startsWith: PREFIX } } }));
117
+ expect(residue).toBe(0);
118
+ }
119
+
120
+ /** 与种子化同一扩展组合(默认集 + 追加集)把 HTML 变成 Y update */
121
+ function htmlToUpdates(html: string): Uint8Array {
122
+ const yDoc = seedYDocFromHtml(html, [
123
+ ...createKnowledgeExtensions(),
124
+ ...createKnowledgeDocAdditions(),
125
+ ]);
126
+ return Y.encodeStateAsUpdate(yDoc);
127
+ }
128
+
129
+ /** 建一个捕获幽灵拒绝信号的 provider(观测面:authenticationFailed / close) */
130
+ async function connectCapturingGhostRejection(
131
+ ctx: StartedServer,
132
+ room: string,
133
+ sub: string,
134
+ ): Promise<{
135
+ provider: HocuspocusProvider;
136
+ rejected: () => boolean;
137
+ closed: () => boolean;
138
+ }> {
139
+ let rejected = false;
140
+ let closed = false;
141
+ const provider = new HocuspocusProvider({
142
+ url: ctx.url,
143
+ name: room,
144
+ token: issueTicket(room, { sub }),
145
+ });
146
+ // 监听必须先于 authenticated 等待——幽灵拒绝发生在鉴权通过后的装载期
147
+ provider.on("authenticationFailed", () => {
148
+ rejected = true;
149
+ });
150
+ provider.on("close", () => {
151
+ closed = true;
152
+ });
153
+ await new Promise<void>((resolve, reject) => {
154
+ provider.on("authenticated", () => resolve());
155
+ provider.on("authenticationFailed", ({ reason }: { reason: string }) =>
156
+ reject(new Error(`鉴权失败:${reason}`)),
157
+ );
158
+ });
159
+ return { provider, rejected: () => rejected, closed: () => closed };
160
+ }
161
+
162
+ /** 轮询 DB 断言(异步落库无法同步等待) */
163
+ async function pollDb(check: () => Promise<boolean>, label: string, timeoutMs = 8000): Promise<void> {
164
+ const deadline = Date.now() + timeoutMs;
165
+ while (!(await check())) {
166
+ if (Date.now() > deadline) throw new Error(`pollDb 超时(${label})`);
167
+ await sleep(50);
168
+ }
169
+ }
170
+
171
+ describe("knowledge exporter 回写(真实 WS + 真实库)", () => {
172
+ let ctx: StartedServer;
173
+
174
+ beforeEach(async () => {
175
+ // 测试进程自身的 seed(htmlToUpdates)与被测导出器同走生产 DOM 注入路径
176
+ await ensureServerDom();
177
+ registerKnowledgeCollab();
178
+ ctx = await startCollabServer({ persistence: {}, debounceMs: 300 });
179
+ });
180
+
181
+ afterEach(async () => {
182
+ await ctx?.stop();
183
+ resetExporters();
184
+ resetRoomGuards();
185
+ resetKnowledgeReindexNotifier();
186
+ await cleanOwnRows();
187
+ });
188
+
189
+ test("场景 1:编辑落库后 content 等于导出器产物 + 通知器带 docId 触发", async () => {
190
+ const doc = await createDocFixture({ html: "<p>旧内容</p>", markdown: "旧内容" });
191
+ const reindexed: string[] = [];
192
+ setKnowledgeReindexNotifier(async (docId) => {
193
+ reindexed.push(docId);
194
+ });
195
+
196
+ const editor = await connectProvider(ctx.url, doc.room, issueTicket(doc.room, { sub: doc.userId }));
197
+ Y.applyUpdate(editor.provider.document, htmlToUpdates("<p>协同内容导出测试</p>"));
198
+
199
+ await pollDb(async () => {
200
+ const row = await prisma.knowledgeDocument.findUnique({
201
+ where: { id: doc.docId },
202
+ select: { content: true },
203
+ });
204
+ const content = row?.content as { html?: string; markdown?: string } | null;
205
+ return Boolean(content?.html?.includes("协同内容导出测试") && content?.markdown?.includes("协同内容导出测试"));
206
+ }, "content 双轨回写");
207
+
208
+ const row = await prisma.knowledgeDocument.findUnique({
209
+ where: { id: doc.docId },
210
+ select: { content: true },
211
+ });
212
+ const content = row!.content as { html: string; markdown: string };
213
+ expect(content.html).toContain("<p>协同内容导出测试</p>");
214
+ expect(content.markdown).toContain("协同内容导出测试");
215
+ expect(content.html).not.toContain("旧内容");
216
+ // notifyKnowledgeReindex 在 content 落库之后 fire-and-forget——与落库
217
+ // 断言之间存在竞态窗(任务 21 全量跑实测),同样轮询等待
218
+ await pollDb(async () => reindexed.includes(doc.docId), "通知器带 docId 触发");
219
+ editor.destroy();
220
+ });
221
+
222
+ test("场景 2:归属统计写入 AuditLog(per-author 占比 + 主作者 userId + 摘要粒度)", async () => {
223
+ const doc = await createDocFixture({ html: "<p>空</p>", markdown: "空" });
224
+
225
+ const editorA = await connectProvider(ctx.url, doc.room, issueTicket(doc.room, { sub: doc.userId }));
226
+ Y.applyUpdate(editorA.provider.document, htmlToUpdates("<p>甲的段落</p>"));
227
+ const editorB = await connectProvider(ctx.url, doc.room, issueTicket(doc.room, { sub: "test-exp-user-other" }));
228
+ await waitUntil(
229
+ () => editorB.provider.document.getText("content").length > 0 || true,
230
+ "B 同步",
231
+ );
232
+ // B 在 A 内容之上追加独立段落(并发编辑,两人都留有 struct)
233
+ Y.applyUpdate(editorB.provider.document, htmlToUpdates("<p>乙的段落</p>"));
234
+
235
+ await pollDb(async () => {
236
+ const rows = await prisma.auditLog.findMany({
237
+ where: { resourceId: doc.docId, action: "document.collab_update" },
238
+ });
239
+ return rows.some((row) => {
240
+ const meta = row.metadata as { perAuthor?: Array<{ authorId: string | null }> };
241
+ return (meta.perAuthor?.length ?? 0) >= 2;
242
+ });
243
+ }, "双作者归属统计");
244
+
245
+ const rows = await prisma.auditLog.findMany({
246
+ where: { resourceId: doc.docId, action: "document.collab_update" },
247
+ });
248
+ const merged = rows.find((row) => {
249
+ const meta = row.metadata as { perAuthor?: Array<{ authorId: string | null }> };
250
+ return (meta.perAuthor?.length ?? 0) >= 2;
251
+ })!;
252
+ const meta = merged.metadata as {
253
+ source?: string;
254
+ summary?: string;
255
+ perAuthor?: Array<{ authorId: string | null; updates: number; share: number }>;
256
+ };
257
+ expect(meta.source).toBe("collab");
258
+ expect(meta.summary).toBe("更新了文档");
259
+ const authors = meta.perAuthor!.map((p) => p.authorId).sort();
260
+ expect(authors).toEqual([doc.userId, "test-exp-user-other"].sort());
261
+ for (const entry of meta.perAuthor!) {
262
+ expect(entry.updates).toBeGreaterThanOrEqual(1);
263
+ expect(entry.share).toBeGreaterThan(0);
264
+ expect(entry.share).toBeLessThanOrEqual(1);
265
+ }
266
+ // 主作者 = 占比最高者,落 AuditLog.userId
267
+ const top = meta.perAuthor!.slice().sort((a, b) => b.share - a.share)[0]!;
268
+ expect(merged.userId).toBe(top.authorId);
269
+ editorA.destroy();
270
+ editorB.destroy();
271
+ });
272
+
273
+ test("场景 3:幽灵 room 装载防御——实体已不存在则拒绝装载 + 零快照", async () => {
274
+ // 不建 fixture:docId 从未存在
275
+ const ghostRoom = buildRoomName({ kind: "knowledge-doc", docId: `${PREFIX}ghost-${rand()}` });
276
+ trackedRooms.push(ghostRoom);
277
+ const { provider, rejected } = await connectCapturingGhostRejection(
278
+ ctx,
279
+ ghostRoom,
280
+ "test-exp-user-other",
281
+ );
282
+
283
+ // 装载期守卫抛错 → 服务端发 permissionDenied → provider authenticationFailed
284
+ await pollDb(() => Promise.resolve(rejected()), "幽灵 room 被拒绝装载");
285
+ expect(ctx.server.hocuspocus.documents.has(ghostRoom)).toBe(false);
286
+ const snapshot = await prisma.collabDocument.count({ where: { roomName: ghostRoom } });
287
+ expect(snapshot).toBe(0);
288
+ provider.destroy();
289
+ });
290
+
291
+ test("场景 4:删除后不复活——存活 room 的实体被删 → 内容不回写、快照不重建、连接断开", async () => {
292
+ const doc = await createDocFixture({ html: "<p>初始</p>", markdown: "初始" });
293
+ const editor = await connectProvider(ctx.url, doc.room, issueTicket(doc.room, { sub: doc.userId }));
294
+ Y.applyUpdate(editor.provider.document, htmlToUpdates("<p>第一次导出</p>"));
295
+
296
+ await pollDb(async () => {
297
+ const row = await prisma.knowledgeDocument.findUnique({
298
+ where: { id: doc.docId },
299
+ select: { content: true },
300
+ });
301
+ return Boolean((row?.content as { html?: string })?.html?.includes("第一次导出"));
302
+ }, "首轮导出");
303
+ await pollDb(
304
+ async () =>
305
+ (await prisma.collabDocument.count({ where: { roomName: doc.room } })) > 0,
306
+ "首轮快照",
307
+ );
308
+
309
+ // 模拟 web 删除路径(软删实体 + 删快照行),room 仍存活
310
+ await prisma.knowledgeDocument.update({ where: { id: doc.docId }, data: { isDeleted: true } });
311
+ await prisma.collabDocument.deleteMany({ where: { roomName: doc.room } });
312
+
313
+ // 删除后的编辑触发下次落库:guard 检出幽灵 → 跳过 + 断开
314
+ const closedPromise = new Promise<void>((resolve) => {
315
+ editor.provider.on("close", () => resolve());
316
+ });
317
+ Y.applyUpdate(editor.provider.document, htmlToUpdates("<p>删除后的复活尝试</p>"));
318
+ await Promise.race([closedPromise, sleep(6000)]);
319
+
320
+ await pollDb(async () => {
321
+ const row = await prisma.knowledgeDocument.findUnique({
322
+ where: { id: doc.docId },
323
+ select: { content: true },
324
+ });
325
+ return !(row?.content as { html?: string })?.html?.includes("复活尝试");
326
+ }, "内容未被复活");
327
+ const snapshot = await prisma.collabDocument.count({ where: { roomName: doc.room } });
328
+ expect(snapshot).toBe(0);
329
+ editor.destroy();
330
+ });
331
+
332
+ test("场景 5:未配置通知器——内容照常回写且不抛错(降级 warn-once)", async () => {
333
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
334
+ try {
335
+ const doc = await createDocFixture({ html: "<p>旧</p>", markdown: "旧" });
336
+ const editor = await connectProvider(ctx.url, doc.room, issueTicket(doc.room, { sub: doc.userId }));
337
+ Y.applyUpdate(editor.provider.document, htmlToUpdates("<p>无通知器导出</p>"));
338
+
339
+ await pollDb(async () => {
340
+ const row = await prisma.knowledgeDocument.findUnique({
341
+ where: { id: doc.docId },
342
+ select: { content: true },
343
+ });
344
+ return Boolean((row?.content as { html?: string })?.html?.includes("无通知器导出"));
345
+ }, "无通知器仍回写");
346
+ // notifyKnowledgeReindex 在 content 落库之后执行——pollDb 可能在两者
347
+ // 之间观察到 content(2026-10-07 任务 21 全量跑实测一次 flake),warn
348
+ // 断言同样轮询等待消除竞态
349
+ await pollDb(async () => warnSpy.mock.calls.length > 0, "warn-once 触发");
350
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("向量索引重建通知未配置"));
351
+ editor.destroy();
352
+ } finally {
353
+ warnSpy.mockRestore();
354
+ }
355
+ });
356
+ });
357
+
358
+ describe("DOM 注入(exporter 运行时前置)", () => {
359
+ test("ensureServerDom 在 node 环境注入 DOM 全局(幂等)", async () => {
360
+ await ensureServerDom();
361
+ expect(typeof globalThis.window).toBe("object");
362
+ expect(typeof globalThis.document).toBe("object");
363
+ // 幂等:二次调用不抛不覆盖
364
+ await ensureServerDom();
365
+ });
366
+ });
@@ -0,0 +1,105 @@
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
+ // 归属统计共享助手(computeAuthorAttribution,2026-10-25 审计 A07 🔵 五处
19
+ // 复制收敛)与 bug 活动 hint 上界/释放的单元测试(纯内存,不触库)。
20
+
21
+ import { describe, expect, test } from "vitest";
22
+ import { buildRoomName } from "@allbluecn/collab-core/rooms";
23
+ import { computeAuthorAttribution, type CollabAuthorStat } from "../exporters";
24
+ import {
25
+ drainBugActivityHints,
26
+ forgetBugActivityHints,
27
+ MAX_PENDING_ACTIVITY_HINTS_PER_ROOM,
28
+ notifyBugActivityHint,
29
+ } from "../exporters/bug";
30
+
31
+ function stat(authorId: string | null, updates: number, bytes: number): CollabAuthorStat {
32
+ return { authorId, updates, bytes };
33
+ }
34
+
35
+ describe("computeAuthorAttribution(§10.2 per-author 汇总单源)", () => {
36
+ test("主作者按字节降序、平局比条数", () => {
37
+ const result = computeAuthorAttribution([
38
+ stat("user-a", 3, 100),
39
+ stat("user-b", 1, 300),
40
+ stat("user-c", 9, 300),
41
+ ]);
42
+ // user-b 与 user-c 字节并列,user-c 条数多 → 主作者 user-c
43
+ expect(result.primary).toBe("user-c");
44
+ expect(result.totalBytes).toBe(700);
45
+ });
46
+
47
+ test("perAuthor share 4 位小数、未归属单列", () => {
48
+ const result = computeAuthorAttribution([
49
+ stat("user-a", 1, 750),
50
+ stat(null, 2, 250),
51
+ ]);
52
+ expect(result.primary).toBe("user-a");
53
+ expect(result.perAuthor).toEqual([
54
+ { authorId: "user-a", updates: 1, bytes: 750, share: 0.75 },
55
+ { authorId: null, updates: 2, bytes: 250, share: 0.25 },
56
+ ]);
57
+ });
58
+
59
+ test("全批次无归属 → primary null(宁缺勿错);唯一作者占满 share", () => {
60
+ const result = computeAuthorAttribution([stat(null, 2, 100)]);
61
+ expect(result.primary).toBeNull();
62
+ expect(result.perAuthor[0]!.share).toBe(1);
63
+ });
64
+
65
+ test("零字节批次 → share 为 0(totalBytes=0 分母守卫)", () => {
66
+ const result = computeAuthorAttribution([stat(null, 2, 0), stat("user-a", 1, 0)]);
67
+ expect(result.primary).toBe("user-a");
68
+ expect(result.perAuthor.every((row) => row.share === 0)).toBe(true);
69
+ });
70
+
71
+ test("空批次 → primary null、零字节", () => {
72
+ const result = computeAuthorAttribution([]);
73
+ expect(result.primary).toBeNull();
74
+ expect(result.totalBytes).toBe(0);
75
+ expect(result.perAuthor).toEqual([]);
76
+ });
77
+ });
78
+
79
+ describe("bug 活动 hint 上界与释放(防幽灵/长期无 store 滞留)", () => {
80
+ const room = buildRoomName({ kind: "entity-bug", bugId: "hint-cap-test" });
81
+ const hint = (n: number) => ({ action: "reopened_by_sdk", actor: `sdk:test-${n}` });
82
+
83
+ test("超上界丢弃最旧并保持上界", () => {
84
+ forgetBugActivityHints(room);
85
+ for (let i = 0; i < MAX_PENDING_ACTIVITY_HINTS_PER_ROOM + 5; i += 1) {
86
+ notifyBugActivityHint(room, hint(i));
87
+ }
88
+ const drained = drainBugActivityHints(room);
89
+ expect(drained).toHaveLength(MAX_PENDING_ACTIVITY_HINTS_PER_ROOM);
90
+ expect(drained[0]!.actor).toBe(`sdk:test-${5}`); // 最旧 5 条被丢弃
91
+ expect(drained.at(-1)!.actor).toBe(`sdk:test-${MAX_PENDING_ACTIVITY_HINTS_PER_ROOM + 4}`);
92
+ });
93
+
94
+ test("forgetBugActivityHints 释放(卸载/幽灵路径调用)", () => {
95
+ notifyBugActivityHint(room, hint(0));
96
+ forgetBugActivityHints(room);
97
+ expect(drainBugActivityHints(room)).toEqual([]);
98
+ });
99
+
100
+ test("drain 幂等:出队后为空", () => {
101
+ notifyBugActivityHint(room, hint(1));
102
+ expect(drainBugActivityHints(room)).toHaveLength(1);
103
+ expect(drainBugActivityHints(room)).toEqual([]);
104
+ });
105
+ });