session.spec.ts 56 KB

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