session.spec.ts 61 KB

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