@morlay/dsh-session 0.0.0-stage → 0.2.0-alpha.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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +27 -2
  3. package/dist/contract-DcuROwBE.mjs +263 -0
  4. package/dist/contract.d.mts +3 -0
  5. package/dist/contract.mjs +3 -0
  6. package/dist/decorate-g56z_1VW.mjs +8 -0
  7. package/dist/endpoint.d.mts +261 -0
  8. package/dist/endpoint.mjs +256 -0
  9. package/dist/index-CslqzhJh.d.mts +87 -0
  10. package/dist/index.d.mts +5 -0
  11. package/dist/index.mjs +5 -0
  12. package/dist/rolldown-runtime-3qf6kE1h.d.mts +1 -0
  13. package/dist/server.d.mts +23 -0
  14. package/dist/server.mjs +35 -0
  15. package/dist/testing.d.mts +213 -0
  16. package/dist/testing.mjs +840 -0
  17. package/dist/token-meter.contract-BoF6536N.d.mts +136 -0
  18. package/dist/token-meter.contract-CVJ4qB0S.mjs +20 -0
  19. package/dist/token-meter.service-B_UwV7QS.d.mts +45 -0
  20. package/dist/token-meter.service-DVClfYcN.mjs +83 -0
  21. package/dist/ui.d.mts +50 -0
  22. package/dist/ui.mjs +77 -0
  23. package/package.json +65 -3
  24. package/src/contract/events.ts +62 -0
  25. package/src/contract/index.ts +14 -0
  26. package/src/contract/session-format.contract.ts +18 -0
  27. package/src/contract/session-log.contract.ts +10 -0
  28. package/src/contract/session-projection-cache.contract.ts +33 -0
  29. package/src/contract/session-projection-store.contract.ts +47 -0
  30. package/src/contract/session-projection-value.contract.ts +10 -0
  31. package/src/contract/session-query-tracing.contract.ts +8 -0
  32. package/src/contract/session-query.contract.ts +140 -0
  33. package/src/contract/session-surface.contract.ts +5 -0
  34. package/src/contract/session-workspace.contract.ts +64 -0
  35. package/src/contract/session.contract.ts +72 -0
  36. package/src/contract/token-meter.contract.ts +22 -0
  37. package/src/endpoint/index.ts +9 -0
  38. package/src/endpoint/session-controller.remote.ts +13 -0
  39. package/src/endpoint/session-controller.ts +120 -0
  40. package/src/endpoint/session-endpoint.ts +443 -0
  41. package/src/endpoint/session-id.ts +8 -0
  42. package/src/index.ts +15 -0
  43. package/src/server/index.ts +19 -0
  44. package/src/server/session-projection-cache.provide.ts +5 -0
  45. package/src/server/session-projection.provide.ts +10 -0
  46. package/src/server/session-projection.registry.ts +4 -0
  47. package/src/server/session-query.provide.ts +5 -0
  48. package/src/server/session-stats.service.ts +18 -0
  49. package/src/server/session-store.plugin.ts +4 -0
  50. package/src/server/session.provide.ts +5 -0
  51. package/src/server/sessions-host.provide.ts +6 -0
  52. package/src/server/token-meter.provide.ts +5 -0
  53. package/src/session-projection-cache.service.ts +41 -0
  54. package/src/session-projection-store.service.ts +15 -0
  55. package/src/session-query.service.ts +37 -0
  56. package/src/session-turn-outline.service.ts +2 -0
  57. package/src/session.service.ts +12 -0
  58. package/src/testing/context.ts +35 -0
  59. package/src/testing/coordinator-contract.ts +496 -0
  60. package/src/testing/index.ts +25 -0
  61. package/src/testing/log.ts +385 -0
  62. package/src/token-meter.service.ts +14 -0
  63. package/src/ui/index.ts +4 -0
  64. package/src/ui/session-endpoint.client.ts +125 -0
@@ -0,0 +1,12 @@
1
+ // 默认实现:上游 `SessionStore` 服务类经 `fromCordis` 接管到契约令牌上。
2
+ import SessionStoreService from "@deepseek-ai/dsh-session";
3
+ import { Injectable, type Context } from "@morlay/zephyr";
4
+ import { fromCordis } from "@morlay/zephyr/compat";
5
+ import { SessionStore } from "./contract/session.contract.ts";
6
+
7
+ @Injectable()
8
+ export class SessionStoreDefault extends fromCordis(SessionStore, SessionStoreService) {
9
+ override async onInit(ctx: Context): Promise<void> {
10
+ await this.mount(ctx);
11
+ }
12
+ }
@@ -0,0 +1,35 @@
1
+ // 会话域的**最小装配 helper**:真 cordis ctx + 真 `SessionStore`(服务名 `sessions`)。
2
+ //
3
+ // 只做这一件事:下游 spec 不必各自 `new CordisContext()` + `new SessionStore(ctx)`。
4
+ // 它**不**装 apps 的清单、也不装 llm / tools / 端点行——那些是各自域的事(要就自己往这个 ctx 上挂)。
5
+ import { Context as CordisContext } from "@deepseek-ai/cordis/src/context.ts";
6
+ import { SessionStore } from "@deepseek-ai/dsh-session";
7
+ import type { Context } from "@morlay/zephyr";
8
+
9
+ /**
10
+ * 测试用的会话 ctx:真 cordis `Context`,加上按上游注册名发布的那一个服务。
11
+ *
12
+ * 本仓禁止 `declare module`,所以成员在这里显式声明;`get` / `provide` 也一样——cordis 靠模块增强
13
+ * 把它们挂到 Context 上,`vendor/**` 不进我们的 program 时读不到。
14
+ */
15
+ export type SessionTestContext = Context & {
16
+ readonly sessions: SessionStore;
17
+ get(name: string, strict?: boolean): unknown;
18
+ provide(name: string, value: unknown): () => void;
19
+ };
20
+
21
+ /**
22
+ * 造一份最小会话装配。
23
+ *
24
+ * 用直接构造(`new SessionStore(ctx)` 在构造里注册 `sessions`)而不是 `ctx.plugin`:后者异步生效,
25
+ * 而用例在下一行就要 `ctx.sessions.create(...)`。
26
+ * @param options - `sessions: false` 给「会话存储由别人装」的场景(别人装了再装一次就是同名重复注册)。
27
+ * @returns 带 `sessions` 的 cordis ctx。
28
+ */
29
+ export function createSessionContext(
30
+ options: { readonly sessions?: boolean } = {},
31
+ ): SessionTestContext {
32
+ const ctx = new CordisContext() as unknown as SessionTestContext;
33
+ if (options.sessions !== false) new SessionStore(ctx as never);
34
+ return ctx;
35
+ }
@@ -0,0 +1,496 @@
1
+ // 会话域的**编排契约套件**:会话存储与落盘在一起时的那十几条语义(种子账目、续写、HMR、撕裂尾部)。
2
+ //
3
+ // 套件**不起装配**:ctx 怎么造、行怎么挂都由调用方给(`createCtx` / `mount` 两个回调),
4
+ // 套件只描述「装配好之后的行为」。用例名与断言是从源包一字不改搬来的。
5
+ import { describe, expect, it } from "vitest";
6
+ import { Session, SessionId, SessionLogOffset, SessionSeq } from "@deepseek-ai/dsh-session";
7
+ import type { SessionEvent } from "@deepseek-ai/dsh-session";
8
+ import type { Context as ZephyrContext } from "@morlay/zephyr";
9
+ /** 套件要的那份**落盘句柄**:只声明用到的方法(不 import 落盘实现包的类型,会话域不依赖持久化)。 */
10
+ export interface CoordinatorHandle {
11
+ readonly header: { readonly [key: string]: unknown };
12
+ readonly inheritedEventCount: number;
13
+ read(): Promise<{ readonly [key: string]: unknown }>;
14
+ append(events: readonly unknown[]): Promise<unknown>;
15
+ close(): Promise<void>;
16
+ }
17
+
18
+ /**
19
+ * 套件要的那份**落盘面**:只用到 `open` / `create`。
20
+ *
21
+ * 成员签名与上游 `SessionPersistence` 保持一致(额外参数可选),这样任何实现都能直接传进来,
22
+ * 不需要断言——会话域也因此不必为了"套件的类型"去依赖落盘包的声明。
23
+ */
24
+ export interface CoordinatorPersistence {
25
+ open(
26
+ id: import("@deepseek-ai/dsh-session").SessionId,
27
+ mode: "read" | "write",
28
+ options?: unknown,
29
+ ): Promise<CoordinatorHandle>;
30
+ create(header: never, options?: unknown): Promise<CoordinatorHandle>;
31
+ }
32
+ import { appendLog, meta, oneTurnLog } from "./log.ts";
33
+
34
+ /**
35
+ * 套件要的那份 ctx:会话存储 + 落盘(其余成员(`plugin` / `parallel` / `get`)由 zephyr 的 ctx 提供)。
36
+ */
37
+ /** 套件要的那份**会话目录面**:只用到 `create` / `flush`(实现是谁都行)。 */
38
+ export interface CoordinatorSessions {
39
+ create(id: never, options?: unknown): unknown;
40
+ flush(session: unknown): Promise<void>;
41
+ }
42
+
43
+ export type CoordinatorContext = ZephyrContext & {
44
+ readonly sessions: CoordinatorSessions;
45
+ readonly sessionPersistence: CoordinatorPersistence;
46
+ };
47
+
48
+ /**
49
+ * 一份装配的来源:造 ctx 与挂行都由调用方实现。
50
+ *
51
+ * `Ctx` 由调用方定:它自己的 ctx 类型只要**至少**有 `sessions` 与 `sessionPersistence`——
52
+ * 套件按 `CoordinatorContext` 读这两个成员,调用方挂行时仍用自己那份更宽的类型。
53
+ */
54
+ export interface CoordinatorFixture {
55
+ /**
56
+ * 造 ctx(调用方给实现;套件不自己起装配)。
57
+ *
58
+ * 返回类型是 **`unknown`**:调用方的 ctx 往往比 `CoordinatorContext` 更宽(上游面),
59
+ * 让这里收窄会把"更宽的实现"挡在门外。套件内部按 `CoordinatorContext` 断言使用。
60
+ */
61
+ createCtx: () => unknown;
62
+
63
+ // `CordisFiber`:cordis 的 fiber 面(只要 `dispose`)。
64
+ mount: (ctx: CoordinatorContext) => Promise<{ dispose(): Promise<void> }>;
65
+
66
+ /** 造一条撕裂的物理尾部(后端专用;没有就不测那一条)。 */
67
+ corruptTail?: (id: SessionId, cwd: string | undefined) => Promise<void>;
68
+
69
+ /** 每个用例之后的清理(删临时根)。 */
70
+ cleanup: () => Promise<void>;
71
+ }
72
+
73
+ const WORK = "/w";
74
+
75
+ // `ctx.plugin(...)` 返回的是 cordis 的 fiber:运行期有 `dispose`(构造函数里赋值的 readonly 属性),
76
+ // 但 oxlint 的 typeCheck 在 `Fiber` 类型面上看不见它。这里按实际用到的面收窄一次,别在每个用例里重复。
77
+ function disposeFiber(fiber: object): Promise<void> {
78
+ return (fiber as { dispose(): Promise<void> }).dispose();
79
+ }
80
+
81
+ // 夹具里的一条用户消息:`id` 是品牌字符串,这里在边界铸一次(不引 llm 的工厂,
82
+ // 那个包归 agent 域所有,会话域不该为一份 spec 数据反向依赖它)。
83
+ type UserMessageData = Extract<SessionEvent, { type: "user/message" }>["data"];
84
+
85
+ function userMessageOf(id: string, text: string): UserMessageData {
86
+ return {
87
+ id,
88
+ role: "user",
89
+ content: [{ type: "text", text }],
90
+ source: { kind: "user" },
91
+ } as unknown as UserMessageData;
92
+ }
93
+
94
+ function send(session: Session, events: readonly SessionEvent[]): void {
95
+ appendLog(session, events);
96
+ }
97
+
98
+ export function runCoordinatorContract(
99
+ name: string,
100
+ makeFixture: () => Promise<CoordinatorFixture>,
101
+ ): void {
102
+ describe(`SessionPersistenceRdb orchestration: ${name}`, () => {
103
+ async function freshCtx(
104
+ fix: CoordinatorFixture,
105
+ ): Promise<{ ctx: CoordinatorContext; fiber: { dispose(): Promise<void> } }> {
106
+ const ctx = fix.createCtx() as CoordinatorContext;
107
+ const fiber = await fix.mount(ctx);
108
+ return { ctx, fiber };
109
+ }
110
+
111
+ async function readAll(
112
+ ctx: CoordinatorContext,
113
+ id: SessionId,
114
+ ): Promise<{ meta: Session["header"]; events: readonly SessionEvent[] }> {
115
+ const handle = await ctx.sessionPersistence.open(id, "read");
116
+ try {
117
+ const { events } = await handle.read();
118
+ return { meta: handle.header, events };
119
+ } finally {
120
+ await handle.close();
121
+ }
122
+ }
123
+
124
+ it("persists a live session driven through the store, surviving reload", async () => {
125
+ const fix = await makeFixture();
126
+ const { ctx, fiber } = await freshCtx(fix);
127
+ try {
128
+ const session = ctx.sessions.create(SessionId("live"), { meta: { cwd: WORK } });
129
+ send(session, oneTurnLog());
130
+ await ctx.sessions.flush(session);
131
+
132
+ const loaded = await readAll(ctx, SessionId("live"));
133
+ expect(loaded.events).toHaveLength(6);
134
+ expect(loaded.meta.cwd).toBe(WORK);
135
+ } finally {
136
+ await fiber.dispose();
137
+ await fix.cleanup();
138
+ }
139
+ });
140
+
141
+ it("round-trips the seed boundary (inheritedEventCount) through persistence", async () => {
142
+ const fix = await makeFixture();
143
+ const { ctx, fiber } = await freshCtx(fix);
144
+ try {
145
+ let session!: Session;
146
+ const sessionFiber = await ctx.plugin(
147
+ Object.assign(
148
+ (inner: CoordinatorContext) => {
149
+ session = inner.sessions.create(SessionId("forked-child"), {
150
+ seed: oneTurnLog().slice(0, 3),
151
+ meta: { cwd: WORK, isSeeded: true },
152
+ inheritedEventCount: SessionLogOffset(3),
153
+ });
154
+ },
155
+ { inject: ["sessions"] },
156
+ ),
157
+ );
158
+ send(session, oneTurnLog().slice(3));
159
+ await ctx.sessions.flush(session);
160
+ await disposeFiber(sessionFiber);
161
+
162
+ const handle = await ctx.sessionPersistence.open(SessionId("forked-child"), "read");
163
+ try {
164
+ expect(handle.header.isSeeded).toBe(true);
165
+ expect(handle.inheritedEventCount).toBe(3);
166
+ } finally {
167
+ await handle.close();
168
+ }
169
+ } finally {
170
+ await fiber.dispose();
171
+ await fix.cleanup();
172
+ }
173
+ });
174
+
175
+ it("round-trips the delegation depth through persistence", async () => {
176
+ const fix = await makeFixture();
177
+ const { ctx, fiber } = await freshCtx(fix);
178
+ try {
179
+ let session!: Session;
180
+ const sessionFiber = await ctx.plugin(
181
+ Object.assign(
182
+ (inner: CoordinatorContext) => {
183
+ session = inner.sessions.create(SessionId("delegated-child"), {
184
+ meta: { cwd: WORK, parentSession: SessionId("root"), delegationDepth: 2 },
185
+ });
186
+ },
187
+ { inject: ["sessions"] },
188
+ ),
189
+ );
190
+ send(session, oneTurnLog());
191
+ await ctx.parallel("session/flush", session);
192
+ await disposeFiber(sessionFiber);
193
+
194
+ const loaded = await readAll(ctx, SessionId("delegated-child"));
195
+ expect(loaded.meta.delegationDepth).toBe(2);
196
+ } finally {
197
+ await fiber.dispose();
198
+ await fix.cleanup();
199
+ }
200
+ });
201
+
202
+ it("source-frozen events cannot be mutated after buffering and persist unchanged", async () => {
203
+ const fix = await makeFixture();
204
+ const { ctx, fiber } = await freshCtx(fix);
205
+ try {
206
+ const session = ctx.sessions.create(SessionId("mutate"), { meta: { cwd: WORK } });
207
+ session.append("turn/start", { turn: 1 });
208
+ const ev = session.append("user/message", userMessageOf("mutate-user", "original"), {
209
+ surfaceOp: "append",
210
+ });
211
+ expect(() => {
212
+ (ev.data as unknown as { content: { type: "text"; text: string }[] }).content[0]!.text =
213
+ "HACKED";
214
+ }).toThrow(TypeError);
215
+ session.append("turn/end", { turn: 1, reason: { kind: "completed" } });
216
+ await ctx.sessions.flush(session);
217
+
218
+ const loaded = await readAll(ctx, SessionId("mutate"));
219
+ const message = loaded.events.find((event) => event.type === "user/message");
220
+ expect(
221
+ message?.type === "user/message" && (message.data.content[0] as { text: string }).text,
222
+ ).toBe("original");
223
+ } finally {
224
+ await fiber.dispose();
225
+ await fix.cleanup();
226
+ }
227
+ });
228
+
229
+ it("fork: a seeded new session persists its seed once (no double-write on a no-op flush)", async () => {
230
+ const fix = await makeFixture();
231
+ const { ctx, fiber } = await freshCtx(fix);
232
+ try {
233
+ const seed = oneTurnLog();
234
+
235
+ const forked = ctx.sessions.create(SessionId("forked"), { seed, meta: { cwd: WORK } });
236
+ await ctx.sessions.flush(forked);
237
+ const loaded = await readAll(ctx, SessionId("forked"));
238
+
239
+ expect(loaded.events.slice(0, seed.length)).toEqual(seed);
240
+ expect(loaded.events.at(-1)).toMatchObject({ type: "session/end-seed", seq: seed.length });
241
+
242
+ await ctx.sessions.flush(forked);
243
+ const reloaded = await readAll(ctx, SessionId("forked"));
244
+ expect(reloaded.events).toEqual(loaded.events);
245
+ } finally {
246
+ await fiber.dispose();
247
+ await fix.cleanup();
248
+ }
249
+ });
250
+
251
+ it("resume: a re-created session seeded with the loaded log does not re-append its seed and continues the seq", async () => {
252
+ const fix = await makeFixture();
253
+ const first = await freshCtx(fix);
254
+ try {
255
+ const s1 = first.ctx.sessions.create(SessionId("resumed"), { meta: { cwd: WORK } });
256
+ send(s1, oneTurnLog());
257
+ await first.ctx.sessions.flush(s1);
258
+ } finally {
259
+ await first.fiber.dispose();
260
+ }
261
+
262
+ const second = await freshCtx(fix);
263
+ try {
264
+ const loaded = await readAll(second.ctx, SessionId("resumed"));
265
+ const s2 = second.ctx.sessions.create(SessionId("resumed"), {
266
+ seed: loaded.events,
267
+ meta: { cwd: WORK },
268
+ });
269
+ await second.ctx.sessions.flush(s2);
270
+ s2.append("turn/start", { turn: 2 });
271
+ s2.append("turn/end", { turn: 2, reason: { kind: "completed" } });
272
+ await second.ctx.sessions.flush(s2);
273
+
274
+ const reloaded = await readAll(second.ctx, SessionId("resumed"));
275
+
276
+ expect(reloaded.events.map((e) => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);
277
+ expect(reloaded.events[6]).toMatchObject({ type: "session/end-seed" });
278
+ } finally {
279
+ await second.fiber.dispose();
280
+ await fix.cleanup();
281
+ }
282
+ });
283
+
284
+ it("HMR: applying the plugin seeds existing live sessions", async () => {
285
+ const fix = await makeFixture();
286
+ const ctx = fix.createCtx() as CoordinatorContext;
287
+
288
+ const session = ctx.sessions.create(SessionId("pre-existing"), { meta: { cwd: WORK } });
289
+ session.append("turn/start", { turn: 1 });
290
+ session.append("user/message", userMessageOf("pre-existing-user", "hi"), {
291
+ surfaceOp: "append",
292
+ });
293
+ session.append("turn/end", { turn: 1, reason: { kind: "completed" } });
294
+
295
+ const fiber = await fix.mount(ctx);
296
+ try {
297
+ await ctx.sessions.flush(session);
298
+ const loaded = await readAll(ctx, SessionId("pre-existing"));
299
+ expect(loaded.events.length).toBeGreaterThanOrEqual(2);
300
+ } finally {
301
+ await fiber.dispose();
302
+ await fix.cleanup();
303
+ }
304
+ });
305
+
306
+ it("HMR: dispose drains remaining buffers", async () => {
307
+ const fix = await makeFixture();
308
+ const ctx = fix.createCtx() as CoordinatorContext;
309
+ const fiber = await fix.mount(ctx);
310
+ const session = ctx.sessions.create(SessionId("drain"), { meta: { cwd: WORK } });
311
+ session.append("turn/start", { turn: 1 });
312
+ session.append("user/message", userMessageOf("drain-user", "buffered"), {
313
+ surfaceOp: "append",
314
+ });
315
+ session.append("turn/end", { turn: 1, reason: { kind: "completed" } });
316
+ await fiber.dispose();
317
+
318
+ const second = await freshCtx(fix);
319
+ try {
320
+ const loaded = await readAll(second.ctx, SessionId("drain"));
321
+ expect(loaded.events.length).toBeGreaterThanOrEqual(2);
322
+ } finally {
323
+ await second.fiber.dispose();
324
+ await fix.cleanup();
325
+ }
326
+ });
327
+
328
+ it("a NEW live session colliding on a persisted id is rejected, not silently adopted", async () => {
329
+ const fix = await makeFixture();
330
+ const { ctx, fiber } = await freshCtx(fix);
331
+ try {
332
+ let first!: Session;
333
+ const firstFiber = await ctx.plugin(
334
+ Object.assign(
335
+ (inner: CoordinatorContext) => {
336
+ first = inner.sessions.create(SessionId("collide"), { meta: { cwd: WORK } });
337
+ },
338
+ { inject: ["sessions"] },
339
+ ),
340
+ );
341
+ send(first, oneTurnLog());
342
+ await ctx.sessions.flush(first);
343
+ await disposeFiber(firstFiber);
344
+
345
+ let second!: Session;
346
+ await ctx.plugin(
347
+ Object.assign(
348
+ (inner: CoordinatorContext) => {
349
+ second = inner.sessions.create(SessionId("collide"), { meta: { cwd: "/other" } });
350
+ },
351
+ { inject: ["sessions"] },
352
+ ),
353
+ );
354
+ await expect(ctx.sessions.flush(second)).rejects.toThrow(/different cwd/);
355
+ } finally {
356
+ await fiber.dispose();
357
+ await fix.cleanup();
358
+ }
359
+ });
360
+
361
+ it("an abandoned lazy session (never materialized) releases its id for reuse", async () => {
362
+ const fix = await makeFixture();
363
+ const { ctx, fiber } = await freshCtx(fix);
364
+ try {
365
+ let firstSession!: Session;
366
+ const firstFiber = await ctx.plugin(
367
+ Object.assign(
368
+ (inner: CoordinatorContext) => {
369
+ firstSession = inner.sessions.create(SessionId("abandoned"), { meta: { cwd: WORK } });
370
+ },
371
+ { inject: ["sessions"] },
372
+ ),
373
+ );
374
+ await ctx.sessions.flush(firstSession);
375
+ await disposeFiber(firstFiber);
376
+
377
+ let reuse!: Session;
378
+ await ctx.plugin(
379
+ Object.assign(
380
+ (inner: CoordinatorContext) => {
381
+ reuse = inner.sessions.create(SessionId("abandoned"), { meta: { cwd: WORK } });
382
+ },
383
+ { inject: ["sessions"] },
384
+ ),
385
+ );
386
+ await expect(ctx.sessions.flush(reuse)).resolves.toBe(true);
387
+ reuse.append("turn/start", { turn: 1 });
388
+ reuse.append("turn/end", { turn: 1, reason: { kind: "completed" } });
389
+ await ctx.sessions.flush(reuse);
390
+ const loaded = await readAll(ctx, SessionId("abandoned"));
391
+ expect(loaded.events.map((e) => e.seq)).toEqual([0, 1]);
392
+ } finally {
393
+ await fiber.dispose();
394
+ await fix.cleanup();
395
+ }
396
+ });
397
+
398
+ it("append adopts a storage-only session (fresh instance) and continues the seq", async () => {
399
+ const fix = await makeFixture();
400
+ const { ctx, fiber } = await freshCtx(fix);
401
+ try {
402
+ const m = meta("storage-only", WORK);
403
+ const handle = await ctx.sessionPersistence.create(m);
404
+ await handle.append(oneTurnLog());
405
+ await handle.close();
406
+
407
+ const writer = await ctx.sessionPersistence.open(SessionId("storage-only"), "write");
408
+ await writer.append([
409
+ { type: "turn/start", seq: SessionSeq(6), time: 7, data: { turn: 2 } },
410
+ {
411
+ type: "turn/end",
412
+ seq: SessionSeq(7),
413
+ time: 8,
414
+ data: { turn: 2, reason: { kind: "completed" } },
415
+ },
416
+ ]);
417
+ await writer.close();
418
+
419
+ const loaded = await readAll(ctx, SessionId("storage-only"));
420
+ expect(loaded.events.map((e) => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
421
+ } finally {
422
+ await fiber.dispose();
423
+ await fix.cleanup();
424
+ }
425
+ });
426
+
427
+ it("create rejects a duplicate id (in memory and on a persisted log)", async () => {
428
+ const fix = await makeFixture();
429
+ const { ctx, fiber } = await freshCtx(fix);
430
+ try {
431
+ const m = meta("dup-id", WORK);
432
+ const first = await ctx.sessionPersistence.create(m);
433
+ await expect(ctx.sessionPersistence.create(m)).rejects.toThrow(/already exists/);
434
+ await first.append(oneTurnLog());
435
+ await first.close();
436
+ await expect(ctx.sessionPersistence.create(m)).rejects.toThrow(/already exists/);
437
+ } finally {
438
+ await fiber.dispose();
439
+ await fix.cleanup();
440
+ }
441
+ });
442
+
443
+ it("round-trips a header with parentSession (fork lineage)", async () => {
444
+ const fix = await makeFixture();
445
+ const { ctx, fiber } = await freshCtx(fix);
446
+ try {
447
+ const m = meta("lineage", WORK);
448
+ const handle = await ctx.sessionPersistence.create({
449
+ ...m,
450
+ parentSession: SessionId("parent"),
451
+ });
452
+ await handle.append(oneTurnLog());
453
+ await handle.close();
454
+
455
+ const loaded = await readAll(ctx, SessionId("lineage"));
456
+ expect(loaded.meta.parentSession).toBe(SessionId("parent"));
457
+ } finally {
458
+ await fiber.dispose();
459
+ await fix.cleanup();
460
+ }
461
+ });
462
+
463
+ it("torn-tail: a never-committed tail is truncated by the write path", async () => {
464
+ const fix = await makeFixture();
465
+ if (fix.corruptTail === undefined) return;
466
+ const { ctx, fiber } = await freshCtx(fix);
467
+ try {
468
+ const m = meta("torn", WORK);
469
+ const creator = await ctx.sessionPersistence.create(m);
470
+ await creator.append(oneTurnLog());
471
+ await creator.close();
472
+ await fix.corruptTail(SessionId("torn"), WORK);
473
+
474
+ const reader = await ctx.sessionPersistence.open(SessionId("torn"), "read");
475
+ expect((await reader.read()).events).toEqual(oneTurnLog());
476
+ await reader.close();
477
+
478
+ const writer = await ctx.sessionPersistence.open(SessionId("torn"), "write");
479
+ await writer.append([
480
+ { type: "turn/start", seq: SessionSeq(6), time: 7, data: { turn: 2 } },
481
+ {
482
+ type: "turn/end",
483
+ seq: SessionSeq(7),
484
+ time: 8,
485
+ data: { turn: 2, reason: { kind: "completed" } },
486
+ },
487
+ ]);
488
+ expect((await writer.read()).events.map((e) => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
489
+ await writer.close();
490
+ } finally {
491
+ await fiber.dispose();
492
+ await fix.cleanup();
493
+ }
494
+ });
495
+ });
496
+ }
@@ -0,0 +1,25 @@
1
+ // 会话域的**测试支撑**出口(`@morlay/dsh-session/testing`):造数据的 fixtures、契约套件、最小装配。
2
+ //
3
+ // 下游域的 spec 从这里取,别在自己的 `__tests__/support` 里再造一份同形状的数据——那正是
4
+ // 「同一个 fixture 只在一个域存在」这条判据要挡的东西。
5
+ //
6
+ // **显式清单**(不用 `export *`):测试面要能被一眼读完,也避免与别处的同名符号互相遮蔽。
7
+ export {
8
+ appendLog,
9
+ assistantMessage,
10
+ eventOf,
11
+ headerEvent,
12
+ inboxTurnLog,
13
+ meta,
14
+ oneTurnLog,
15
+ oneTurnLogStepFirst,
16
+ secondTurn,
17
+ titleEvent,
18
+ turnLog,
19
+ twoTurnLog,
20
+ userMessage,
21
+ } from "./log.ts";
22
+ export { runCoordinatorContract } from "./coordinator-contract.ts";
23
+ export type { CoordinatorContext, CoordinatorFixture } from "./coordinator-contract.ts";
24
+ export { createSessionContext } from "./context.ts";
25
+ export type { SessionTestContext } from "./context.ts";