session.spec.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. import { describe, expect, expectTypeOf, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SESSION_FORMAT_VERSION, Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  5. import type { CreateSessionOptions, SessionEventType, SessionHeader, SessionSurface, TodoItem } from '@deepseek-ai/dsh-session'
  6. describe('Session', () => {
  7. it('exposes one stable readonly surface view', () => {
  8. const session = new Session(SessionId('surface-view'))
  9. const surface = session.surface
  10. expectTypeOf(surface).toEqualTypeOf<SessionSurface>()
  11. expect(surface).toBe(session.surface)
  12. })
  13. it('derives message history from the event log', () => {
  14. const session = new Session(SessionId('s1'))
  15. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  16. session.append('user/message', { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  17. session.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hi' } })
  18. session.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' },
  19. turn: 1, step: 1,
  20. content: [
  21. { type: 'text', text: 'let me check' },
  22. { type: 'tool-call', id: CallId('c1'), name: 'echo', arguments: '{}' },
  23. ],
  24. }, { surfaceOp: 'append' })
  25. session.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  26. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  27. const messages = session.deriveMessages()
  28. expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user'])
  29. // raw chunks must NOT appear in derived history
  30. expect(messages[1]!.content).toHaveLength(2)
  31. expect(messages[2]!.content[0]).toMatchObject({ type: 'tool-result', toolCallId: CallId('c1') })
  32. })
  33. it('accepts and round-trips a max-tokens turn/end reason', () => {
  34. // The max-tokens TurnEndReason variant carries no extra data, so it must
  35. // append and persist like any other reason (JSON-serializable, no fields).
  36. const session = new Session(SessionId('s1'))
  37. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  38. session.append('turn/end', { turn: 1, reason: { kind: 'max-tokens' } })
  39. const turnEnd = session.events.findLast(e => e.type === 'turn/end')!
  40. expect(turnEnd.data.reason).toEqual({ kind: 'max-tokens' })
  41. // survives a structuredClone (the persistence-serialization boundary)
  42. expect(structuredClone(turnEnd.data.reason)).toEqual({ kind: 'max-tokens' })
  43. })
  44. it('renders context and steering messages as plain user content', () => {
  45. const session = new Session(SessionId('s2'))
  46. session.append('context/message', {
  47. content: [{ type: 'text', text: 'file changed: a.ts' }],
  48. source: { kind: 'plugin', plugin: 'watcher' },
  49. }, { surfaceOp: 'append' })
  50. session.append('steering/message', {
  51. turn: 1,
  52. content: [{ type: 'text', text: 'focus on tests' }],
  53. source: { kind: 'user' },
  54. }, { surfaceOp: 'append' })
  55. const [contextMessage, steeringMessage] = session.deriveMessages()
  56. expect(contextMessage!.role).toBe('user')
  57. expect(contextMessage!.content).toEqual([{ type: 'text', text: 'file changed: a.ts' }])
  58. expect(steeringMessage!.role).toBe('user')
  59. expect(steeringMessage!.content).toEqual([{ type: 'text', text: 'focus on tests' }])
  60. })
  61. it('keeps context meta durable in the event while hiding it from the projection', () => {
  62. const session = new Session(SessionId('s2-raw'))
  63. const meta = {
  64. kind: 'workspace-instructions',
  65. version: 1,
  66. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  67. }
  68. session.append('context/message', {
  69. content: [{ type: 'text', text: '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>' }],
  70. source: { kind: 'plugin', plugin: 'workspace-context' },
  71. meta,
  72. }, { surfaceOp: 'append' })
  73. expect(session.deriveMessages()).toEqual([{
  74. role: 'user',
  75. content: [{ type: 'text', text: '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>' }],
  76. }])
  77. const event = session.events[0]
  78. expect(event?.type === 'context/message' && event.data.meta).toEqual(meta)
  79. })
  80. it('replays identically from a seeded event log', () => {
  81. const original = new Session(SessionId('s3'))
  82. original.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  83. original.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  84. original.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'a' }] }, { surfaceOp: 'append' })
  85. original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  86. const replayed = new Session(SessionId('s3-replay'), [...original.events])
  87. expect(replayed.deriveMessages()).toEqual(original.deriveMessages())
  88. expect(replayed.seq).toBe(original.seq)
  89. })
  90. it('rejects pre-provider request headers and assistant messages on seed/load', () => {
  91. const requestHeader = {
  92. type: 'request/header', seq: 0, time: 1,
  93. data: { header: { config: { model: 'old-model' } }, reason: 'initial' },
  94. } as unknown as SessionEvent
  95. expect(() => new Session(SessionId('old-header'), [requestHeader]))
  96. .toThrow('seed request/header at index 0 lacks provider/model')
  97. const assistantMessage = {
  98. type: 'assistant/message', seq: 0, time: 1,
  99. data: { turn: 1, step: 1, content: [{ type: 'text', text: 'old' }] },
  100. surfaceOp: 'append',
  101. } as unknown as SessionEvent
  102. expect(() => new Session(SessionId('old-assistant'), [assistantMessage]))
  103. .toThrow('seed assistant/message at index 0 lacks provider/model provenance')
  104. const malformedHeader = {
  105. type: 'request/header', seq: 0, time: 1,
  106. data: { header: 'old-header' },
  107. } as unknown as SessionEvent
  108. expect(() => new Session(SessionId('malformed-header'), [malformedHeader]))
  109. .toThrow('seed request/header at index 0 lacks provider/model')
  110. const unrelatedPrimitiveData = {
  111. type: 'plugin/event', seq: 0, time: 1, data: null,
  112. } as unknown as SessionEvent
  113. expect(new Session(SessionId('primitive-plugin-data'), [unrelatedPrimitiveData]).events)
  114. .toEqual([unrelatedPrimitiveData])
  115. })
  116. it('isolates the log from mutation through a derived message (append-only contract)', () => {
  117. const session = new Session(SessionId('s4'))
  118. session.append('user/message', { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  119. session.append('tool/result', {
  120. turn: 1, step: 1, callId: CallId('c1'),
  121. content: [{ type: 'text', text: 'tool out' }], isError: false,
  122. }, { surfaceOp: 'append' })
  123. const before = structuredClone(session.events)
  124. // A misbehaving consumer tries to mutate the messages it was handed.
  125. const messages = session.deriveMessages()
  126. const userBlock = messages[0]!.content[0]!
  127. expect(() => { if (userBlock.type === 'text') userBlock.text = 'HACKED' }).toThrow(TypeError)
  128. const toolBlock = messages[1]!.content[0]!
  129. expect(() => {
  130. if (toolBlock.type === 'tool-result') toolBlock.content.push({ type: 'text', text: 'injected' })
  131. }).toThrow(TypeError)
  132. expect(() => { messages[0]!.content.push({ type: 'text', text: 'extra' }) }).toThrow(TypeError)
  133. // The returned ARRAY is the caller's own snapshot, though — reordering it
  134. // is the caller's business and never reaches the cache or the log.
  135. messages.reverse()
  136. // The log is unchanged: deep-equal to the snapshot taken before mutation.
  137. expect(session.events).toEqual(before)
  138. // And a fresh derivation still reflects the original content and order.
  139. expect(session.deriveMessages()[0]!.content).toEqual([{ type: 'text', text: 'original' }])
  140. })
  141. it('rejects non-JSON-serializable event data at the source (incl. sparse arrays)', () => {
  142. const session = new Session(SessionId('s5'))
  143. const bad = (extra: unknown) => () => session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, extra } as never, { surfaceOp: 'append' })
  144. expect(bad(1n)).toThrow(/non-JSON-serializable/)
  145. expect(bad(() => 0)).toThrow(/non-JSON-serializable/)
  146. expect(bad(Symbol('s'))).toThrow(/non-JSON-serializable/)
  147. expect(bad(new Map())).toThrow(/non-JSON-serializable/)
  148. expect(bad(undefined)).toThrow(/non-JSON-serializable/)
  149. expect(bad(Infinity)).toThrow(/non-JSON-serializable/)
  150. // A sparse array: `every` skips the hole but JSON.stringify writes it null.
  151. // Build the hole without a sparse literal or `delete` (both linted).
  152. const sparse: unknown[] = Array(3)
  153. sparse[0] = 1
  154. sparse[2] = 3 // index 1 stays a hole
  155. expect(bad(sparse)).toThrow(/non-JSON-serializable/)
  156. // A DENSE array carrying a non-serializable element is rejected too.
  157. expect(bad([1, 2n, 3])).toThrow(/non-JSON-serializable/)
  158. // A nested non-serializable value (inside a plain object) is rejected.
  159. expect(bad({ nested: { deep: () => 0 } })).toThrow(/non-JSON-serializable/)
  160. // A circular reference is rejected (the seen-set guard, not a stack blow-up).
  161. const cyclic: Record<string, unknown> = { a: 1 }
  162. cyclic['self'] = cyclic
  163. expect(bad(cyclic)).toThrow(/non-JSON-serializable/)
  164. // The rejected appends never entered the log.
  165. expect(session.events).toHaveLength(0)
  166. })
  167. it('rejects a surface-eligible append with no surfaceOp marker (runtime guard for the union-widening loophole)', () => {
  168. const session = new Session(SessionId('s5b'))
  169. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  170. // A widened SessionEventType bypasses the overload's conditional requirement,
  171. // so the runtime guard must still reject the missing surface marker.
  172. const widenedType = 'user/message' as SessionEventType
  173. expect(() => session.append(widenedType, { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }))
  174. .toThrow(/surface-eligible and requires a surfaceOp marker/)
  175. // The rejected append never entered the log (only turn/start is present).
  176. expect(session.events).toHaveLength(1)
  177. })
  178. it('accepts dense arrays and nested plain objects', () => {
  179. const session = new Session(SessionId('s6'))
  180. expect(() => session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, extra: [1, 2, [3, { a: null, b: true }]] } as never, { surfaceOp: 'append' })).not.toThrow()
  181. expect(session.events).toHaveLength(1)
  182. })
  183. it('validates seed events: rejects a non-JSON-serializable seed', () => {
  184. // A replay/fork seed must satisfy the SAME invariant as Session.append, or
  185. // it builds a live log no backend can persist.
  186. const badSeed = [
  187. { type: 'user/message' as const, seq: 0, time: 1, data: { content: [{ type: 'text' as const, text: 'x' }], source: { kind: 'user' as const }, bad: 1n } },
  188. ] as unknown as SessionEvent[]
  189. expect(() => new Session(SessionId('seed-bad'), badSeed)).toThrow(/losslessly JSON-serializable/)
  190. })
  191. it('validates seed events: rejects a non-contiguous seq', () => {
  192. const gapSeed = [
  193. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  194. { type: 'turn/end' as const, seq: 5, time: 2, data: { turn: 1, reason: { kind: 'completed' as const } } }, // gap: expected seq 1
  195. ] as SessionEvent[]
  196. expect(() => new Session(SessionId('seed-gap'), gapSeed)).toThrow(/contiguous|seq/)
  197. })
  198. it('validates seed events: rejects a surface-eligible event missing its surfaceOp marker', () => {
  199. // A surface-eligible event (user/message) with no surfaceOp would load fine
  200. // but vanish from deriveMessages() (the surface is the sole derivation path),
  201. // so a resume/fork would silently lose history. append() forbids this at
  202. // compile time; a raw seed must be rejected at runtime to match.
  203. const markerlessSeed = [
  204. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  205. { type: 'user/message' as const, seq: 1, time: 2, data: { content: [{ type: 'text' as const, text: 'hi' }], source: { kind: 'user' as const } } },
  206. { type: 'turn/end' as const, seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' as const } } },
  207. ] as SessionEvent[]
  208. expect(() => new Session(SessionId('seed-no-marker'), markerlessSeed)).toThrow(/requires a surfaceOp marker/)
  209. })
  210. it('accepts a well-formed contiguous serializable seed', () => {
  211. const goodSeed = [
  212. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  213. { type: 'user/message' as const, seq: 1, time: 2, data: { content: [{ type: 'text' as const, text: 'hi' }], source: { kind: 'user' as const } }, surfaceOp: 'append' as const },
  214. { type: 'turn/end' as const, seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' as const } } },
  215. ] as SessionEvent[]
  216. const session = new Session(SessionId('seed-ok'), goodSeed)
  217. expect(session.events).toHaveLength(3)
  218. })
  219. it('reads each seed array entry once so validation and storage use the same event', () => {
  220. const accepted = {
  221. type: 'turn/start' as const,
  222. seq: 0,
  223. time: 1,
  224. data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } },
  225. }
  226. const drifted = { ...accepted, seq: 99, data: { invalid: 1n } }
  227. let reads = 0
  228. const seed = new Array<SessionEvent>(1)
  229. Object.defineProperty(seed, 0, {
  230. enumerable: true,
  231. get: () => {
  232. reads += 1
  233. return reads === 1 ? accepted : drifted
  234. },
  235. })
  236. const session = new Session(SessionId('seed-entry-snapshot'), seed)
  237. expect(reads).toBe(1)
  238. expect(session.events).toEqual([accepted])
  239. })
  240. it('reads a nested seed-data getter once and stores its first JSON value', () => {
  241. let reads = 0
  242. const data = Object.defineProperty({}, 'value', {
  243. enumerable: true,
  244. get: () => {
  245. reads += 1
  246. return reads === 1 ? 'accepted' : 1n
  247. },
  248. })
  249. const seed = [{ type: 'test/unstable', seq: 0, time: 1, data }] as unknown as SessionEvent[]
  250. const session = new Session(SessionId('seed-nested-drift'), seed)
  251. expect(reads).toBe(1)
  252. expect(session.events[0]!.data).toEqual({ value: 'accepted' })
  253. })
  254. it('rejects non-JSON surface metadata in a seed event', () => {
  255. const seed = [{
  256. type: 'user/message',
  257. seq: 0,
  258. time: 1,
  259. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  260. surfaceOp: { op: 'replace', start: 1n, end: 2 },
  261. }] as unknown as SessionEvent[]
  262. expect(() => new Session(SessionId('seed-bad-metadata'), seed))
  263. .toThrow(/losslessly JSON-serializable/)
  264. })
  265. it('rejects exotic seed metadata before cloning can erase its prototype', () => {
  266. class ReplaceOp {
  267. readonly op = 'replace' as const
  268. readonly start = 0
  269. readonly end = 0
  270. }
  271. const seed = [{
  272. type: 'user/message',
  273. seq: 0,
  274. time: 1,
  275. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  276. surfaceOp: new ReplaceOp(),
  277. }] as unknown as SessionEvent[]
  278. expect(() => new Session(SessionId('seed-exotic-metadata'), seed))
  279. .toThrow(/losslessly JSON-serializable/)
  280. })
  281. it('rejects an exotic seed event shell before spreading erases its prototype', () => {
  282. class SeedEvent {
  283. readonly type = 'turn/start' as const
  284. readonly seq = 0
  285. readonly time = 1
  286. readonly data = { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } }
  287. }
  288. const seed: SessionEvent[] = [new SeedEvent()]
  289. expect(() => new Session(SessionId('seed-exotic-shell'), seed))
  290. .toThrow(/not losslessly JSON-serializable/)
  291. })
  292. it('accepts a null-prototype seed event shell as a plain JSON record', () => {
  293. const event = Object.assign(Object.create(null) as Record<string, unknown>, {
  294. type: 'turn/start' as const,
  295. seq: 0,
  296. time: 1,
  297. data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } },
  298. }) as unknown as SessionEvent
  299. const session = new Session(SessionId('seed-null-prototype'), [event])
  300. expect(session.events).toEqual([{ ...event }])
  301. })
  302. it('reads a nested seed-metadata getter once and stores its first JSON value', () => {
  303. let reads = 0
  304. const surfaceOp = Object.defineProperty({ op: 'replace', end: 0 }, 'start', {
  305. enumerable: true,
  306. get: () => {
  307. reads += 1
  308. return reads === 1 ? 0 : 1n
  309. },
  310. })
  311. const seed = [{
  312. type: 'user/message',
  313. seq: 0,
  314. time: 1,
  315. data: { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  316. surfaceOp: 'append',
  317. }, {
  318. type: 'user/message',
  319. seq: 1,
  320. time: 2,
  321. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  322. surfaceOp,
  323. sourceEventSeqs: [0],
  324. }] as unknown as SessionEvent[]
  325. const session = new Session(SessionId('seed-unstable-metadata'), seed)
  326. const event = session.events[1]!
  327. if (event.type !== 'user/message') throw new Error('test fixture must remain a user/message')
  328. expect(reads).toBe(1)
  329. expect(event.surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  330. })
  331. it.each([
  332. ['an Error', new Error('validator failed'), 'validator failed'],
  333. ['a non-Error value', 'validator failed', 'invalid surface metadata'],
  334. ] as const)('adds seed context when surface validation throws %s', (_name, failure, expected) => {
  335. const originalHasOwn = Object.hasOwn
  336. const hasOwn = vi.spyOn(Object, 'hasOwn').mockImplementation((object: object, property: PropertyKey): boolean => {
  337. if ((object as Record<string, unknown>)['op'] === 'replace') throw failure
  338. return originalHasOwn(object, property)
  339. })
  340. const seed = [{
  341. type: 'user/message',
  342. seq: 0,
  343. time: 1,
  344. data: { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  345. surfaceOp: 'append',
  346. }, {
  347. type: 'user/message',
  348. seq: 1,
  349. time: 2,
  350. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  351. surfaceOp: { op: 'replace', start: 0, end: 0 },
  352. sourceEventSeqs: [0],
  353. }] as unknown as SessionEvent[]
  354. try {
  355. expect(() => new Session(SessionId('seed-non-error-metadata-failure'), seed))
  356. .toThrow(`invalid seed event at index 1: ${expected}`)
  357. } finally {
  358. hasOwn.mockRestore()
  359. }
  360. })
  361. it('snapshots the seed: mutating the original after construction does not affect session.events', () => {
  362. const seed = [
  363. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  364. { type: 'user/message' as const, seq: 1, time: 2, data: { content: [{ type: 'text' as const, text: 'original' }], source: { kind: 'user' as const } }, surfaceOp: 'append' as const },
  365. { type: 'turn/end' as const, seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' as const } } },
  366. ] as SessionEvent[]
  367. const session = new Session(SessionId('seed-snapshot'), seed)
  368. // Mutate the ORIGINAL seed objects after construction: a shared reference
  369. // would let this rewrite the forked log (or reintroduce non-serializable
  370. // data past validation). The snapshot must shield session.events.
  371. const um = seed[1]!
  372. ;(um.data as { content: { type: 'text'; text: string }[] }).content[0]!.text = 'HACKED'
  373. ;(um.data as Record<string, unknown>)['injected'] = 1n // would have failed validation
  374. const logged = session.events[1]!
  375. expect(logged.type === 'user/message' && (logged.data.content[0] as { text: string }).text).toBe('original')
  376. expect((logged.data as Record<string, unknown>)['injected']).toBeUndefined()
  377. })
  378. it('snapshots append data: mutating the passed object after append does not affect session.events', () => {
  379. const session = new Session(SessionId('append-snapshot'))
  380. const data = { content: [{ type: 'text' as const, text: 'original' }], source: { kind: 'user' as const } }
  381. const event = session.append('user/message', data, { surfaceOp: 'append' })
  382. // Mutate the caller's object after append returns. A shared reference would
  383. // make session.events diverge from the value that passed validation.
  384. data.content[0]!.text = 'HACKED'
  385. ;(data as Record<string, unknown>)['injected'] = 1n
  386. const logged = session.events[0]!
  387. expect(logged.type === 'user/message' && (logged.data.content[0] as { text: string }).text).toBe('original')
  388. expect((logged.data as Record<string, unknown>)['injected']).toBeUndefined()
  389. // The returned event carries the same snapshot, not the caller's input.
  390. expect((event.data.content[0] as { text: string }).text).toBe('original')
  391. })
  392. it('reads a nested append-data getter once and stores its first JSON value', () => {
  393. const session = new Session(SessionId('append-nested-drift'))
  394. let reads = 0
  395. const data = Object.defineProperty({}, 'value', {
  396. enumerable: true,
  397. get: () => {
  398. reads += 1
  399. return reads === 1 ? 'accepted' : 1n
  400. },
  401. })
  402. const event = session.append('todo/write', data as never)
  403. expect(reads).toBe(1)
  404. expect(event.data).toEqual({ value: 'accepted' })
  405. expect(session.events).toEqual([event])
  406. })
  407. it('rejects non-JSON surface metadata before appending the event', () => {
  408. const session = new Session(SessionId('append-bad-metadata'))
  409. expect(() => session.append(
  410. 'user/message',
  411. { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  412. { surfaceOp: { op: 'replace', start: 1n, end: 2 } } as never,
  413. )).toThrow(/non-JSON-serializable surface metadata/)
  414. expect(session.events).toEqual([])
  415. })
  416. it('rejects exotic surface metadata before cloning can erase its prototype', () => {
  417. class ReplaceOp {
  418. readonly op = 'replace' as const
  419. readonly start = 0
  420. readonly end = 0
  421. }
  422. const session = new Session(SessionId('append-exotic-metadata'))
  423. expect(() => session.append(
  424. 'user/message',
  425. { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  426. { surfaceOp: new ReplaceOp() },
  427. )).toThrow(/non-JSON-serializable surface metadata/)
  428. expect(session.events).toEqual([])
  429. })
  430. it('reads a nested append-metadata getter once and stores its first JSON value', () => {
  431. const session = new Session(SessionId('append-unstable-metadata'))
  432. const source = session.append(
  433. 'user/message',
  434. { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  435. { surfaceOp: 'append' },
  436. )
  437. let reads = 0
  438. const surfaceOp = Object.defineProperty({ op: 'replace', end: 0 }, 'start', {
  439. enumerable: true,
  440. get: () => {
  441. reads += 1
  442. return reads === 1 ? 0 : 1n
  443. },
  444. })
  445. const event = session.append(
  446. 'user/message',
  447. { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  448. { surfaceOp, sourceEventSeqs: [0] } as never,
  449. )
  450. expect(reads).toBe(1)
  451. expect(event.surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  452. expect(session.events).toEqual([source, event])
  453. })
  454. it('rejects invalid plain surface metadata shapes at append', () => {
  455. const session = new Session(SessionId('append-invalid-surface-shape'))
  456. const appendRaw = session.append.bind(session) as unknown as (
  457. type: SessionEventType,
  458. data: unknown,
  459. opts?: unknown,
  460. ) => SessionEvent
  461. const data = { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }
  462. expect(() => appendRaw('user/message', data, { surfaceOp: 'invalid' }))
  463. .toThrow(/invalid surfaceOp/)
  464. expect(() => appendRaw('user/message', data, {
  465. surfaceOp: { op: 'replace', start: -1, end: 0 },
  466. })).toThrow(/invalid replace surfaceOp/)
  467. expect(() => appendRaw('user/message', data, {
  468. surfaceOp: 'append',
  469. sourceEventSeqs: [0, -1],
  470. })).toThrow(/non-negative safe integers/)
  471. expect(session.events).toEqual([])
  472. })
  473. it('rejects surface metadata on non-surface append and seed events', () => {
  474. const session = new Session(SessionId('non-surface-metadata'))
  475. const appendRaw = session.append.bind(session) as unknown as (
  476. type: SessionEventType,
  477. data: unknown,
  478. opts?: unknown,
  479. ) => SessionEvent
  480. expect(() => appendRaw(
  481. 'turn/start',
  482. { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  483. { surfaceOp: 'append' },
  484. )).toThrow(/not surface-eligible and cannot carry surfaceOp/)
  485. expect(() => new Session(SessionId('non-surface-metadata-seed'), [{
  486. type: 'turn/start',
  487. seq: 0,
  488. time: 1,
  489. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  490. surfaceOp: 'append',
  491. } as unknown as SessionEvent])).toThrow(/invalid seed event.*not surface-eligible/)
  492. expect(session.events).toEqual([])
  493. })
  494. it('deep-freezes seeded and appended event snapshots', () => {
  495. const seeded = new Session(SessionId('seed-frozen'), [{
  496. type: 'turn/start',
  497. seq: 0,
  498. time: 1,
  499. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  500. }])
  501. const seededEvent = seeded.events[0]!
  502. if (seededEvent.type !== 'turn/start') throw new Error('test fixture must remain a turn/start')
  503. expect(Object.isFrozen(seededEvent)).toBe(true)
  504. expect(Object.isFrozen(seededEvent.data)).toBe(true)
  505. expect(Object.isFrozen(seededEvent.data.trigger)).toBe(true)
  506. expect(() => { seededEvent.data.turn = 99 }).toThrow(TypeError)
  507. const appended = new Session(SessionId('append-frozen'))
  508. const appendedEvent = appended.append('todo/write', {
  509. todos: [{ content: 'first', status: 'pending' }],
  510. })
  511. expect(Object.isFrozen(appendedEvent)).toBe(true)
  512. expect(Object.isFrozen(appendedEvent.data)).toBe(true)
  513. expect(Object.isFrozen(appendedEvent.data.todos)).toBe(true)
  514. expect(Object.isFrozen(appendedEvent.data.todos[0])).toBe(true)
  515. expect(() => { appendedEvent.data.todos[0]!.content = 'mutated' }).toThrow(TypeError)
  516. })
  517. it('returns cached frozen event-array snapshots that do not grow after append', () => {
  518. const session = new Session(SessionId('events-snapshot'))
  519. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  520. const before = session.events
  521. const beforeEvent = before[0]!
  522. if (beforeEvent.type !== 'turn/start') throw new Error('test fixture must remain a turn/start')
  523. expect(session.events).toBe(before)
  524. expect(Object.isFrozen(before)).toBe(true)
  525. expect(() => { (before as SessionEvent[]).push(beforeEvent) }).toThrow(TypeError)
  526. expect(() => { beforeEvent.data.turn = 99 }).toThrow(TypeError)
  527. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  528. const after = session.events
  529. expect(before).toHaveLength(1)
  530. expect(after).toHaveLength(2)
  531. expect(after).not.toBe(before)
  532. expect(session.events).toBe(after)
  533. })
  534. it('detaches and freezes an explicitly supplied session header', () => {
  535. const input = {
  536. version: SESSION_FORMAT_VERSION,
  537. id: SessionId('header-owned'),
  538. createdAt: 123,
  539. cwd: '/accepted',
  540. parentSession: SessionId('parent'),
  541. seedLength: 2,
  542. }
  543. const session = new Session(SessionId('header-owned'), undefined, input)
  544. input.cwd = '/caller-mutated'
  545. expect(session.header).toEqual({
  546. version: SESSION_FORMAT_VERSION,
  547. id: 'header-owned',
  548. createdAt: 123,
  549. cwd: '/accepted',
  550. parentSession: 'parent',
  551. seedLength: 2,
  552. })
  553. expect(session.header).not.toBe(input)
  554. expect(Object.isFrozen(session.header)).toBe(true)
  555. expect(Reflect.set(session.header, 'cwd', '/published-mutated')).toBe(false)
  556. expect(session.id).toBe('header-owned')
  557. expect(session.header.cwd).toBe('/accepted')
  558. })
  559. it('rejects an exotic, non-JSON, or mismatched supplied header', () => {
  560. class ExoticHeader implements SessionHeader {
  561. readonly version = SESSION_FORMAT_VERSION
  562. readonly id = SessionId('header-invalid')
  563. readonly createdAt = 123
  564. }
  565. expect(() => new Session(SessionId('header-invalid'), undefined, new ExoticHeader()))
  566. .toThrow(/not losslessly JSON-serializable/)
  567. expect(() => new Session(SessionId('header-invalid'), undefined, {
  568. version: SESSION_FORMAT_VERSION,
  569. id: SessionId('header-invalid'),
  570. createdAt: 123,
  571. parentSession: 1n,
  572. } as unknown as SessionHeader)).toThrow(/not losslessly JSON-serializable/)
  573. expect(() => new Session(SessionId('header-invalid'), undefined, {
  574. version: SESSION_FORMAT_VERSION,
  575. id: SessionId('other'),
  576. createdAt: 123,
  577. })).toThrow(/does not match session id/)
  578. })
  579. it('rejects invalid scalar fields in an explicitly supplied header', () => {
  580. const base = {
  581. version: SESSION_FORMAT_VERSION,
  582. id: SessionId('header-shape'),
  583. createdAt: 123,
  584. }
  585. const cases: Array<{ header: unknown; error: RegExp }> = [
  586. { header: 1, error: /not a plain JSON record/ },
  587. { header: null, error: /not a plain JSON record/ },
  588. { header: { ...base, version: 1 }, error: /header version/ },
  589. { header: { ...base, createdAt: '123' }, error: /createdAt must be a finite number/ },
  590. { header: { ...base, cwd: 1 }, error: /header cwd must be a string/ },
  591. { header: { ...base, cwd: 'relative' }, error: /header cwd must be an absolute path/ },
  592. { header: { ...base, parentSession: 1 }, error: /header parentSession must be a string/ },
  593. { header: { ...base, seedLength: '1' }, error: /seedLength must be a non-negative safe integer/ },
  594. { header: { ...base, seedLength: 0.5 }, error: /seedLength must be a non-negative safe integer/ },
  595. { header: { ...base, seedLength: -1 }, error: /seedLength must be a non-negative safe integer/ },
  596. ]
  597. for (const { header, error } of cases) {
  598. expect(() => new Session(SessionId('header-shape'), undefined, header as SessionHeader)).toThrow(error)
  599. }
  600. })
  601. it('rejects seed records with invalid fixed-envelope fields', () => {
  602. const base = {
  603. type: 'turn/start',
  604. seq: 0,
  605. time: 1,
  606. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  607. }
  608. const cases: unknown[] = [
  609. { ...base, extra: true },
  610. { ...base, type: 1 },
  611. { ...base, seq: '0' },
  612. { ...base, seq: 0.5 },
  613. { ...base, seq: -1 },
  614. { ...base, time: '1' },
  615. { ...base, time: 0.5 },
  616. { ...base, time: -1 },
  617. { type: base.type, seq: base.seq, time: base.time },
  618. ]
  619. for (const [index, event] of cases.entries()) {
  620. expect(() => new Session(SessionId(`bad-envelope-${index}`), [event as SessionEvent]))
  621. .toThrow(/invalid event envelope/)
  622. }
  623. })
  624. })
  625. describe('SessionStore', () => {
  626. it('creates sessions, emits session/created and session/event', async () => {
  627. const ctx = new Context()
  628. await ctx.plugin(SessionStore)
  629. const created: Session[] = []
  630. const events: [Session, SessionEvent][] = []
  631. ctx.on('session/created', session => void created.push(session))
  632. ctx.on('session/event', (session, event) => void events.push([session, event]))
  633. const session = ctx.sessions.create()
  634. expect(created).toEqual([session])
  635. // The store-owned append publication hooks are module-private. A JavaScript caller
  636. // may create an unrelated property with the old implementation's name,
  637. // but cannot suppress the durable event feed.
  638. expect(Reflect.set(session, 'onAppend', undefined)).toBe(true)
  639. session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  640. expect(events).toHaveLength(1)
  641. expect(events[0]![0]).toBe(session)
  642. expect(events[0]![1].type).toBe('user/message')
  643. expect(ctx.sessions.get(session.id)).toBe(session)
  644. expect(ctx.sessions.list()).toEqual([session])
  645. })
  646. it('rejects duplicate ids and supports seeding', async () => {
  647. const ctx = new Context()
  648. await ctx.plugin(SessionStore)
  649. const a = ctx.sessions.create(SessionId('fixed'))
  650. expect(() => ctx.sessions.create(SessionId('fixed'))).toThrow('already exists')
  651. a.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  652. const forked = ctx.sessions.create(SessionId('fork'), { seed: [...a.events] })
  653. expect(forked.deriveMessages()).toEqual(a.deriveMessages())
  654. })
  655. it('enter() rejects a stale prepared session whose id is already live (no overwrite)', async () => {
  656. // A stale prepared object must not replace the live same-id entry; its later
  657. // detach would otherwise remove the wrong session.
  658. const ctx = new Context()
  659. await ctx.plugin(SessionStore)
  660. const stale = ctx.sessions.prepare(SessionId('racy'))
  661. const live = ctx.sessions.create(SessionId('racy'))
  662. expect(() => ctx.sessions.enter(stale)).toThrow(/already exists/)
  663. // The live session is intact and still the store entry.
  664. expect(ctx.sessions.get(SessionId('racy'))).toBe(live)
  665. })
  666. it('prepare() + enter() + announce() register a session and emit session/created', async () => {
  667. const ctx = new Context()
  668. await ctx.plugin(SessionStore)
  669. const created: Session[] = []
  670. ctx.on('session/created', session => void created.push(session))
  671. const session = ctx.sessions.prepare(SessionId('lifecycle'))
  672. // prepare alone does NOT enter the store.
  673. expect(ctx.sessions.get(SessionId('lifecycle'))).toBeUndefined()
  674. const detach = ctx.sessions.enter(session)
  675. expect(ctx.sessions.get(SessionId('lifecycle'))).toBe(session)
  676. // enter does NOT announce.
  677. expect(created).toEqual([])
  678. ctx.sessions.announce(session)
  679. expect(created).toEqual([session])
  680. // The detach disposer removes the entry + stops notification.
  681. detach()
  682. detach() // idempotent: cannot disturb a later same-id lifecycle
  683. expect(ctx.sessions.get(SessionId('lifecycle'))).toBeUndefined()
  684. })
  685. it('prevents simultaneous attachment of one session object to two stores', async () => {
  686. const firstCtx = new Context()
  687. const secondCtx = new Context()
  688. await firstCtx.plugin(SessionStore)
  689. await secondCtx.plugin(SessionStore)
  690. const session = new Session(SessionId('owned-key'))
  691. const detachFirst = firstCtx.sessions.enter(session)
  692. expect(() => secondCtx.sessions.enter(session)).toThrow(/already attached to a store/)
  693. expect(firstCtx.sessions.get(SessionId('owned-key'))).toBe(session)
  694. detachFirst()
  695. expect(firstCtx.sessions.get(SessionId('owned-key'))).toBeUndefined()
  696. const detachSecond = secondCtx.sessions.enter(session)
  697. expect(secondCtx.sessions.get(SessionId('owned-key'))).toBe(session)
  698. detachSecond()
  699. })
  700. it('rejects direct and reentrant repeat announcements to preserve one lifecycle pair', async () => {
  701. const ctx = new Context()
  702. await ctx.plugin(SessionStore)
  703. let created = 0
  704. let disposed = 0
  705. let reentrantError = ''
  706. ctx.on('session/created', (session) => {
  707. created += 1
  708. try {
  709. ctx.sessions.announce(session)
  710. } catch (error: unknown) {
  711. reentrantError = String(error)
  712. }
  713. })
  714. ctx.on('session/disposed', () => { disposed += 1 })
  715. const session = ctx.sessions.prepare(SessionId('once'))
  716. const detach = ctx.sessions.enter(session)
  717. ctx.sessions.announce(session)
  718. expect(reentrantError).toMatch(/already announced/)
  719. expect(() => { ctx.sessions.announce(session) }).toThrow(/already announced/)
  720. detach()
  721. expect({ created, disposed }).toEqual({ created: 1, disposed: 1 })
  722. })
  723. it('defers a reentrant detach until the creation dispatch unwinds', async () => {
  724. const ctx = new Context()
  725. await ctx.plugin(SessionStore)
  726. const order: string[] = []
  727. const session = ctx.sessions.prepare(SessionId('reentrant-detach'))
  728. const detach = ctx.sessions.enter(session)
  729. ctx.on('session/created', (created) => {
  730. order.push('created:first')
  731. detach()
  732. expect(ctx.sessions.get(created.id)).toBe(created)
  733. })
  734. ctx.on('session/created', (created) => {
  735. order.push('created:second')
  736. expect(ctx.sessions.get(created.id)).toBe(created)
  737. })
  738. ctx.on('session/disposed', (disposed) => {
  739. order.push('disposed')
  740. expect(ctx.sessions.get(disposed.id)).toBeUndefined()
  741. })
  742. ctx.sessions.announce(session)
  743. expect(order).toEqual(['created:first', 'created:second', 'disposed'])
  744. expect(ctx.sessions.get(session.id)).toBeUndefined()
  745. detach()
  746. })
  747. it('rolls back create when its owner unloads from session/created', async () => {
  748. const ctx = new Context()
  749. await ctx.plugin(SessionStore)
  750. let ownerCtx!: Context
  751. const owner = await ctx.plugin(Object.assign((inner: Context) => { ownerCtx = inner }, { inject: ['sessions'] }))
  752. const id = SessionId('create-unload-race')
  753. ctx.on('session/created', (session) => {
  754. if (session.id === id) void owner.dispose()
  755. })
  756. ownerCtx.sessions.create(id)
  757. await owner.dispose()
  758. expect(ctx.sessions.get(id)).toBeUndefined()
  759. })
  760. it('synthesizes a minimal current-version header for a bare-created session', async () => {
  761. const ctx = new Context()
  762. await ctx.plugin(SessionStore)
  763. const session = ctx.sessions.create(SessionId('plain'))
  764. expect(session.header).toMatchObject({ version: SESSION_FORMAT_VERSION, id: 'plain' })
  765. expect(typeof session.header.createdAt).toBe('number')
  766. expect(session.header.cwd).toBeUndefined()
  767. expect(session.header.parentSession).toBeUndefined()
  768. })
  769. it('attaches cwd and parentSession from meta to the header', async () => {
  770. const ctx = new Context()
  771. await ctx.plugin(SessionStore)
  772. const session = ctx.sessions.create(SessionId('child'), {
  773. meta: { cwd: '/work/project', parentSession: SessionId('parent') },
  774. })
  775. expect(session.header).toMatchObject({
  776. version: SESSION_FORMAT_VERSION,
  777. id: 'child',
  778. cwd: '/work/project',
  779. parentSession: 'parent',
  780. })
  781. })
  782. it('attaches delegationDepth from meta to the header', async () => {
  783. const ctx = new Context()
  784. await ctx.plugin(SessionStore)
  785. const session = ctx.sessions.create(SessionId('delegated-child'), {
  786. meta: { parentSession: SessionId('parent'), delegationDepth: 2 },
  787. })
  788. expect(session.header).toMatchObject({
  789. id: 'delegated-child',
  790. parentSession: 'parent',
  791. delegationDepth: 2,
  792. })
  793. })
  794. it('rejects non-JSON and invalid scalar session metadata', async () => {
  795. const ctx = new Context()
  796. await ctx.plugin(SessionStore)
  797. const cases: Array<{ meta: unknown; error: RegExp }> = [
  798. { meta: { parentSession: 1n }, error: /header is not losslessly JSON-serializable/ },
  799. { meta: { cwd: 1 }, error: /header cwd must be a string/ },
  800. { meta: { parentSession: 1 }, error: /header parentSession must be a string/ },
  801. { meta: { createdAt: '123' }, error: /header createdAt must be a finite number/ },
  802. { meta: { seedLength: '1' }, error: /seedLength must be a non-negative safe integer/ },
  803. { meta: { seedLength: 0.5 }, error: /seedLength must be a non-negative safe integer/ },
  804. { meta: { seedLength: -1 }, error: /seedLength must be a non-negative safe integer/ },
  805. { meta: { delegationDepth: '1' }, error: /delegationDepth must be a non-negative safe integer/ },
  806. { meta: { delegationDepth: 0.5 }, error: /delegationDepth must be a non-negative safe integer/ },
  807. { meta: { delegationDepth: -1 }, error: /delegationDepth must be a non-negative safe integer/ },
  808. ]
  809. for (const [index, { meta, error }] of cases.entries()) {
  810. expect(() => ctx.sessions.prepare(SessionId(`bad-meta-${index}`), {
  811. meta: meta as NonNullable<CreateSessionOptions['meta']>,
  812. })).toThrow(error)
  813. }
  814. })
  815. it('rejects a non-absolute meta.cwd', async () => {
  816. const ctx = new Context()
  817. await ctx.plugin(SessionStore)
  818. expect(() => ctx.sessions.create(SessionId('rel'), { meta: { cwd: 'relative/path' } }))
  819. .toThrow(/cwd must be an absolute path/)
  820. // the rejected session was not registered
  821. expect(ctx.sessions.get(SessionId('rel'))).toBeUndefined()
  822. })
  823. it('a bare Session() constructed without the store still exposes a current-version header', () => {
  824. const session = new Session(SessionId('bare'))
  825. expect(session.header).toMatchObject({ version: SESSION_FORMAT_VERSION, id: 'bare' })
  826. expect(typeof session.header.createdAt).toBe('number')
  827. })
  828. it('detaches sessions when the creating fiber is disposed (HMR safety)', async () => {
  829. const ctx = new Context()
  830. await ctx.plugin(SessionStore)
  831. let session!: Session
  832. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  833. session = inner.sessions.create(SessionId('scoped'))
  834. }, { inject: ['sessions'] }))
  835. expect(ctx.sessions.get(SessionId('scoped'))).toBe(session)
  836. let observed = 0
  837. ctx.on('session/event', () => void observed++)
  838. await fiber.dispose()
  839. expect(ctx.sessions.get(SessionId('scoped'))).toBeUndefined()
  840. session.append('user/message', { content: [{ type: 'text', text: 'late' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  841. expect(observed).toBe(0)
  842. })
  843. it('pairs a partial session/created announcement with disposal during rollback', async () => {
  844. const ctx = new Context()
  845. await ctx.plugin(SessionStore)
  846. let threw = false
  847. const disposed: Session[] = []
  848. ctx.on('session/disposed', (session) => { disposed.push(session) })
  849. ctx.on('session/created', () => {
  850. if (!threw) { threw = true; throw new Error('boom created listener') }
  851. })
  852. // The throwing emit must roll the store entry back, not leak it.
  853. expect(() => ctx.sessions.create(SessionId('fixed'))).toThrow('boom created listener')
  854. expect(ctx.sessions.get(SessionId('fixed'))).toBeUndefined() // rolled back, not leaked
  855. expect(disposed.map(session => session.id)).toEqual(['fixed'])
  856. // A subsequent create of the SAME id succeeds (the already-exists check is
  857. // not wedged) and its store-owned publication hooks are correctly wired.
  858. const events: SessionEvent[] = []
  859. ctx.on('session/event', (_session, event) => void events.push(event))
  860. const session = ctx.sessions.create(SessionId('fixed'))
  861. expect(ctx.sessions.get(SessionId('fixed'))).toBe(session)
  862. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  863. expect(events).toHaveLength(1)
  864. })
  865. it('contains session/event observer failures after the append commit point', async () => {
  866. const ctx = new Context()
  867. await ctx.plugin(SessionStore)
  868. const warnings: string[] = []
  869. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  870. const session = ctx.sessions.create(SessionId('contained-event'))
  871. const heard: SessionEvent[] = []
  872. let committedBeforeNotify = false
  873. ctx.on('session/event', (observedSession, event) => {
  874. committedBeforeNotify = observedSession.events.at(-1) === event
  875. throw new Error('sync event observer')
  876. })
  877. ctx.on('session/event', () => Promise.reject(new Error('async event observer')) as never)
  878. ctx.on('session/event', (_observedSession, event) => { heard.push(event) })
  879. let appended!: SessionEvent
  880. expect(() => {
  881. appended = session.append('turn/start', {
  882. turn: 1,
  883. trigger: { kind: 'message', source: { kind: 'user' } },
  884. })
  885. }).not.toThrow()
  886. expect(committedBeforeNotify).toBe(true)
  887. expect(session.events).toEqual([appended])
  888. expect(heard).toEqual([appended])
  889. await Promise.resolve()
  890. await Promise.resolve()
  891. expect(warnings).toEqual([
  892. 'session "contained-event": session/event listener threw: Error: sync event observer',
  893. 'session "contained-event": session/event listener rejected: Error: async event observer',
  894. ])
  895. })
  896. it('runs internal dispatch validation on one frozen candidate before commit and resets after a veto', async () => {
  897. const ctx = new Context()
  898. await ctx.plugin(SessionStore)
  899. const session = ctx.sessions.create(SessionId('dispatch-veto'))
  900. const validations: Array<{ event: SessionEvent; logLength: number; frozen: boolean }> = []
  901. const observed: SessionEvent[] = []
  902. let reject = true
  903. ctx.on('internal/dispatch', (_mode, name, args) => {
  904. if (name !== 'session/event') return
  905. const [observedSession, event] = args as [Session, SessionEvent]
  906. validations.push({
  907. event,
  908. logLength: observedSession.events.length,
  909. frozen: Object.isFrozen(event) && Object.isFrozen(event.data),
  910. })
  911. if (reject) {
  912. reject = false
  913. throw new Error('reject first candidate')
  914. }
  915. })
  916. ctx.on('session/event', (_observedSession, event) => { observed.push(event) })
  917. expect(() => session.append('turn/start', {
  918. turn: 1,
  919. trigger: { kind: 'message', source: { kind: 'user' } },
  920. })).toThrow('reject first candidate')
  921. expect(session.events).toEqual([])
  922. expect(observed).toEqual([])
  923. const appended = session.append('turn/start', {
  924. turn: 1,
  925. trigger: { kind: 'message', source: { kind: 'user' } },
  926. })
  927. expect(validations.map(({ logLength, frozen }) => ({ logLength, frozen }))).toEqual([
  928. { logLength: 0, frozen: true },
  929. { logLength: 0, frozen: true },
  930. ])
  931. expect(validations.map(({ event }) => event.seq)).toEqual([0, 0])
  932. expect(validations[1]!.event).toBe(appended)
  933. expect(session.events).toEqual([appended])
  934. expect(observed).toEqual([appended])
  935. })
  936. it('does not publish a surface transition rejected by internal dispatch', async () => {
  937. const ctx = new Context()
  938. await ctx.plugin(SessionStore)
  939. const session = ctx.sessions.create(SessionId('surface-dispatch-veto'))
  940. session.append('user/message', {
  941. content: [{ type: 'text', text: 'source' }],
  942. source: { kind: 'user' },
  943. }, { surfaceOp: 'append' })
  944. const surface = session.surface
  945. let reject = true
  946. ctx.on('internal/dispatch', (_mode, name) => {
  947. if (name === 'session/event' && reject) {
  948. reject = false
  949. throw new Error('reject surface candidate')
  950. }
  951. })
  952. expect(() => session.append('assistant/message', {
  953. provenance: { provider: 'mock', model: 'mock' },
  954. turn: 1,
  955. step: 1,
  956. content: [{ type: 'text', text: 'replacement' }],
  957. }, {
  958. surfaceOp: { op: 'replace', start: 0, end: 0 },
  959. sourceEventSeqs: [0],
  960. })).toThrow('reject surface candidate')
  961. expect(session.events).toHaveLength(1)
  962. expect(surface.nodes).toEqual([0])
  963. expect(surface.replaceGeneration).toBe(0)
  964. session.append('user/message', {
  965. content: [{ type: 'text', text: 'next' }],
  966. source: { kind: 'user' },
  967. }, { surfaceOp: 'append' })
  968. expect(surface.nodes).toEqual([0, 1])
  969. expect(surface.replaceGeneration).toBe(0)
  970. })
  971. it('resolves session/event dispatch before commit so instrumentation failure cannot hide a logged event', async () => {
  972. const ctx = new Context()
  973. await ctx.plugin(SessionStore)
  974. const session = ctx.sessions.create(SessionId('dispatch-check'))
  975. const observed: SessionEvent[] = []
  976. ctx.on('internal/dispatch', (_mode, name) => {
  977. if (name === 'session/event') throw new Error('dispatch instrumentation rejected the carrier')
  978. })
  979. ctx.on('session/event', (_observedSession, event) => { observed.push(event) })
  980. expect(() => session.append('turn/start', {
  981. turn: 1,
  982. trigger: { kind: 'message', source: { kind: 'user' } },
  983. })).toThrow('dispatch instrumentation rejected the carrier')
  984. expect(session.events).toEqual([])
  985. expect(observed).toEqual([])
  986. })
  987. it('contains a reentrant observer append without reordering later observers', async () => {
  988. const ctx = new Context()
  989. await ctx.plugin(SessionStore)
  990. const warnings: string[] = []
  991. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  992. const session = ctx.sessions.create(SessionId('reentrant-observer'))
  993. const heard: SessionEvent[] = []
  994. ctx.on('session/event', (observedSession) => {
  995. observedSession.append('todo/write', { todos: [] })
  996. })
  997. ctx.on('session/event', (_observedSession, event) => { heard.push(event) })
  998. const appended = session.append('turn/start', {
  999. turn: 1,
  1000. trigger: { kind: 'message', source: { kind: 'user' } },
  1001. })
  1002. expect(session.events).toEqual([appended])
  1003. expect(heard).toEqual([appended])
  1004. expect(warnings).toEqual([
  1005. 'session "reentrant-observer": session/event listener threw: Error: session append cannot reenter while another append is being published',
  1006. ])
  1007. })
  1008. it('defers detach through dispatch resolution, commit, and observer publication', async () => {
  1009. const ctx = new Context()
  1010. await ctx.plugin(SessionStore)
  1011. const order: string[] = []
  1012. const session = ctx.sessions.prepare(SessionId('detach-during-append'))
  1013. const detach = ctx.sessions.enter(session)
  1014. ctx.on('internal/dispatch', (_mode, name, args) => {
  1015. if (name !== 'session/event') return
  1016. const session = args[0] as Session
  1017. order.push(`resolve:${ctx.sessions.get(session.id) === session ? 'live' : 'detached'}`)
  1018. detach()
  1019. })
  1020. ctx.on('session/event', (session) => {
  1021. order.push(`observe:${ctx.sessions.get(session.id) === session ? 'live' : 'detached'}`)
  1022. })
  1023. ctx.on('session/disposed', (session) => {
  1024. order.push(`dispose:${ctx.sessions.get(session.id) === session ? 'live' : 'detached'}`)
  1025. })
  1026. ctx.sessions.announce(session)
  1027. const appended = session.append('turn/start', {
  1028. turn: 1,
  1029. trigger: { kind: 'message', source: { kind: 'user' } },
  1030. })
  1031. expect(session.events).toEqual([appended])
  1032. expect(order).toEqual(['resolve:live', 'observe:live', 'dispose:detached'])
  1033. expect(ctx.sessions.get(session.id)).toBeUndefined()
  1034. })
  1035. it('observes async session/created rejection without rolling back or starving peers', async () => {
  1036. const ctx = new Context()
  1037. await ctx.plugin(SessionStore)
  1038. const warnings: string[] = []
  1039. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  1040. const heard: string[] = []
  1041. ctx.on('session/created', () => Promise.reject(new Error('late creation failure')) as never)
  1042. ctx.on('session/created', (session) => { heard.push(session.id) })
  1043. const session = ctx.sessions.create(SessionId('async-created'))
  1044. await Promise.resolve()
  1045. await Promise.resolve()
  1046. expect(ctx.sessions.get(session.id)).toBe(session)
  1047. expect(heard).toEqual(['async-created'])
  1048. expect(warnings).toEqual([
  1049. 'session "async-created": session/created listener rejected: Error: late creation failure',
  1050. ])
  1051. })
  1052. it('contains synchronous and async session/disposed listener failures per observer', async () => {
  1053. const ctx = new Context()
  1054. await ctx.plugin(SessionStore)
  1055. const warnings: string[] = []
  1056. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  1057. const heard: string[] = []
  1058. ctx.on('session/disposed', () => { throw new Error('sync disposed') })
  1059. ctx.on('session/disposed', () => Promise.reject(new Error('async disposed')) as never)
  1060. ctx.on('session/disposed', (session) => { heard.push(session.id) })
  1061. const unannounced = ctx.sessions.prepare(SessionId('never-announced'))
  1062. const detachUnannounced = ctx.sessions.enter(unannounced)
  1063. detachUnannounced()
  1064. expect(heard).toEqual([])
  1065. const announced = ctx.sessions.prepare(SessionId('contained-disposal'))
  1066. const detach = ctx.sessions.enter(announced)
  1067. ctx.sessions.announce(announced)
  1068. expect(() => { detach() }).not.toThrow()
  1069. await Promise.resolve()
  1070. await Promise.resolve()
  1071. expect(heard).toEqual(['contained-disposal'])
  1072. expect(warnings).toEqual([
  1073. 'session "contained-disposal": session/disposed listener threw: Error: sync disposed',
  1074. 'session "contained-disposal": session/disposed listener rejected: Error: async disposed',
  1075. ])
  1076. })
  1077. it('contains internal dispatch failure after session detachment', async () => {
  1078. const ctx = new Context()
  1079. await ctx.plugin(SessionStore)
  1080. const warnings: string[] = []
  1081. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  1082. const heard: Session[] = []
  1083. ctx.on('internal/dispatch', (_mode, name) => {
  1084. if (name === 'session/disposed') throw new Error('disposed dispatch instrumentation')
  1085. })
  1086. ctx.on('session/disposed', (session) => { heard.push(session) })
  1087. const session = ctx.sessions.prepare(SessionId('disposed-dispatch'))
  1088. const detach = ctx.sessions.enter(session)
  1089. ctx.sessions.announce(session)
  1090. expect(() => { detach() }).not.toThrow()
  1091. expect(ctx.sessions.get(session.id)).toBeUndefined()
  1092. expect(heard).toEqual([])
  1093. expect(warnings).toEqual([
  1094. 'session "disposed-dispatch": session/disposed dispatch threw: Error: disposed dispatch instrumentation',
  1095. ])
  1096. })
  1097. it('does not let internal dispatch replace the disposed callback tuple', async () => {
  1098. const ctx = new Context()
  1099. await ctx.plugin(SessionStore)
  1100. const replacement = new Session(SessionId('replacement-disposed'))
  1101. const heard: Session[] = []
  1102. ctx.on('internal/dispatch', (_mode, name, args) => {
  1103. if (name === 'session/disposed') args[0] = replacement
  1104. })
  1105. ctx.on('session/disposed', (session) => { heard.push(session) })
  1106. const session = ctx.sessions.prepare(SessionId('fixed-disposed-tuple'))
  1107. const detach = ctx.sessions.enter(session)
  1108. ctx.sessions.announce(session)
  1109. detach()
  1110. expect(heard).toEqual([session])
  1111. })
  1112. })
  1113. describe('todo/write event', () => {
  1114. it('appends the whole-list snapshot and isolates the log from later mutation', () => {
  1115. const session = new Session(SessionId('t1'))
  1116. const todos: TodoItem[] = [
  1117. { content: 'plan the work', status: 'in_progress' },
  1118. { content: 'write the code', status: 'pending' },
  1119. ]
  1120. session.append('todo/write', { todos })
  1121. const event = session.events.findLast(e => e.type === 'todo/write')!
  1122. expect(event.type).toBe('todo/write')
  1123. expect(event.data.todos).toEqual(todos)
  1124. // The append snapshots its input: mutating the caller's array afterward must
  1125. // not change what the log holds (the durable-source-of-truth contract).
  1126. todos.push({ content: 'sneak in', status: 'pending' })
  1127. todos[0]!.status = 'completed'
  1128. expect(event.data.todos).toEqual([
  1129. { content: 'plan the work', status: 'in_progress' },
  1130. { content: 'write the code', status: 'pending' },
  1131. ])
  1132. })
  1133. it('is last-write-wins: the current list is the most recent todo/write', () => {
  1134. const session = new Session(SessionId('t2'))
  1135. session.append('todo/write', { todos: [{ content: 'first', status: 'pending' }] })
  1136. session.append('todo/write', { todos: [
  1137. { content: 'first', status: 'completed' },
  1138. { content: 'second', status: 'in_progress' },
  1139. ] })
  1140. const current = session.events.findLast(e => e.type === 'todo/write')!.data.todos
  1141. expect(current).toEqual([
  1142. { content: 'first', status: 'completed' },
  1143. { content: 'second', status: 'in_progress' },
  1144. ])
  1145. })
  1146. it('is NOT a surface event: it produces no derived message and joins no surface node', () => {
  1147. const session = new Session(SessionId('t3'))
  1148. session.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1149. const before = session.deriveMessages().length
  1150. session.append('todo/write', { todos: [{ content: 'a task', status: 'pending' }] })
  1151. // The todo event must not add a message to the derived history…
  1152. expect(session.deriveMessages()).toHaveLength(before)
  1153. // …and must not appear on the ordered surface.
  1154. expect(session.surface.nodes).not.toContain(session.seq - 1)
  1155. })
  1156. it('round-trips through a seeded replay identically (durable, no surfaceOp needed)', () => {
  1157. const original = new Session(SessionId('t4'))
  1158. original.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1159. original.append('todo/write', { todos: [{ content: 'only', status: 'completed' }] })
  1160. original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1161. // Seeding a non-surface event with no surfaceOp must not throw.
  1162. const replayed = new Session(SessionId('t4-replay'), [...original.events])
  1163. expect(replayed.events.findLast(e => e.type === 'todo/write')!.data.todos)
  1164. .toEqual([{ content: 'only', status: 'completed' }])
  1165. expect(replayed.seq).toBe(original.seq)
  1166. })
  1167. })