tool-session-query.spec.ts 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context, type Fiber } from 'cordis'
  3. import type { Agent } from '@deepseek-ai/dsh-agent'
  4. import { CallId, HarnessError } from '@deepseek-ai/dsh-llm'
  5. import { MAX_TIMER_DELAY_MS, TimeoutReason } from '@deepseek-ai/dsh-timeout'
  6. import * as TimeoutPolicy from '@deepseek-ai/dsh-timeout-policy'
  7. import SessionStore, {
  8. SESSION_FORMAT_VERSION,
  9. SessionId,
  10. type Session,
  11. type SessionHeader,
  12. type SessionId as SessionIdValue,
  13. } from '@deepseek-ai/dsh-session'
  14. import SessionQueryService, {
  15. SessionQueryError,
  16. SessionSearchCursor,
  17. type SessionEventSearchHit,
  18. type SessionEventSearchPage,
  19. type SessionEventSearchRequest,
  20. type SessionLineageNode,
  21. type SessionSearchExecContext,
  22. type SessionSearchHit,
  23. type SessionSearchPage,
  24. type SessionSearchRequest,
  25. type SessionTitleObservationResult,
  26. } from '@deepseek-ai/dsh-session-query'
  27. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  28. import ToolRegistry, { type ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  29. import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query'
  30. const activeContexts: Context[] = []
  31. afterEach(async () => {
  32. vi.useRealTimers()
  33. vi.restoreAllMocks()
  34. for (const ctx of activeContexts.splice(0)) await ctx.fiber.dispose()
  35. FakeQuery.reset()
  36. })
  37. function header(id: string, cwd: string | undefined, createdAt = 1, parentSession?: SessionIdValue): SessionHeader {
  38. return {
  39. version: SESSION_FORMAT_VERSION,
  40. id: SessionId(id),
  41. createdAt,
  42. ...cwd === undefined ? {} : { cwd },
  43. ...parentSession === undefined ? {} : { parentSession },
  44. }
  45. }
  46. function createSession(
  47. ctx: Context,
  48. id: string,
  49. cwd: string | undefined,
  50. createdAt = 1,
  51. parentSession?: SessionIdValue,
  52. ): Session {
  53. return ctx.sessions.create(SessionId(id), {
  54. meta: {
  55. createdAt,
  56. ...cwd === undefined ? {} : { cwd },
  57. ...parentSession === undefined ? {} : { parentSession },
  58. },
  59. })
  60. }
  61. function openStep(session: Session, text = 'prior needle'): void {
  62. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  63. session.append(
  64. 'user/message',
  65. { content: [{ type: 'text', text }], source: { kind: 'user' } },
  66. { surfaceOp: 'append' },
  67. )
  68. session.append('step/start', { turn: 1, step: 1 })
  69. }
  70. function fakeAgent(session: Session): Agent {
  71. return { id: session.id, session } as unknown as Agent
  72. }
  73. function sessionHit(
  74. id: string,
  75. cwd: string | undefined,
  76. text = 'needle excerpt',
  77. parentSession?: SessionIdValue,
  78. ): SessionSearchHit {
  79. return {
  80. header: header(id, cwd, 100, parentSession),
  81. live: true,
  82. persisted: false,
  83. bestMatch: {
  84. sessionId: SessionId(id),
  85. seq: 4,
  86. type: 'assistant/message',
  87. time: 200,
  88. surface: 'current',
  89. snippet: text,
  90. },
  91. }
  92. }
  93. function eventHit(sessionId: SessionIdValue, seq: number, text = 'needle excerpt'): SessionEventSearchHit {
  94. return {
  95. sessionId,
  96. seq,
  97. type: 'user/message',
  98. time: 200 + seq,
  99. surface: 'current',
  100. snippet: text,
  101. }
  102. }
  103. class FakeQuery extends SessionQueryService {
  104. static sessionSearch: (
  105. request: SessionSearchRequest,
  106. exec?: SessionSearchExecContext,
  107. ) => Promise<SessionSearchPage<SessionSearchHit>> = () => Promise.resolve({ items: [] })
  108. static eventSearch: (
  109. request: SessionEventSearchRequest,
  110. exec?: SessionSearchExecContext,
  111. ) => Promise<SessionEventSearchPage> = request => Promise.resolve({
  112. session: header(request.sessionId, '/work'),
  113. items: [],
  114. })
  115. static sessionRequests: SessionSearchRequest[] = []
  116. static eventRequests: SessionEventSearchRequest[] = []
  117. static searchSignals: Array<AbortSignal | undefined> = []
  118. static titles = new Map<SessionIdValue, string | Error>()
  119. static reset(): void {
  120. this.sessionSearch = () => Promise.resolve({ items: [] })
  121. this.eventSearch = request => Promise.resolve({
  122. session: header(request.sessionId, '/work'),
  123. items: [],
  124. })
  125. this.sessionRequests = []
  126. this.eventRequests = []
  127. this.searchSignals = []
  128. this.titles = new Map()
  129. }
  130. override searchSessions(
  131. request: SessionSearchRequest,
  132. exec?: SessionSearchExecContext,
  133. ): Promise<SessionSearchPage<SessionSearchHit>> {
  134. FakeQuery.sessionRequests.push(request)
  135. FakeQuery.searchSignals.push(exec?.signal)
  136. return FakeQuery.sessionSearch(request, exec)
  137. }
  138. override searchEvents(
  139. request: SessionEventSearchRequest,
  140. exec?: SessionSearchExecContext,
  141. ): Promise<SessionEventSearchPage> {
  142. FakeQuery.eventRequests.push(request)
  143. FakeQuery.searchSignals.push(exec?.signal)
  144. return FakeQuery.eventSearch(request, exec)
  145. }
  146. override async readTitleSnapshots(
  147. sessionIds: readonly SessionIdValue[],
  148. signal?: AbortSignal,
  149. ): Promise<SessionTitleObservationResult[]> {
  150. const observations = await super.readTitleSnapshots(sessionIds, signal)
  151. return observations.map((observation): SessionTitleObservationResult => {
  152. const value = FakeQuery.titles.get(observation.sessionId)
  153. if (value instanceof Error) {
  154. return { sessionId: observation.sessionId, status: 'rejected', reason: value }
  155. }
  156. if (value === undefined || observation.status === 'rejected') return observation
  157. return {
  158. ...observation,
  159. value: {
  160. ...observation.value,
  161. title: {
  162. title: value,
  163. messageSeqs: [],
  164. source: { kind: 'fallback' },
  165. eventSeq: 0,
  166. updatedAt: 1,
  167. },
  168. },
  169. }
  170. })
  171. }
  172. }
  173. interface Mounted {
  174. readonly ctx: Context
  175. readonly fiber: Fiber
  176. readonly caller: Session
  177. call(name: string, args: unknown, options?: { agent?: Agent; signal?: AbortSignal }): Promise<ToolExecutionResult>
  178. }
  179. async function mount(
  180. config: ToolSessionQuery.Config = {},
  181. callerCwd: string | null = '/work',
  182. enforceTimeout = false,
  183. ): Promise<Mounted> {
  184. const ctx = new Context()
  185. activeContexts.push(ctx)
  186. await ctx.plugin(SessionStore)
  187. await ctx.plugin(SystemPrompt)
  188. await ctx.plugin(ToolRegistry)
  189. if (enforceTimeout) await ctx.plugin(TimeoutPolicy)
  190. await ctx.plugin(FakeQuery)
  191. const fiber = await ctx.plugin(ToolSessionQuery, config)
  192. const caller = createSession(ctx, 'caller', callerCwd ?? undefined, 10)
  193. openStep(caller)
  194. let calls = 0
  195. return {
  196. ctx,
  197. fiber,
  198. caller,
  199. call: (toolName, args, options = {}) => ctx.tools.execute({
  200. name: toolName,
  201. arguments: args,
  202. callId: CallId(`call-${++calls}`),
  203. signal: options.signal ?? new AbortController().signal,
  204. ...options.agent === undefined ? { agent: fakeAgent(caller) } : { agent: options.agent },
  205. }),
  206. }
  207. }
  208. function text(result: ToolExecutionResult): string {
  209. return result.content.map(block => block.type === 'text' ? block.text : '').join('\n')
  210. }
  211. function errorCode(result: ToolExecutionResult): string | undefined {
  212. return result.isError ? result.error.info?.code : undefined
  213. }
  214. describe('registration and schemas', () => {
  215. it('registers the five cursor-free tools, prompt, timeouts, and pure generic presenters, then disposes them', async () => {
  216. const mounted = await mount({ maxSearchResults: 7, searchTimeoutMs: 1234 })
  217. const names = mounted.ctx.tools.schemas().map(schema => schema.name)
  218. expect(names).toEqual([
  219. 'session_search',
  220. 'session_event_search',
  221. 'session_trace',
  222. 'session_event_trace',
  223. 'session_event_read',
  224. ])
  225. const sessionSchema = mounted.ctx.tools.schemas().find(schema => schema.name === 'session_search')
  226. expect(sessionSchema?.parameters).not.toHaveProperty('properties.cursor')
  227. expect(sessionSchema?.parameters).not.toHaveProperty('properties.limit')
  228. expect(sessionSchema?.parameters).not.toHaveProperty('properties.cwd')
  229. expect(mounted.ctx.tools.get('session_search')?.timeoutMs).toBe(1234)
  230. expect(mounted.ctx.tools.get('session_trace')?.timeoutMs).toBeUndefined()
  231. const parallelArgs: Record<string, unknown> = {
  232. session_trace: {},
  233. session_event_trace: { seq: 0 },
  234. session_event_read: { seq: 0 },
  235. }
  236. for (const [name, args] of Object.entries(parallelArgs)) {
  237. expect(mounted.ctx.tools.get(name)?.isConcurrencySafe?.(args)).toBe(true)
  238. }
  239. expect(mounted.ctx.tools.get('session_search')?.output.render({}, 'rendered'))
  240. .toEqual([{ type: 'text', text: 'rendered' }])
  241. expect(mounted.ctx.tools.get('session_search')?.presentCall?.({ query: 'needle' }))
  242. .toEqual({ card: 'generic', kind: 'search', title: 'Search prior sessions', rawInput: 'needle' })
  243. expect(mounted.ctx.tools.get('session_event_search')?.presentCall?.({ query: 'needle' }))
  244. .toEqual({ card: 'generic', kind: 'search', title: 'Search session events', rawInput: 'needle' })
  245. expect(mounted.ctx.tools.get('session_trace')?.presentCall?.({}))
  246. .toEqual({ card: 'generic', kind: 'read', title: 'Trace current session' })
  247. expect(mounted.ctx.tools.get('session_trace')?.presentCall?.({ session_id: 'other' }))
  248. .toEqual({ card: 'generic', kind: 'read', title: 'Trace session other', rawInput: 'other' })
  249. expect(mounted.ctx.tools.get('session_event_trace')?.presentCall?.({ session_id: 'other', seq: 3 }))
  250. .toEqual({
  251. card: 'generic',
  252. kind: 'read',
  253. title: 'Trace event 3',
  254. rawInput: { session_id: 'other', seq: 3 },
  255. })
  256. expect(mounted.ctx.tools.get('session_event_read')?.presentCall?.({ seq: 4 }))
  257. .toEqual({ card: 'generic', kind: 'read', title: 'Read event 4', rawInput: { seq: 4 } })
  258. const assembly = await mounted.ctx.systemPrompt.assemble()
  259. expect(assembly.sections.find(section => section.name === 'tool:session-query')?.text)
  260. .toContain('prior sessions')
  261. await mounted.fiber.dispose()
  262. expect(mounted.ctx.tools.schemas().map(schema => schema.name)).toEqual([])
  263. expect((await mounted.ctx.systemPrompt.assemble()).sections.map(section => section.name))
  264. .not.toContain('tool:session-query')
  265. })
  266. it('keeps generation-bound searches exclusive while exact observations remain parallel', async () => {
  267. const mounted = await mount()
  268. const classifications = [
  269. ['session_search', { query: 'q' }, 'exclusive'],
  270. ['session_event_search', { query: 'q' }, 'exclusive'],
  271. ['session_trace', {}, 'parallel'],
  272. ['session_event_trace', { seq: 0 }, 'parallel'],
  273. ['session_event_read', { seq: 0 }, 'parallel'],
  274. ] as const
  275. for (const [name, args, kind] of classifications) {
  276. expect(mounted.ctx.tools.executionMode({
  277. name,
  278. arguments: args,
  279. callId: CallId(`mode-${name}`),
  280. signal: new AbortController().signal,
  281. agent: fakeAgent(mounted.caller),
  282. })).toEqual({ kind })
  283. }
  284. })
  285. it('fails invalid direct config before registering anything', async () => {
  286. const mounted = await mount()
  287. for (const maxSearchResults of [0, 1.5, Number.NaN]) {
  288. expect(() => { ToolSessionQuery.apply(mounted.ctx, { maxSearchResults }) })
  289. .toThrow('maxSearchResults')
  290. }
  291. for (const searchTimeoutMs of [0, 1.5, Number.POSITIVE_INFINITY, MAX_TIMER_DELAY_MS + 1]) {
  292. expect(() => { ToolSessionQuery.apply(mounted.ctx, { searchTimeoutMs }) })
  293. .toThrow(`no greater than ${MAX_TIMER_DELAY_MS}`)
  294. }
  295. expect(() => { ToolSessionQuery.apply(new Context(), {}) }).toThrow()
  296. })
  297. it('expresses the complete Node timer range in the Loader config schema', () => {
  298. expect(new ToolSessionQuery.Config({ searchTimeoutMs: MAX_TIMER_DELAY_MS }))
  299. .toEqual({ maxSearchResults: 100, searchTimeoutMs: MAX_TIMER_DELAY_MS })
  300. expect(() => new ToolSessionQuery.Config({ searchTimeoutMs: 1.5 })).toThrow()
  301. expect(() => new ToolSessionQuery.Config({ searchTimeoutMs: MAX_TIMER_DELAY_MS + 1 })).toThrow()
  302. })
  303. })
  304. describe('input validation and translation', () => {
  305. it.each([
  306. [{ query: ' ' }, 'SESSION_QUERY_INVALID_QUERY'],
  307. [{ query: 'bad\0query' }, 'SESSION_QUERY_INVALID_QUERY'],
  308. [{ query: 'q', session_ids: [] }, 'SESSION_QUERY_INVALID_FILTER'],
  309. [{ query: 'q', parent_session_ids: [] }, 'SESSION_QUERY_INVALID_FILTER'],
  310. [{ query: 'q', availability: [] }, 'SESSION_QUERY_INVALID_FILTER'],
  311. [{ query: 'q', availability: ['archived'] }, 'INVALID_ARGS'],
  312. [{ query: 'q', event_types: [] }, 'SESSION_QUERY_INVALID_FILTER'],
  313. [{ query: 'q', event_surfaces: [] }, 'SESSION_QUERY_INVALID_FILTER'],
  314. [{ query: 'q', event_surfaces: ['hidden'] }, 'INVALID_ARGS'],
  315. [{ query: 'q', event_seq_from: -1 }, 'SESSION_QUERY_INVALID_FILTER'],
  316. [{ query: 'q', event_seq_to: Number.MAX_SAFE_INTEGER + 1 }, 'SESSION_QUERY_INVALID_FILTER'],
  317. [{ query: 'q', event_seq_from: 2, event_seq_to: 1 }, 'SESSION_QUERY_INVALID_FILTER'],
  318. [{ query: 'q', created_at_from: '2026-07-24T10:00:00' }, 'SESSION_QUERY_INVALID_FILTER'],
  319. [{ query: 'q', created_at_from: '2026-02-30T10:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'],
  320. [{ query: 'q', created_at_from: '2100-02-29T10:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'],
  321. [{ query: 'q', created_at_from: '2026-04-31T10:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'],
  322. [{ query: 'q', created_at_from: '2026-01-01T24:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'],
  323. [{ query: 'q', created_at_from: '2026-01-01T00:60:00Z' }, 'SESSION_QUERY_INVALID_FILTER'],
  324. [{ query: 'q', created_at_from: '2026-01-01T00:00:60Z' }, 'SESSION_QUERY_INVALID_FILTER'],
  325. [{ query: 'q', created_at_from: '2026-01-01T00:00:00+24:00' }, 'SESSION_QUERY_INVALID_FILTER'],
  326. [{ query: 'q', created_at_from: '2026-01-01T00:00:00+00:60' }, 'SESSION_QUERY_INVALID_FILTER'],
  327. [{
  328. query: 'q',
  329. created_at_from: '2026-07-25T00:00:00Z',
  330. created_at_to: '2026-07-24T00:00:00Z',
  331. }, 'SESSION_QUERY_INVALID_FILTER'],
  332. ])('rejects invalid search arguments %#', async (args, code) => {
  333. const mounted = await mount()
  334. const result = await mounted.call('session_search', args)
  335. expect(errorCode(result)).toBe(code)
  336. })
  337. it('normalizes the query and compiles inclusive session/event filters with one parent OR clause', async () => {
  338. const mounted = await mount()
  339. createSession(mounted.ctx, 'parent', '/work')
  340. await mounted.call('session_search', {
  341. query: ' alpha beta ',
  342. session_ids: ['a', 'b'],
  343. created_at_from: '2026-07-24T00:00:00+08:00',
  344. created_at_to: '2026-07-24T01:00:00+08:00',
  345. parent_session_ids: ['parent'],
  346. include_root_sessions: true,
  347. availability: ['live'],
  348. event_seq_from: 2,
  349. event_seq_to: 9,
  350. event_time_from: '2026-07-24T00:00:00Z',
  351. event_time_to: '2026-07-24T01:00:00Z',
  352. event_types: ['plugin/open-event'],
  353. event_surfaces: ['shadowed'],
  354. })
  355. expect(FakeQuery.sessionRequests).toHaveLength(1)
  356. expect(FakeQuery.sessionRequests[0]).toEqual({
  357. query: 'alpha beta',
  358. sessionFilters: [
  359. { kind: 'id', values: ['a', 'b'] },
  360. {
  361. kind: 'created-at',
  362. from: Date.parse('2026-07-24T00:00:00+08:00'),
  363. to: Date.parse('2026-07-24T01:00:00+08:00'),
  364. },
  365. { kind: 'availability', values: ['live'] },
  366. { kind: 'parent', values: ['parent', null] },
  367. { kind: 'cwd', values: ['/work'] },
  368. ],
  369. eventFilters: [
  370. { kind: 'seq', from: 2, to: 9 },
  371. {
  372. kind: 'time',
  373. from: Date.parse('2026-07-24T00:00:00Z'),
  374. to: Date.parse('2026-07-24T01:00:00Z'),
  375. },
  376. { kind: 'type', values: ['plugin/open-event'] },
  377. { kind: 'surface', values: ['shadowed'] },
  378. ],
  379. })
  380. })
  381. it.each([
  382. ['one fractional digit', '2026-07-24T00:00:00.1Z', 100],
  383. ['two fractional digits', '2026-07-24T00:00:00.12Z', 120],
  384. ['three fractional digits', '2026-07-24T00:00:00.123Z', 123],
  385. ])('normalizes %s into an exact integer epoch-millisecond filter', async (_case, value, offset) => {
  386. const mounted = await mount()
  387. await mounted.call('session_search', {
  388. query: 'q',
  389. created_at_from: value,
  390. })
  391. const expected = Date.parse('2026-07-24T00:00:00.000Z') + offset
  392. expect(Number.isFinite(expected)).toBe(true)
  393. expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({
  394. kind: 'created-at',
  395. from: expected,
  396. })
  397. })
  398. it('maps exact same-millisecond decimal bounds to adjacent numeric values without collapsing the interval', async () => {
  399. const mounted = await mount()
  400. const base = Date.parse('2026-07-24T00:00:00.000Z')
  401. const result = await mounted.call('session_search', {
  402. query: 'q',
  403. created_at_from: '2026-07-24T00:00:00.12300001Z',
  404. created_at_to: '2026-07-24T08:00:00.1239999+08:00',
  405. })
  406. expect(result.isError).toBe(false)
  407. expect(text(result)).toContain('No prior session matches found.')
  408. const range = FakeQuery.sessionRequests[0]?.sessionFilters
  409. ?.find(filter => filter.kind === 'created-at')
  410. expect(range).toBeDefined()
  411. if (range?.kind !== 'created-at' || range.from === undefined || range.to === undefined) {
  412. throw new Error('expected complete created-at range')
  413. }
  414. expect(Number.isFinite(range.from)).toBe(true)
  415. expect(Number.isFinite(range.to)).toBe(true)
  416. expect(range.from).toBeGreaterThan(base + 123)
  417. expect(range.from).toBeLessThan(base + 124)
  418. expect(range.to).toBeGreaterThan(base + 123)
  419. expect(range.to).toBeLessThan(base + 124)
  420. expect(range.from).toBeLessThan(range.to)
  421. })
  422. it('rejects exact bounds reversed only below one millisecond before calling the provider', async () => {
  423. const mounted = await mount()
  424. const result = await mounted.call('session_search', {
  425. query: 'q',
  426. created_at_from: '2026-07-24T00:00:00.12300002Z',
  427. created_at_to: '2026-07-24T00:00:00.12300001Z',
  428. })
  429. expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_FILTER')
  430. expect(FakeQuery.sessionRequests).toEqual([])
  431. })
  432. it('compares unequal-length exact remainders with implicit trailing decimal zeroes', async () => {
  433. const mounted = await mount()
  434. const ordered = await mounted.call('session_search', {
  435. query: 'q',
  436. created_at_from: '2026-07-24T00:00:00.1231Z',
  437. created_at_to: '2026-07-24T00:00:00.12311Z',
  438. })
  439. expect(ordered.isError).toBe(false)
  440. const reversed = await mounted.call('session_search', {
  441. query: 'q',
  442. created_at_from: '2026-07-24T00:00:00.12311Z',
  443. created_at_to: '2026-07-24T00:00:00.1231Z',
  444. })
  445. expect(errorCode(reversed)).toBe('SESSION_QUERY_INVALID_FILTER')
  446. })
  447. it('treats trailing-zero fractional spellings as the same exact instant', async () => {
  448. const mounted = await mount()
  449. const result = await mounted.call('session_search', {
  450. query: 'q',
  451. created_at_from: '2026-07-24T00:00:00.1230000100Z',
  452. created_at_to: '2026-07-24T00:00:00.12300001Z',
  453. })
  454. expect(result.isError).toBe(false)
  455. expect(FakeQuery.sessionRequests).toHaveLength(1)
  456. })
  457. it('maps fractional bounds correctly across zero and for negative pre-epoch milliseconds', async () => {
  458. const mounted = await mount()
  459. await mounted.call('session_search', {
  460. query: 'q',
  461. created_at_from: '1970-01-01T00:00:00.0000001Z',
  462. event_time_to: '1969-12-31T23:59:59.9999999Z',
  463. })
  464. expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({
  465. kind: 'created-at',
  466. from: Number.MIN_VALUE,
  467. })
  468. expect(FakeQuery.sessionRequests[0]?.eventFilters).toContainEqual({
  469. kind: 'time',
  470. to: -Number.MIN_VALUE,
  471. })
  472. await mounted.call('session_event_search', {
  473. query: 'q',
  474. time_from: '1969-12-31T23:59:59.87600001Z',
  475. time_to: '1969-12-31T19:59:59.8769999-04:00',
  476. })
  477. const range = FakeQuery.eventRequests[0]?.filters?.find(filter => filter.kind === 'time')
  478. expect(range).toBeDefined()
  479. if (range?.kind !== 'time' || range.from === undefined || range.to === undefined) {
  480. throw new Error('expected complete event time range')
  481. }
  482. expect(range.from).toBeGreaterThan(-124)
  483. expect(range.from).toBeLessThan(-123)
  484. expect(range.to).toBeGreaterThan(-124)
  485. expect(range.to).toBeLessThan(-123)
  486. expect(range.from).toBeLessThan(range.to)
  487. })
  488. it('rejects a normalized timestamp when the platform parser cannot produce a finite value', async () => {
  489. const mounted = await mount()
  490. vi.spyOn(Date, 'parse').mockReturnValueOnce(Number.NaN)
  491. const result = await mounted.call('session_search', {
  492. query: 'q',
  493. created_at_from: '2026-07-24T00:00:00.123456Z',
  494. })
  495. expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_FILTER')
  496. expect(FakeQuery.sessionRequests).toEqual([])
  497. })
  498. it('compiles one-sided timestamps and independent root/parent clauses', async () => {
  499. const mounted = await mount()
  500. createSession(mounted.ctx, 'parent', '/work')
  501. await mounted.call('session_search', {
  502. query: 'q',
  503. created_at_from: '2024-02-29T00:00Z',
  504. include_root_sessions: true,
  505. event_time_to: '2000-02-29T00:00Z',
  506. })
  507. expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({
  508. kind: 'created-at',
  509. from: Date.parse('2024-02-29T00:00Z'),
  510. })
  511. expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({
  512. kind: 'parent',
  513. values: [null],
  514. })
  515. expect(FakeQuery.sessionRequests[0]?.eventFilters).toContainEqual({
  516. kind: 'time',
  517. to: Date.parse('2000-02-29T00:00Z'),
  518. })
  519. await mounted.call('session_search', {
  520. query: 'q',
  521. parent_session_ids: ['parent'],
  522. })
  523. expect(FakeQuery.sessionRequests[1]?.sessionFilters).toContainEqual({
  524. kind: 'parent',
  525. values: ['parent'],
  526. })
  527. })
  528. })
  529. describe('workspace authority and lineage redaction', () => {
  530. it('fails closed without an agent and for direct cross-workspace targets', async () => {
  531. const mounted = await mount()
  532. createSession(mounted.ctx, 'outside', '/outside')
  533. const missing = await mounted.ctx.tools.execute({
  534. name: 'session_trace',
  535. arguments: {},
  536. callId: CallId('missing-agent'),
  537. signal: new AbortController().signal,
  538. })
  539. expect(errorCode(missing)).toBe('SESSION_QUERY_TOOL_MISSING_AGENT')
  540. const denied = await mounted.call('session_event_read', { session_id: 'outside', seq: 0 })
  541. expect(errorCode(denied)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  542. expect(text(denied)).not.toContain('session "outside"')
  543. })
  544. it('allows only self for a null-cwd caller and denies cross-session search', async () => {
  545. const mounted = await mount({}, null)
  546. const own = await mounted.call('session_trace', {})
  547. expect(own.isError).toBe(false)
  548. expect(text(own)).toContain('Session caller')
  549. expect(errorCode(await mounted.call('session_search', { query: 'q' })))
  550. .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  551. createSession(mounted.ctx, 'other', undefined)
  552. expect(errorCode(await mounted.call('session_trace', { session_id: 'other' })))
  553. .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  554. })
  555. it('makes hidden and nonexistent parent guesses indistinguishable without calling search', async () => {
  556. const mounted = await mount()
  557. const hiddenParent = createSession(mounted.ctx, 'guessed-hidden-parent-secret', '/outside')
  558. const visibleChild = createSession(
  559. mounted.ctx,
  560. 'visible-child-of-hidden-parent',
  561. '/work',
  562. 20,
  563. hiddenParent.id,
  564. )
  565. FakeQuery.sessionSearch = () => Promise.resolve({
  566. items: [sessionHit(visibleChild.id, '/work', 'must not be discoverable', hiddenParent.id)],
  567. })
  568. const hidden = await mounted.call('session_search', {
  569. query: 'needle',
  570. parent_session_ids: [hiddenParent.id],
  571. })
  572. const missing = await mounted.call('session_search', {
  573. query: 'needle',
  574. parent_session_ids: ['guessed-missing-parent'],
  575. })
  576. expect(hidden).toEqual(missing)
  577. expect(text(hidden)).toBe('No prior session matches found.')
  578. expect(JSON.stringify(hidden)).not.toContain(visibleChild.id)
  579. expect(FakeQuery.sessionRequests).toEqual([])
  580. })
  581. it('deduplicates parent guesses and sends only authorized parents plus the root marker', async () => {
  582. const mounted = await mount()
  583. const visible = createSession(mounted.ctx, 'visible-parent', '/work')
  584. const hidden = createSession(mounted.ctx, 'hidden-parent-filter-secret', '/outside')
  585. await mounted.call('session_search', {
  586. query: 'needle',
  587. parent_session_ids: [visible.id, hidden.id, visible.id, 'missing-parent'],
  588. include_root_sessions: true,
  589. })
  590. await mounted.call('session_search', {
  591. query: 'needle',
  592. parent_session_ids: [hidden.id],
  593. include_root_sessions: true,
  594. })
  595. await mounted.call('session_search', {
  596. query: 'needle',
  597. parent_session_ids: ['missing-parent'],
  598. include_root_sessions: true,
  599. })
  600. const parentValues = FakeQuery.sessionRequests.map(request =>
  601. request.sessionFilters?.find(filter => filter.kind === 'parent'))
  602. expect(parentValues).toEqual([
  603. { kind: 'parent', values: [visible.id, null] },
  604. { kind: 'parent', values: [null] },
  605. { kind: 'parent', values: [null] },
  606. ])
  607. })
  608. it('rejects unrequested or unauthorized records returned during parent preauthorization', async () => {
  609. const mounted = await mount()
  610. const requested = SessionId('requested-parent')
  611. vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions').mockResolvedValueOnce([
  612. { header: header('unrequested-parent', '/work'), live: true, persisted: false },
  613. { header: header(requested, '/outside'), live: true, persisted: false },
  614. ])
  615. const result = await mounted.call('session_search', {
  616. query: 'needle',
  617. parent_session_ids: [requested],
  618. })
  619. expect(text(result)).toBe('No prior session matches found.')
  620. expect(FakeQuery.sessionRequests).toEqual([])
  621. })
  622. it('validates every other search filter before parent preauthorization', async () => {
  623. const mounted = await mount()
  624. const filterSessions = vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions')
  625. const result = await mounted.call('session_search', {
  626. query: 'needle',
  627. parent_session_ids: ['guessed-parent'],
  628. event_seq_from: -1,
  629. })
  630. expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_FILTER')
  631. expect(filterSessions).not.toHaveBeenCalled()
  632. expect(FakeQuery.sessionRequests).toEqual([])
  633. })
  634. it('sanitizes parent preauthorization failures without calling search', async () => {
  635. const mounted = await mount()
  636. const secret = 'conflict at hidden-parent-preauthorization-secret'
  637. vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions').mockRejectedValueOnce(
  638. new SessionQueryError(secret, 'SESSION_QUERY_SOURCE_CONFLICT'),
  639. )
  640. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  641. const result = await mounted.call('session_search', {
  642. query: 'needle',
  643. parent_session_ids: ['guessed-parent'],
  644. })
  645. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  646. expect(text(result)).toBe('Error: session query operation failed')
  647. expect(JSON.stringify(result)).not.toContain(secret)
  648. expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret))
  649. expect(FakeQuery.sessionRequests).toEqual([])
  650. })
  651. it('sanitizes direct-target authorization failures before event search', async () => {
  652. const mounted = await mount()
  653. const target = createSession(mounted.ctx, 'authorization-failure-target', '/work')
  654. const secret = 'conflict with hidden-authorization-session-secret'
  655. vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions').mockRejectedValueOnce(
  656. new SessionQueryError(secret, 'SESSION_QUERY_SOURCE_CONFLICT'),
  657. )
  658. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  659. const result = await mounted.call('session_event_search', {
  660. session_id: target.id,
  661. query: 'needle',
  662. })
  663. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  664. expect(text(result)).toBe('Error: session query operation failed')
  665. expect(JSON.stringify(result)).not.toContain(secret)
  666. expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret))
  667. expect(FakeQuery.eventRequests).toEqual([])
  668. })
  669. it('preserves parent-preauthorization cancellation and waits for cleanup without logging it', async () => {
  670. const mounted = await mount()
  671. const controller = new AbortController()
  672. const cancellation = new SessionQueryError(
  673. 'parent preauthorization cancelled',
  674. 'SESSION_QUERY_ABORTED',
  675. )
  676. const started = Promise.withResolvers<undefined>()
  677. const abortObserved = Promise.withResolvers<undefined>()
  678. const cleanup = Promise.withResolvers<undefined>()
  679. let active = false
  680. vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions')
  681. .mockImplementation(async (_filters, signal) => {
  682. if (signal === undefined) throw new Error('expected parent-authorization signal')
  683. active = true
  684. const aborted = new Promise<void>((resolve) => {
  685. signal.addEventListener('abort', () => { resolve() }, { once: true })
  686. })
  687. started.resolve(undefined)
  688. await aborted
  689. abortObserved.resolve(undefined)
  690. await cleanup.promise
  691. active = false
  692. signal.throwIfAborted()
  693. return []
  694. })
  695. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  696. const pending = mounted.call('session_search', {
  697. query: 'needle',
  698. parent_session_ids: ['guessed-parent'],
  699. }, { signal: controller.signal })
  700. let settled = false
  701. void pending.then(
  702. () => { settled = true },
  703. () => { settled = true },
  704. )
  705. await started.promise
  706. controller.abort(cancellation)
  707. await abortObserved.promise
  708. expect(settled).toBe(false)
  709. expect(active).toBe(true)
  710. expect(FakeQuery.sessionRequests).toEqual([])
  711. cleanup.resolve(undefined)
  712. const result = await pending
  713. expect(active).toBe(false)
  714. expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED')
  715. expect(text(result)).toBe('Error: parent preauthorization cancelled')
  716. expect(warn).not.toHaveBeenCalled()
  717. })
  718. it('redacts an unauthorized ancestor and prunes unauthorized descendant subtrees without hidden ids', async () => {
  719. const mounted = await mount()
  720. const hiddenParent = createSession(mounted.ctx, 'hidden-parent-secret', '/outside')
  721. const target = createSession(mounted.ctx, 'target', '/work', 20, hiddenParent.id)
  722. const visible = createSession(mounted.ctx, 'visible-child', '/work', 30, target.id)
  723. const hidden = createSession(mounted.ctx, 'hidden-child-secret', '/outside', 40, target.id)
  724. createSession(mounted.ctx, 'hidden-grandchild-secret', '/work', 50, hidden.id)
  725. FakeQuery.titles.set(target.id, 'Target title')
  726. FakeQuery.titles.set(visible.id, 'Visible title')
  727. const result = await mounted.call('session_trace', { session_id: target.id })
  728. const output = text(result)
  729. expect(output).toContain('Target title')
  730. expect(output).toContain('visible-child')
  731. expect(output).toContain('[outside workspace boundary]')
  732. expect(output).toContain('[outside workspace subtree]')
  733. expect(output).not.toContain('hidden-parent-secret')
  734. expect(output).not.toContain('hidden-child-secret')
  735. expect(output).not.toContain('hidden-grandchild-secret')
  736. })
  737. it('sanitizes a real outside-workspace ancestor cycle before the lineage error reaches the model', async () => {
  738. const mounted = await mount()
  739. const hiddenA = SessionId('hidden-cycle-a-secret')
  740. const hiddenB = SessionId('hidden-cycle-b-secret')
  741. createSession(mounted.ctx, hiddenA, '/outside', 2, hiddenB)
  742. createSession(mounted.ctx, hiddenB, '/outside', 3, hiddenA)
  743. const target = createSession(mounted.ctx, 'visible-cycle-target', '/work', 4, hiddenA)
  744. const result = await mounted.call('session_trace', { session_id: target.id })
  745. expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_LINEAGE')
  746. expect(text(result)).toBe('Error: session lineage is invalid')
  747. const presentation = JSON.stringify(result)
  748. expect(presentation).not.toContain(hiddenA)
  749. expect(presentation).not.toContain(hiddenB)
  750. })
  751. it.each([
  752. {
  753. name: 'sensitive source conflict',
  754. makeError: () => new SessionQueryError(
  755. 'conflict with hidden-lineage-session-secret',
  756. 'SESSION_QUERY_SOURCE_CONFLICT',
  757. ),
  758. code: 'SESSION_QUERY_TOOL_FAILED',
  759. message: 'session query operation failed',
  760. secret: 'hidden-lineage-session-secret',
  761. },
  762. {
  763. name: 'typed query error',
  764. makeError: () => new SessionQueryError(
  765. 'unrelated persistence failure',
  766. 'SESSION_QUERY_PERSISTENCE_FAILED',
  767. ),
  768. code: 'SESSION_QUERY_PERSISTENCE_FAILED',
  769. message: 'session history storage is unavailable',
  770. secret: 'unrelated persistence failure',
  771. },
  772. {
  773. name: 'plain error',
  774. makeError: () => new Error('unrelated plain trace failure'),
  775. code: 'SESSION_QUERY_TOOL_FAILED',
  776. message: 'session query operation failed',
  777. secret: 'unrelated plain trace failure',
  778. },
  779. ])('sanitizes an unrelated $name from lineage tracing', async ({ makeError, code, message, secret }) => {
  780. const mounted = await mount()
  781. const target = createSession(mounted.ctx, 'trace-failure-target', '/work')
  782. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  783. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockRejectedValueOnce(makeError())
  784. const result = await mounted.call('session_trace', { session_id: target.id })
  785. expect(errorCode(result)).toBe(code)
  786. expect(text(result)).toBe(`Error: ${message}`)
  787. expect(JSON.stringify(result)).not.toContain(secret)
  788. expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret))
  789. })
  790. it.each([
  791. 'session_event_trace',
  792. 'session_event_read',
  793. ] as const)('sanitizes typed service diagnostics from %s', async (toolName) => {
  794. const mounted = await mount()
  795. const target = createSession(mounted.ctx, `${toolName}-failure-target`, '/work')
  796. target.append(
  797. 'user/message',
  798. { content: [{ type: 'text', text: 'event' }], source: { kind: 'user' } },
  799. { surfaceOp: 'append' },
  800. )
  801. const secret = `event missing beside hidden-${toolName}-secret`
  802. const failure = new SessionQueryError(secret, 'SESSION_QUERY_EVENT_NOT_FOUND')
  803. if (toolName === 'session_event_trace') {
  804. vi.spyOn(mounted.ctx.sessionQuery, 'traceEvent').mockRejectedValueOnce(failure)
  805. } else {
  806. vi.spyOn(mounted.ctx.sessionQuery, 'readEvent').mockRejectedValueOnce(failure)
  807. }
  808. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  809. const result = await mounted.call(toolName, { session_id: target.id, seq: 0 })
  810. expect(errorCode(result)).toBe('SESSION_QUERY_EVENT_NOT_FOUND')
  811. expect(text(result)).toBe('Error: session event was not found')
  812. expect(JSON.stringify(result)).not.toContain(secret)
  813. expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret))
  814. })
  815. it.each([
  816. 'session_trace',
  817. 'session_event_trace',
  818. 'session_event_read',
  819. ] as const)('forwards the exact signal to %s and waits for service cleanup', async (toolName) => {
  820. const mounted = await mount()
  821. const target = createSession(mounted.ctx, `cancelled-${toolName}`, '/work')
  822. target.append(
  823. 'user/message',
  824. { content: [{ type: 'text', text: 'pending exact read' }], source: { kind: 'user' } },
  825. { surfaceOp: 'append' },
  826. )
  827. const controller = new AbortController()
  828. const cancellation = new SessionQueryError(
  829. `${toolName} cancelled`,
  830. 'SESSION_QUERY_ABORTED',
  831. )
  832. const started = Promise.withResolvers<undefined>()
  833. const abortObserved = Promise.withResolvers<undefined>()
  834. const cleanup = Promise.withResolvers<undefined>()
  835. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  836. let observedSignal: AbortSignal | undefined
  837. let active = false
  838. const holdExactRead = async (signal?: AbortSignal): Promise<never> => {
  839. if (signal === undefined) throw new Error('expected exact tool execution signal')
  840. observedSignal = signal
  841. active = true
  842. const aborted = new Promise<void>((resolve) => {
  843. signal.addEventListener('abort', () => { resolve() }, { once: true })
  844. })
  845. started.resolve(undefined)
  846. await aborted
  847. abortObserved.resolve(undefined)
  848. await cleanup.promise
  849. active = false
  850. signal.throwIfAborted()
  851. throw new Error('unreachable after exact tool cancellation')
  852. }
  853. if (toolName === 'session_trace') {
  854. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession')
  855. .mockImplementation((_sessionId, signal) => holdExactRead(signal))
  856. } else if (toolName === 'session_event_trace') {
  857. vi.spyOn(mounted.ctx.sessionQuery, 'traceEvent')
  858. .mockImplementation((_request, signal) => holdExactRead(signal))
  859. } else {
  860. vi.spyOn(mounted.ctx.sessionQuery, 'readEvent')
  861. .mockImplementation((_request, signal) => holdExactRead(signal))
  862. }
  863. const args = toolName === 'session_trace'
  864. ? { session_id: target.id }
  865. : { session_id: target.id, seq: 0 }
  866. const pending = mounted.call(toolName, args, { signal: controller.signal })
  867. let settled = false
  868. void pending.then(
  869. () => { settled = true },
  870. () => { settled = true },
  871. )
  872. await started.promise
  873. controller.abort(cancellation)
  874. await abortObserved.promise
  875. expect(settled).toBe(false)
  876. expect(active).toBe(true)
  877. expect(observedSignal).toBe(controller.signal)
  878. cleanup.resolve(undefined)
  879. const result = await pending
  880. expect(active).toBe(false)
  881. expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED')
  882. expect(text(result)).toBe(`Error: ${toolName} cancelled`)
  883. expect(warn).not.toHaveBeenCalled()
  884. })
  885. it('preserves caller cancellation while a lineage trace is pending', async () => {
  886. const mounted = await mount()
  887. const target = createSession(mounted.ctx, 'cancelled-trace-target', '/work')
  888. const trace = await mounted.ctx.sessionQuery.traceSession(target.id)
  889. let started!: () => void
  890. const traceStarted = new Promise<void>((resolve) => { started = resolve })
  891. let finish!: (value: typeof trace) => void
  892. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockImplementation(() => {
  893. started()
  894. return new Promise<typeof trace>((resolve) => { finish = resolve })
  895. })
  896. const controller = new AbortController()
  897. const cancellation = new SessionQueryError('lineage trace cancelled', 'SESSION_QUERY_ABORTED')
  898. const pending = mounted.call(
  899. 'session_trace',
  900. { session_id: target.id },
  901. { signal: controller.signal },
  902. )
  903. await traceStarted
  904. controller.abort(cancellation)
  905. finish(trace)
  906. const result = await pending
  907. expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED')
  908. expect(text(result)).toBe('Error: lineage trace cancelled')
  909. })
  910. it('gives caller cancellation precedence when a pending trace rejects with invalid lineage', async () => {
  911. const mounted = await mount()
  912. const target = createSession(mounted.ctx, 'cancelled-invalid-lineage-target', '/work')
  913. let started!: () => void
  914. const traceStarted = new Promise<void>((resolve) => { started = resolve })
  915. let fail!: (error: SessionQueryError) => void
  916. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockImplementation(() => {
  917. started()
  918. return new Promise((_resolve, reject) => { fail = reject })
  919. })
  920. const controller = new AbortController()
  921. const cancellation = new SessionQueryError('lineage trace cancelled first', 'SESSION_QUERY_ABORTED')
  922. const pending = mounted.call(
  923. 'session_trace',
  924. { session_id: target.id },
  925. { signal: controller.signal },
  926. )
  927. await traceStarted
  928. controller.abort(cancellation)
  929. fail(new SessionQueryError(
  930. 'session lineage contains a cycle at "hidden-race-secret"',
  931. 'SESSION_QUERY_INVALID_LINEAGE',
  932. ))
  933. const result = await pending
  934. expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED')
  935. expect(text(result)).toBe('Error: lineage trace cancelled first')
  936. expect(JSON.stringify(result)).not.toContain('hidden-race-secret')
  937. })
  938. it('renders branching descendants in source preorder with one indented marker per pruned subtree', async () => {
  939. const mounted = await mount()
  940. const target = createSession(mounted.ctx, 'branch-target', '/work', 20)
  941. const [targetRecord] = await mounted.ctx.sessionQuery.filterSessions([{
  942. kind: 'id',
  943. values: [target.id],
  944. }])
  945. if (targetRecord === undefined) throw new Error('expected target record')
  946. const firstId = SessionId('branch-first')
  947. const nestedId = SessionId('branch-nested')
  948. const hiddenId = SessionId('branch-hidden-secret')
  949. const hiddenDescendantId = SessionId('branch-hidden-descendant-secret')
  950. const lastId = SessionId('branch-last')
  951. const descendants: SessionLineageNode[] = [
  952. {
  953. session: { ...targetRecord, header: header(firstId, '/work', 30) },
  954. descendants: [
  955. {
  956. session: { ...targetRecord, header: header(nestedId, '/work', 40) },
  957. descendants: [],
  958. },
  959. {
  960. session: { ...targetRecord, header: header(hiddenId, '/outside', 50) },
  961. descendants: [{
  962. session: { ...targetRecord, header: header(hiddenDescendantId, '/work', 60) },
  963. descendants: [],
  964. }],
  965. },
  966. ],
  967. },
  968. {
  969. session: { ...targetRecord, header: header(lastId, '/work', 70) },
  970. descendants: [],
  971. },
  972. ]
  973. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValue({
  974. target: targetRecord,
  975. ancestors: [],
  976. descendants,
  977. complete: true,
  978. root: targetRecord,
  979. })
  980. const titleReads: SessionIdValue[] = []
  981. vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockImplementation((sessionIds) => {
  982. titleReads.push(...sessionIds)
  983. return Promise.resolve([...new Set(sessionIds)].map(sessionId => ({
  984. sessionId,
  985. status: 'fulfilled' as const,
  986. value: { session: header(sessionId, '/work') },
  987. })))
  988. })
  989. const output = text(await mounted.call('session_trace', { session_id: target.id }))
  990. expect(output.slice(output.indexOf('Descendants:'))).toBe([
  991. 'Descendants:',
  992. '- branch-first — untitled | 1970-01-01T00:00:00.030Z | live',
  993. ' - branch-nested — untitled | 1970-01-01T00:00:00.040Z | live',
  994. ' - [outside workspace subtree]',
  995. '- branch-last — untitled | 1970-01-01T00:00:00.070Z | live',
  996. ].join('\n'))
  997. expect(titleReads).toEqual([target.id, firstId, nestedId, lastId])
  998. })
  999. it('renders authorized ancestors and an unresolved lineage boundary without leaking it', async () => {
  1000. const mounted = await mount()
  1001. const root = createSession(mounted.ctx, 'visible-root', '/work', 5)
  1002. const target = createSession(mounted.ctx, 'visible-target', '/work', 6, root.id)
  1003. const complete = text(await mounted.call('session_trace', { session_id: target.id }))
  1004. expect(complete).toContain('visible-root')
  1005. const missingParent = SessionId('missing-parent-secret')
  1006. const incomplete = createSession(mounted.ctx, 'incomplete-target', '/work', 7, missingParent)
  1007. const redacted = text(await mounted.call('session_trace', { session_id: incomplete.id }))
  1008. expect(redacted).toContain('[outside workspace boundary]')
  1009. expect(redacted).not.toContain(missingParent)
  1010. })
  1011. it('renders unavailable trace records and keeps a self-id descendant authorized', async () => {
  1012. const mounted = await mount()
  1013. const target = createSession(mounted.ctx, 'trace-unavailable', '/work')
  1014. const [record] = await mounted.ctx.sessionQuery.filterSessions([{ kind: 'id', values: [target.id] }])
  1015. const [callerRecord] = await mounted.ctx.sessionQuery.filterSessions([{
  1016. kind: 'id',
  1017. values: [mounted.caller.id],
  1018. }])
  1019. if (record === undefined || callerRecord === undefined) throw new Error('expected live records')
  1020. const unavailable = { ...record, live: false, persisted: false }
  1021. const persisted = { ...callerRecord, live: false, persisted: true }
  1022. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValue({
  1023. target: unavailable,
  1024. ancestors: [],
  1025. descendants: [{ session: persisted, descendants: [] }],
  1026. complete: true,
  1027. root: unavailable,
  1028. })
  1029. const output = text(await mounted.call('session_trace', { session_id: target.id }))
  1030. expect(output).toContain('Availability: unavailable')
  1031. expect(output).toContain(mounted.caller.id)
  1032. expect(output).toContain('persisted')
  1033. })
  1034. it('rejects every payload observation whose target moved after pre-authorization', async () => {
  1035. const mounted = await mount()
  1036. const target = createSession(mounted.ctx, 'moving-target', '/work')
  1037. target.append(
  1038. 'user/message',
  1039. { content: [{ type: 'text', text: 'authorized payload' }], source: { kind: 'user' } },
  1040. { surfaceOp: 'append' },
  1041. )
  1042. const movedHeader = header(target.id, '/outside')
  1043. FakeQuery.eventSearch = () => Promise.resolve({
  1044. session: movedHeader,
  1045. items: [eventHit(target.id, 0, 'secret event hit')],
  1046. })
  1047. const search = await mounted.call('session_event_search', {
  1048. session_id: target.id,
  1049. query: 'secret',
  1050. })
  1051. expect(errorCode(search)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1052. expect(text(search)).not.toContain('secret event hit')
  1053. const lineage = await mounted.ctx.sessionQuery.traceSession(target.id)
  1054. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValueOnce({
  1055. ...lineage,
  1056. target: { ...lineage.target, header: movedHeader },
  1057. })
  1058. expect(errorCode(await mounted.call('session_trace', { session_id: target.id })))
  1059. .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1060. const eventTrace = await mounted.ctx.sessionQuery.traceEvent({ sessionId: target.id, seq: 0 })
  1061. vi.spyOn(mounted.ctx.sessionQuery, 'traceEvent').mockResolvedValueOnce({
  1062. ...eventTrace,
  1063. session: movedHeader,
  1064. })
  1065. expect(errorCode(await mounted.call('session_event_trace', { session_id: target.id, seq: 0 })))
  1066. .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1067. const eventWindow = await mounted.ctx.sessionQuery.readEvent({ sessionId: target.id, seq: 0 })
  1068. vi.spyOn(mounted.ctx.sessionQuery, 'readEvent').mockResolvedValueOnce({
  1069. ...eventWindow,
  1070. session: movedHeader,
  1071. })
  1072. expect(errorCode(await mounted.call('session_event_read', { session_id: target.id, seq: 0 })))
  1073. .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1074. FakeQuery.sessionSearch = () => Promise.resolve({
  1075. items: [sessionHit(target.id, '/work', 'safe hit')],
  1076. })
  1077. vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockResolvedValueOnce([{
  1078. sessionId: target.id,
  1079. status: 'fulfilled',
  1080. value: {
  1081. session: movedHeader,
  1082. title: {
  1083. title: 'secret moved title',
  1084. messageSeqs: [],
  1085. source: { kind: 'fallback' },
  1086. eventSeq: 0,
  1087. updatedAt: 1,
  1088. },
  1089. },
  1090. }])
  1091. const titled = await mounted.call('session_search', { query: 'safe' })
  1092. expect(errorCode(titled)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1093. expect(text(titled)).not.toContain('secret moved title')
  1094. })
  1095. it('rejects a default self read when its same-id observation moved after caller capture', async () => {
  1096. const mounted = await mount()
  1097. const appendLegacy = mounted.caller.append.bind(mounted.caller) as unknown as (
  1098. type: string,
  1099. data: unknown,
  1100. ) => Session['events'][number]
  1101. const secret = appendLegacy(
  1102. 'context/message',
  1103. {
  1104. content: [{ type: 'text', text: 'same-id moved secret' }],
  1105. source: { kind: 'plugin', plugin: 'test' },
  1106. },
  1107. )
  1108. const window = await mounted.ctx.sessionQuery.readEvent({
  1109. sessionId: mounted.caller.id,
  1110. seq: secret.seq,
  1111. })
  1112. vi.spyOn(mounted.ctx.sessionQuery, 'readEvent').mockResolvedValueOnce({
  1113. ...window,
  1114. session: header(mounted.caller.id, '/outside'),
  1115. })
  1116. const denied = await mounted.call('session_event_read', { seq: secret.seq })
  1117. expect(errorCode(denied)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1118. expect(text(denied)).not.toContain('same-id moved secret')
  1119. })
  1120. })
  1121. describe('search paging, prior-history bounds, titles, and cancellation', () => {
  1122. it('drains hidden internal pages to the authorized non-self cap and masks an unauthorized parent id', async () => {
  1123. const mounted = await mount({ maxSearchResults: 2 })
  1124. const outside = createSession(mounted.ctx, 'outside-parent-secret', '/outside')
  1125. const a = createSession(mounted.ctx, 'a', '/work')
  1126. const b = createSession(mounted.ctx, 'b', '/work')
  1127. FakeQuery.titles.set(a.id, 'Alpha')
  1128. FakeQuery.titles.set(b.id, 'Beta')
  1129. const c1 = SessionSearchCursor('c1')
  1130. const c2 = SessionSearchCursor('c2')
  1131. FakeQuery.sessionSearch = (request) => {
  1132. if (request.cursor === undefined) {
  1133. return Promise.resolve({
  1134. items: [
  1135. sessionHit('caller', '/work'),
  1136. sessionHit('unauthorized', '/outside'),
  1137. ],
  1138. nextCursor: c1,
  1139. })
  1140. }
  1141. if (request.cursor === c1) {
  1142. return Promise.resolve({
  1143. items: [sessionHit('a', '/work', 'first', outside.id)],
  1144. nextCursor: c2,
  1145. })
  1146. }
  1147. return Promise.resolve({
  1148. items: [
  1149. sessionHit('b', '/work', 'second'),
  1150. sessionHit('additional-authorized', '/work', 'third'),
  1151. ],
  1152. })
  1153. }
  1154. const result = await mounted.call('session_search', { query: 'needle' })
  1155. const output = text(result)
  1156. expect(FakeQuery.sessionRequests).toHaveLength(3)
  1157. expect(FakeQuery.sessionRequests.every(request => request.limit === undefined)).toBe(true)
  1158. expect(FakeQuery.sessionRequests.map(request => request.cursor)).toEqual([undefined, c1, c2])
  1159. expect(output).toContain('Session a — Alpha')
  1160. expect(output).toContain('Session b — Beta')
  1161. expect(output).toContain('Parent: [outside workspace]')
  1162. expect(output).not.toContain('outside-parent-secret')
  1163. expect(output).toContain('Result cap reached')
  1164. })
  1165. it('does not report a cap when only rejected hits remain after the authorized limit', async () => {
  1166. const mounted = await mount({ maxSearchResults: 1 })
  1167. const cursor = SessionSearchCursor('rejected-tail')
  1168. FakeQuery.sessionSearch = request => request.cursor === undefined
  1169. ? Promise.resolve({
  1170. items: [sessionHit('authorized', '/work')],
  1171. nextCursor: cursor,
  1172. })
  1173. : Promise.resolve({
  1174. items: [
  1175. sessionHit(mounted.caller.id, '/work'),
  1176. sessionHit('outside', '/outside'),
  1177. ],
  1178. })
  1179. const output = text(await mounted.call('session_search', { query: 'needle' }))
  1180. expect(FakeQuery.sessionRequests.map(request => request.cursor)).toEqual([undefined, cursor])
  1181. expect(output).toContain('Session authorized')
  1182. expect(output).not.toContain('Result cap reached')
  1183. })
  1184. it.each([
  1185. {
  1186. toolName: 'session_search',
  1187. args: { query: 'needle' },
  1188. secrets: [
  1189. 'session source conflict at hidden-search-session-secret',
  1190. 'hidden-search-cause-secret',
  1191. ],
  1192. failure: () => new SessionQueryError(
  1193. 'session source conflict at hidden-search-session-secret',
  1194. 'SESSION_QUERY_SOURCE_CONFLICT',
  1195. { cause: new Error('hidden-search-cause-secret') },
  1196. ),
  1197. },
  1198. {
  1199. toolName: 'session_event_search',
  1200. args: { query: 'needle' },
  1201. secrets: [
  1202. 'plain event provider failure at hidden-event-session-secret',
  1203. 'hidden-event-cause-secret',
  1204. ],
  1205. failure: () => new Error(
  1206. 'plain event provider failure at hidden-event-session-secret',
  1207. { cause: 'hidden-event-cause-secret' },
  1208. ),
  1209. },
  1210. ] as const)('sanitizes $toolName provider diagnostics', async ({ toolName, args, secrets, failure }) => {
  1211. const mounted = await mount()
  1212. if (toolName === 'session_search') {
  1213. FakeQuery.sessionSearch = () => Promise.reject(failure())
  1214. } else {
  1215. FakeQuery.eventSearch = () => Promise.reject(failure())
  1216. }
  1217. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1218. const result = await mounted.call(toolName, args)
  1219. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  1220. expect(text(result)).toBe('Error: session query operation failed')
  1221. for (const secret of secrets) {
  1222. expect(JSON.stringify(result)).not.toContain(secret)
  1223. expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret))
  1224. }
  1225. })
  1226. it.each([
  1227. {
  1228. name: 'a hostile prototype trap',
  1229. secrets: ['proxy payload secret', 'getPrototypeOf secondary secret'],
  1230. diagnostic: '[unprintable session query failure]',
  1231. failure: (): unknown => new Proxy(
  1232. { payload: 'proxy payload secret' },
  1233. {
  1234. getPrototypeOf() {
  1235. throw new Error('getPrototypeOf secondary secret')
  1236. },
  1237. },
  1238. ),
  1239. },
  1240. {
  1241. name: 'a throwing stack getter',
  1242. secrets: ['stack primary secret', 'stack getter secondary secret'],
  1243. diagnostic: '[unprintable session query failure]',
  1244. failure: (): unknown => {
  1245. const error = new Error('stack primary secret')
  1246. Object.defineProperty(error, 'stack', {
  1247. get() {
  1248. throw new Error('stack getter secondary secret')
  1249. },
  1250. })
  1251. return error
  1252. },
  1253. },
  1254. {
  1255. name: 'a throwing cause getter',
  1256. secrets: ['cause primary secret', 'cause getter secondary secret'],
  1257. diagnostic: '[unprintable session query failure]',
  1258. failure: (): unknown => {
  1259. const error = new Error('cause primary secret')
  1260. Object.defineProperty(error, 'cause', {
  1261. get() {
  1262. throw new Error('cause getter secondary secret')
  1263. },
  1264. })
  1265. return error
  1266. },
  1267. },
  1268. {
  1269. name: 'throwing string coercion',
  1270. secrets: ['string payload secret', 'string coercion secondary secret'],
  1271. diagnostic: '[unprintable session query failure]',
  1272. failure: (): unknown => ({
  1273. payload: 'string payload secret',
  1274. [Symbol.toPrimitive]() {
  1275. throw new Error('string coercion secondary secret')
  1276. },
  1277. }),
  1278. },
  1279. {
  1280. name: 'a throwing code getter',
  1281. secrets: ['code primary secret', 'code getter secondary secret'],
  1282. diagnostic: 'code primary secret',
  1283. failure: (): unknown => {
  1284. const error = new SessionQueryError(
  1285. 'code primary secret',
  1286. 'SESSION_QUERY_PERSISTENCE_FAILED',
  1287. )
  1288. Object.defineProperty(error, 'code', {
  1289. get() {
  1290. throw new Error('code getter secondary secret')
  1291. },
  1292. })
  1293. return error
  1294. },
  1295. },
  1296. {
  1297. name: 'an unknown string code',
  1298. secrets: ['unknown code primary secret', '__proto__'],
  1299. diagnostic: 'unknown code primary secret',
  1300. failure: (): unknown => {
  1301. const error = new SessionQueryError(
  1302. 'unknown code primary secret',
  1303. 'SESSION_QUERY_PERSISTENCE_FAILED',
  1304. )
  1305. Object.defineProperty(error, 'code', { value: '__proto__' })
  1306. return error
  1307. },
  1308. },
  1309. {
  1310. name: 'a non-string code',
  1311. secrets: ['non-string code primary secret', 'non-string code secondary secret'],
  1312. diagnostic: 'non-string code primary secret',
  1313. failure: (): unknown => {
  1314. const error = new SessionQueryError(
  1315. 'non-string code primary secret',
  1316. 'SESSION_QUERY_PERSISTENCE_FAILED',
  1317. )
  1318. Object.defineProperty(error, 'code', {
  1319. value: {
  1320. toString() {
  1321. throw new Error('non-string code secondary secret')
  1322. },
  1323. },
  1324. })
  1325. return error
  1326. },
  1327. },
  1328. ])('fails generic when inspecting $name is unsafe', async ({ secrets, diagnostic, failure }) => {
  1329. const mounted = await mount()
  1330. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- hostile unknown rejection is the scenario
  1331. FakeQuery.sessionSearch = () => Promise.reject(failure())
  1332. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1333. const result = await mounted.call('session_search', { query: 'needle' })
  1334. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  1335. expect(text(result)).toBe('Error: session query operation failed')
  1336. for (const secret of secrets) expect(JSON.stringify(result)).not.toContain(secret)
  1337. expect(warn).toHaveBeenCalledWith(expect.stringContaining(diagnostic))
  1338. })
  1339. it('retains a fixed safe typed failure when only its nested diagnostic is unprintable', async () => {
  1340. const mounted = await mount()
  1341. const primary = 'typed outer diagnostic secret'
  1342. const nested = 'nested prototype secondary secret'
  1343. const cause = new Proxy(
  1344. {},
  1345. {
  1346. getPrototypeOf() {
  1347. throw new Error(nested)
  1348. },
  1349. },
  1350. )
  1351. FakeQuery.sessionSearch = () => Promise.reject(
  1352. new SessionQueryError(
  1353. primary,
  1354. 'SESSION_QUERY_PERSISTENCE_FAILED',
  1355. { cause },
  1356. ),
  1357. )
  1358. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1359. const result = await mounted.call('session_search', { query: 'needle' })
  1360. expect(errorCode(result)).toBe('SESSION_QUERY_PERSISTENCE_FAILED')
  1361. expect(text(result)).toBe('Error: session history storage is unavailable')
  1362. expect(JSON.stringify(result)).not.toContain(primary)
  1363. expect(JSON.stringify(result)).not.toContain(nested)
  1364. expect(warn).toHaveBeenCalledWith(expect.stringContaining('[unprintable session query failure]'))
  1365. })
  1366. it('logs an inspectable cyclic cause chain without exposing it', async () => {
  1367. const mounted = await mount()
  1368. const outer = new Error('cyclic outer secret')
  1369. const inner = new Error('cyclic inner secret')
  1370. Object.defineProperty(outer, 'cause', { value: inner })
  1371. Object.defineProperty(inner, 'cause', { value: outer })
  1372. FakeQuery.sessionSearch = () => Promise.reject(outer)
  1373. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1374. const result = await mounted.call('session_search', { query: 'needle' })
  1375. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  1376. expect(text(result)).toBe('Error: session query operation failed')
  1377. expect(JSON.stringify(result)).not.toContain('cyclic outer secret')
  1378. expect(JSON.stringify(result)).not.toContain('cyclic inner secret')
  1379. expect(warn).toHaveBeenCalledWith(expect.stringContaining('cyclic outer secret'))
  1380. expect(warn).toHaveBeenCalledWith(expect.stringContaining('cyclic inner secret'))
  1381. expect(warn).toHaveBeenCalledWith(expect.stringContaining('[circular error cause]'))
  1382. })
  1383. it('fails generic when internal warning logging throws', async () => {
  1384. const mounted = await mount()
  1385. const primary = 'typed persistence primary secret'
  1386. const secondary = 'logger warning secondary secret'
  1387. FakeQuery.sessionSearch = () => Promise.reject(
  1388. new SessionQueryError(primary, 'SESSION_QUERY_PERSISTENCE_FAILED'),
  1389. )
  1390. const warn = vi.spyOn(mounted.ctx.logger, 'warn')
  1391. .mockImplementation(() => undefined)
  1392. .mockImplementationOnce(() => {
  1393. throw new Error(secondary)
  1394. })
  1395. const result = await mounted.call('session_search', { query: 'needle' })
  1396. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  1397. expect(text(result)).toBe('Error: session query operation failed')
  1398. expect(JSON.stringify(result)).not.toContain(primary)
  1399. expect(JSON.stringify(result)).not.toContain(secondary)
  1400. expect(warn).toHaveBeenCalledTimes(1)
  1401. })
  1402. it('preserves stale-cursor diagnostics without transparently restarting', async () => {
  1403. const mounted = await mount({ maxSearchResults: 2 })
  1404. const cursor = SessionSearchCursor('stale-next')
  1405. FakeQuery.sessionSearch = request => request.cursor === undefined
  1406. ? Promise.resolve({ items: [], nextCursor: cursor })
  1407. : Promise.reject(new SessionQueryError('stale provider generation', 'SESSION_QUERY_STALE_CURSOR'))
  1408. const result = await mounted.call('session_search', { query: 'needle' })
  1409. expect(errorCode(result)).toBe('SESSION_QUERY_STALE_CURSOR')
  1410. expect(text(result)).toContain('retry the complete search call')
  1411. expect(FakeQuery.sessionRequests).toHaveLength(2)
  1412. })
  1413. it('rejects a repeated internal cursor instead of looping', async () => {
  1414. const mounted = await mount()
  1415. const cursor = SessionSearchCursor('repeat')
  1416. FakeQuery.sessionSearch = () => Promise.resolve({ items: [], nextCursor: cursor })
  1417. const result = await mounted.call('session_search', { query: 'needle' })
  1418. expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_CURSOR')
  1419. expect(text(result)).toBe('Error: session-search provider repeated a continuation cursor')
  1420. expect(FakeQuery.sessionRequests).toHaveLength(2)
  1421. })
  1422. it('renders authorized parent ids and all availability states', async () => {
  1423. const mounted = await mount({ maxSearchResults: 3 })
  1424. const parent = createSession(mounted.ctx, 'parent', '/work')
  1425. const child = createSession(mounted.ctx, 'child', '/work', 2, parent.id)
  1426. const callerChild = createSession(mounted.ctx, 'caller-child', '/work', 3, mounted.caller.id)
  1427. FakeQuery.sessionSearch = () => Promise.resolve({
  1428. items: [
  1429. { ...sessionHit(child.id, '/work', 'both', parent.id), live: true, persisted: true },
  1430. { ...sessionHit(callerChild.id, '/work', 'persisted', mounted.caller.id), live: false, persisted: true },
  1431. { ...sessionHit('unavailable', '/work', 'neither'), live: false, persisted: false },
  1432. ],
  1433. })
  1434. const output = text(await mounted.call('session_search', { query: 'needle' }))
  1435. expect(output).toContain('Parent: parent')
  1436. expect(output).toContain(`Parent: ${mounted.caller.id}`)
  1437. expect(output).toContain('Availability: live, persisted')
  1438. expect(output).toContain('Availability: persisted')
  1439. expect(output).toContain('Availability: unavailable')
  1440. })
  1441. it('intersects current-session search with the event before the latest step and leaves other targets unchanged', async () => {
  1442. const mounted = await mount()
  1443. FakeQuery.eventSearch = request => Promise.resolve({
  1444. session: header(request.sessionId, '/work'),
  1445. items: [eventHit(request.sessionId, 1)],
  1446. })
  1447. await mounted.call('session_event_search', {
  1448. query: 'prior',
  1449. seq_from: 0,
  1450. seq_to: 99,
  1451. })
  1452. expect(FakeQuery.eventRequests[0]?.filters).toContainEqual({ kind: 'seq', from: 0, to: 1 })
  1453. const other = createSession(mounted.ctx, 'other', '/work')
  1454. await mounted.call('session_event_search', {
  1455. session_id: other.id,
  1456. query: 'prior',
  1457. seq_from: 0,
  1458. seq_to: 99,
  1459. })
  1460. expect(FakeQuery.eventRequests[1]?.filters).toContainEqual({ kind: 'seq', from: 0, to: 99 })
  1461. })
  1462. it('returns no current-session hits without calling FTS when the user range starts in the active step', async () => {
  1463. const mounted = await mount()
  1464. const result = await mounted.call('session_event_search', {
  1465. query: 'prior',
  1466. seq_from: 2,
  1467. })
  1468. expect(result.isError).toBe(false)
  1469. expect(text(result)).toContain('No prior event matches found.')
  1470. expect(FakeQuery.eventRequests).toEqual([])
  1471. })
  1472. it('requires a current step boundary and drains event pages to a capped result', async () => {
  1473. const mounted = await mount({ maxSearchResults: 2 })
  1474. const noStep = createSession(mounted.ctx, 'no-step', '/work')
  1475. const missing = await mounted.call(
  1476. 'session_event_search',
  1477. { query: 'q' },
  1478. { agent: fakeAgent(noStep) },
  1479. )
  1480. expect(errorCode(missing)).toBe('SESSION_QUERY_TOOL_NO_CURRENT_STEP')
  1481. const other = createSession(mounted.ctx, 'paged-events', '/work')
  1482. const cursor = SessionSearchCursor('events-next')
  1483. FakeQuery.eventSearch = request => request.cursor === undefined
  1484. ? Promise.resolve({
  1485. session: header(other.id, '/work'),
  1486. items: [eventHit(other.id, 1)],
  1487. nextCursor: cursor,
  1488. })
  1489. : Promise.resolve({
  1490. session: header(other.id, '/work'),
  1491. items: [eventHit(other.id, 2), eventHit(other.id, 3)],
  1492. })
  1493. const result = await mounted.call('session_event_search', {
  1494. session_id: other.id,
  1495. query: 'q',
  1496. })
  1497. expect(FakeQuery.eventRequests.map(request => request.cursor)).toEqual([undefined, cursor])
  1498. expect(text(result)).toContain('Result cap reached')
  1499. })
  1500. it('preserves base results when a title read fails, annotates the code, and logs the full error', async () => {
  1501. const mounted = await mount()
  1502. const hit = createSession(mounted.ctx, 'hit', '/work')
  1503. const failure = new HarnessError('title backend failed', 'TITLE_BACKEND')
  1504. FakeQuery.titles.set(hit.id, failure)
  1505. FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] })
  1506. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1507. const result = await mounted.call('session_search', { query: 'needle' })
  1508. expect(result.isError).toBe(false)
  1509. expect(text(result)).toContain('untitled (title unavailable: SESSION_QUERY_TOOL_FAILED)')
  1510. expect(JSON.stringify(result)).not.toContain('title backend failed')
  1511. expect(warn).toHaveBeenCalledWith(expect.stringContaining('title backend failed'))
  1512. expect(warn).toHaveBeenCalledWith(expect.stringContaining('HarnessError'))
  1513. })
  1514. it('reports unknown title failures and preserves an Error without a stack', async () => {
  1515. const mounted = await mount()
  1516. const first = createSession(mounted.ctx, 'unknown-title', '/work')
  1517. const second = createSession(mounted.ctx, 'second-title-failure', '/work')
  1518. const stackless = new Error('stackless')
  1519. Object.defineProperty(stackless, 'stack', { value: undefined })
  1520. const readTitles = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots')
  1521. .mockResolvedValueOnce([
  1522. { sessionId: first.id, status: 'rejected', reason: 'string failure' },
  1523. { sessionId: second.id, status: 'rejected', reason: stackless },
  1524. ])
  1525. FakeQuery.sessionSearch = () => Promise.resolve({
  1526. items: [
  1527. sessionHit(first.id, '/work'),
  1528. sessionHit(second.id, '/work'),
  1529. ],
  1530. })
  1531. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1532. const result = await mounted.call('session_search', { query: 'needle' })
  1533. expect(text(result)).toContain('title unavailable: SESSION_QUERY_TOOL_FAILED')
  1534. expect(JSON.stringify(result)).not.toContain('string failure')
  1535. expect(JSON.stringify(result)).not.toContain('stackless')
  1536. expect(readTitles).toHaveBeenCalledTimes(1)
  1537. expect(readTitles.mock.calls[0]?.[0]).toEqual([first.id, second.id])
  1538. expect(warn).toHaveBeenCalledWith(expect.stringContaining('string failure'))
  1539. expect(warn).toHaveBeenCalledWith(expect.stringContaining('Error: stackless'))
  1540. })
  1541. it('isolates an unprintable per-title failure behind the generic unavailable marker', async () => {
  1542. const mounted = await mount()
  1543. const hit = createSession(mounted.ctx, 'hostile-title-failure', '/work')
  1544. const primary = 'per-title proxy payload secret'
  1545. const secondary = 'per-title prototype secondary secret'
  1546. const reason = new Proxy(
  1547. { payload: primary },
  1548. {
  1549. getPrototypeOf() {
  1550. throw new Error(secondary)
  1551. },
  1552. },
  1553. )
  1554. FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] })
  1555. vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockResolvedValueOnce([{
  1556. sessionId: hit.id,
  1557. status: 'rejected',
  1558. reason,
  1559. }])
  1560. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1561. const result = await mounted.call('session_search', { query: 'needle' })
  1562. expect(result.isError).toBe(false)
  1563. expect(text(result)).toContain('untitled (title unavailable: SESSION_QUERY_TOOL_FAILED)')
  1564. expect(JSON.stringify(result)).not.toContain(primary)
  1565. expect(JSON.stringify(result)).not.toContain(secondary)
  1566. expect(warn).toHaveBeenCalledWith(expect.stringContaining('[unprintable session query failure]'))
  1567. })
  1568. it('sanitizes a thrown batch-title service failure instead of rendering its diagnostic', async () => {
  1569. const mounted = await mount()
  1570. const hit = createSession(mounted.ctx, 'thrown-title-failure', '/work')
  1571. const secret = 'title batch failed beside hidden-title-session-secret'
  1572. FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] })
  1573. vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots')
  1574. .mockRejectedValueOnce(new Error(secret))
  1575. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1576. const result = await mounted.call('session_search', { query: 'needle' })
  1577. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED')
  1578. expect(text(result)).toBe('Error: session query operation failed')
  1579. expect(JSON.stringify(result)).not.toContain(secret)
  1580. expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret))
  1581. })
  1582. it('does not downgrade cancellation during title enrichment', async () => {
  1583. const mounted = await mount()
  1584. const hit = createSession(mounted.ctx, 'abort-title', '/work')
  1585. const controller = new AbortController()
  1586. const cancellation = new Error('cancelled title batch')
  1587. FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] })
  1588. let started!: () => void
  1589. const batchStarted = new Promise<void>((resolve) => { started = resolve })
  1590. const readTitles = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockImplementation((_ids, signal) => {
  1591. started()
  1592. return new Promise((_resolve, reject) => {
  1593. signal?.addEventListener('abort', () => { reject(cancellation) }, { once: true })
  1594. })
  1595. })
  1596. const pending = mounted.call('session_search', { query: 'needle' }, { signal: controller.signal })
  1597. await batchStarted
  1598. controller.abort(cancellation)
  1599. const result = await pending
  1600. expect(result.isError).toBe(true)
  1601. expect(text(result)).not.toContain('title unavailable')
  1602. expect(readTitles.mock.calls[0]?.[1]).toBe(controller.signal)
  1603. })
  1604. it('does not downgrade an authorization failure returned by title observation', async () => {
  1605. const mounted = await mount()
  1606. const hit = createSession(mounted.ctx, 'unauthorized-title-error', '/work')
  1607. const failure = new HarnessError(
  1608. 'title observation became unauthorized',
  1609. 'SESSION_QUERY_TOOL_UNAUTHORIZED',
  1610. )
  1611. FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] })
  1612. vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockResolvedValueOnce([{
  1613. sessionId: hit.id,
  1614. status: 'rejected',
  1615. reason: failure,
  1616. }])
  1617. const result = await mounted.call('session_search', { query: 'needle' })
  1618. expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED')
  1619. expect(text(result)).toBe('Error: session target is outside the caller workspace')
  1620. expect(JSON.stringify(result)).not.toContain('title observation became unauthorized')
  1621. expect(text(result)).not.toContain('title unavailable')
  1622. })
  1623. it('forwards caller cancellation into direct-target authorization and waits for cleanup', async () => {
  1624. const mounted = await mount()
  1625. const target = createSession(mounted.ctx, 'stalled-direct-authorization', '/work')
  1626. const controller = new AbortController()
  1627. const cancellation = new SessionQueryError(
  1628. 'direct-target authorization cancelled',
  1629. 'SESSION_QUERY_ABORTED',
  1630. )
  1631. const started = Promise.withResolvers<undefined>()
  1632. const abortObserved = Promise.withResolvers<undefined>()
  1633. const cleanup = Promise.withResolvers<undefined>()
  1634. let active = false
  1635. const filterSessions = vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions')
  1636. .mockImplementation(async (_filters, signal) => {
  1637. if (signal === undefined) throw new Error('expected authorization signal')
  1638. active = true
  1639. const aborted = new Promise<void>((resolve) => {
  1640. signal.addEventListener('abort', () => { resolve() }, { once: true })
  1641. })
  1642. started.resolve(undefined)
  1643. await aborted
  1644. abortObserved.resolve(undefined)
  1645. await cleanup.promise
  1646. active = false
  1647. signal.throwIfAborted()
  1648. return []
  1649. })
  1650. const pending = mounted.call(
  1651. 'session_event_search',
  1652. { session_id: target.id, query: 'needle' },
  1653. { signal: controller.signal },
  1654. )
  1655. let settled = false
  1656. void pending.then(
  1657. () => { settled = true },
  1658. () => { settled = true },
  1659. )
  1660. await started.promise
  1661. controller.abort(cancellation)
  1662. await abortObserved.promise
  1663. expect(settled).toBe(false)
  1664. expect(active).toBe(true)
  1665. expect(filterSessions.mock.calls[0]?.[1]).toBe(controller.signal)
  1666. expect(controller.signal.reason).toBe(cancellation)
  1667. expect(FakeQuery.eventRequests).toEqual([])
  1668. cleanup.resolve(undefined)
  1669. const result = await pending
  1670. expect(active).toBe(false)
  1671. expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED')
  1672. expect(text(result)).toBe('Error: direct-target authorization cancelled')
  1673. expect(FakeQuery.eventRequests).toEqual([])
  1674. })
  1675. it('forwards the search deadline into parent authorization and times out only after cleanup', async () => {
  1676. vi.useFakeTimers()
  1677. const timeoutMs = 1_234
  1678. const mounted = await mount({ searchTimeoutMs: timeoutMs }, '/work', true)
  1679. const parent = createSession(mounted.ctx, 'stalled-parent-authorization', '/work')
  1680. FakeQuery.sessionSearch = () => Promise.resolve({
  1681. items: [sessionHit('authorized-child', '/work', 'needle', parent.id)],
  1682. })
  1683. const upstream = new AbortController()
  1684. const started = Promise.withResolvers<undefined>()
  1685. const abortObserved = Promise.withResolvers<undefined>()
  1686. const cleanup = Promise.withResolvers<undefined>()
  1687. let active = false
  1688. let deadlineSignal: AbortSignal | undefined
  1689. const filterSessions = vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions')
  1690. .mockImplementation(async (_filters, signal) => {
  1691. if (signal === undefined) throw new Error('expected authorization signal')
  1692. deadlineSignal = signal
  1693. active = true
  1694. const aborted = new Promise<void>((resolve) => {
  1695. signal.addEventListener('abort', () => { resolve() }, { once: true })
  1696. })
  1697. started.resolve(undefined)
  1698. await aborted
  1699. abortObserved.resolve(undefined)
  1700. await cleanup.promise
  1701. active = false
  1702. signal.throwIfAborted()
  1703. return []
  1704. })
  1705. const pending = mounted.call(
  1706. 'session_search',
  1707. { query: 'needle' },
  1708. { signal: upstream.signal },
  1709. )
  1710. let settled = false
  1711. void pending.then(
  1712. () => { settled = true },
  1713. () => { settled = true },
  1714. )
  1715. await started.promise
  1716. await vi.advanceTimersByTimeAsync(timeoutMs)
  1717. await abortObserved.promise
  1718. expect(settled).toBe(false)
  1719. expect(active).toBe(true)
  1720. expect(deadlineSignal).toBeDefined()
  1721. expect(deadlineSignal).not.toBe(upstream.signal)
  1722. expect(filterSessions.mock.calls[0]?.[1]).toBe(deadlineSignal)
  1723. expect(FakeQuery.searchSignals).toEqual([deadlineSignal])
  1724. expect(deadlineSignal?.reason).toBeInstanceOf(TimeoutReason)
  1725. expect(deadlineSignal?.reason).toMatchObject({ code: 'TOOL_TIMEOUT', timeoutMs })
  1726. cleanup.resolve(undefined)
  1727. const result = await pending
  1728. expect(active).toBe(false)
  1729. expect(errorCode(result)).toBe('TOOL_TIMEOUT')
  1730. expect(text(result)).toBe(`Error: tool call timed out after ${timeoutMs}ms`)
  1731. })
  1732. it('passes the exact execution signal to every FTS page and stops on cancellation', async () => {
  1733. const mounted = await mount()
  1734. const controller = new AbortController()
  1735. const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined)
  1736. let started!: () => void
  1737. const bodyStarted = new Promise<void>((resolve) => { started = resolve })
  1738. FakeQuery.sessionSearch = (_request, exec) => new Promise((_resolve, reject) => {
  1739. started()
  1740. exec?.signal?.addEventListener('abort', () => {
  1741. reject(new SessionQueryError('aborted', 'SESSION_QUERY_ABORTED'))
  1742. }, { once: true })
  1743. })
  1744. const cancellation = new SessionQueryError('aborted', 'SESSION_QUERY_ABORTED')
  1745. const pending = mounted.call('session_search', { query: 'needle' }, { signal: controller.signal })
  1746. await bodyStarted
  1747. controller.abort(cancellation)
  1748. const result = await pending
  1749. expect(result.isError).toBe(true)
  1750. expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED')
  1751. expect(FakeQuery.searchSignals).toEqual([controller.signal])
  1752. expect(warn).not.toHaveBeenCalled()
  1753. })
  1754. })
  1755. describe('trace and exact read rendering', () => {
  1756. it('renders a deeply nested lineage without recursive consumer traversal', async () => {
  1757. const mounted = await mount()
  1758. const target = createSession(mounted.ctx, 'deep-target', '/work')
  1759. const [targetRecord] = await mounted.ctx.sessionQuery.filterSessions([{
  1760. kind: 'id',
  1761. values: [target.id],
  1762. }])
  1763. if (targetRecord === undefined) throw new Error('expected target record')
  1764. const depth = 3_000
  1765. let descendants: SessionLineageNode[] = []
  1766. for (let index = depth; index >= 1; index -= 1) {
  1767. descendants = [{
  1768. session: {
  1769. ...targetRecord,
  1770. header: header(`deep-${index}`, '/work', index),
  1771. },
  1772. descendants,
  1773. }]
  1774. }
  1775. vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValue({
  1776. target: targetRecord,
  1777. ancestors: [],
  1778. descendants,
  1779. complete: true,
  1780. root: targetRecord,
  1781. })
  1782. vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockImplementation(sessionIds => Promise.resolve(
  1783. [...new Set(sessionIds)].map(sessionId => ({
  1784. sessionId,
  1785. status: 'fulfilled' as const,
  1786. value: { session: header(sessionId, '/work') },
  1787. })),
  1788. ))
  1789. const output = text(await mounted.call('session_trace', { session_id: target.id }))
  1790. expect(output).toContain('Descendants:\n- deep-1 —')
  1791. expect(output).toContain(`${' '.repeat(depth - 1)}- deep-${depth} —`)
  1792. })
  1793. it('renders every event relationship sequence and a UTC target timestamp', async () => {
  1794. const mounted = await mount()
  1795. const session = createSession(mounted.ctx, 'relationships', '/work')
  1796. session.append(
  1797. 'user/message',
  1798. { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  1799. { surfaceOp: 'append' },
  1800. )
  1801. session.append(
  1802. 'assistant/message',
  1803. {
  1804. turn: 1,
  1805. step: 1,
  1806. content: [{ type: 'text', text: 'replacement' }],
  1807. provenance: { provider: 'test', model: 'test' },
  1808. },
  1809. { surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] },
  1810. )
  1811. const result = await mounted.call('session_event_trace', { session_id: session.id, seq: 0 })
  1812. expect(text(result)).toContain('Replacement chain: 1')
  1813. expect(text(result)).toContain('Direct derived events: 1')
  1814. expect(text(result)).toContain(new Date(session.events[0]?.time ?? 0).toISOString())
  1815. })
  1816. it('renders unabridged fenced target JSON and readable semantic or log-only neighbor summaries', async () => {
  1817. const mounted = await mount()
  1818. const session = createSession(mounted.ctx, 'read', '/work')
  1819. session.append(
  1820. 'user/message',
  1821. { content: [{ type: 'text', text: 'before semantic text' }], source: { kind: 'user' } },
  1822. { surfaceOp: 'append' },
  1823. )
  1824. session.append(
  1825. 'assistant/message',
  1826. {
  1827. turn: 1,
  1828. step: 1,
  1829. content: [{ type: 'text', text: 'target full text' }],
  1830. provenance: { provider: 'test', model: 'test' },
  1831. },
  1832. { surfaceOp: 'append' },
  1833. )
  1834. const appendLegacy = session.append.bind(session) as unknown as (
  1835. type: string,
  1836. data: unknown,
  1837. ) => Session['events'][number]
  1838. appendLegacy(
  1839. 'context/message',
  1840. { content: [{ type: 'text', text: 'after semantic text' }], source: { kind: 'plugin', plugin: 'test' } },
  1841. )
  1842. const result = await mounted.call('session_event_read', {
  1843. session_id: session.id,
  1844. seq: 1,
  1845. before: 1,
  1846. after: 1,
  1847. })
  1848. const output = text(result)
  1849. expect(output).toContain('```json')
  1850. expect(output).toContain('"text": "target full text"')
  1851. expect(output).toContain('before semantic text')
  1852. expect(output).toContain('seq 2 | context/message')
  1853. expect(output).toContain('(no semantic text)')
  1854. expect(output).not.toContain('after semantic text')
  1855. expect(output).not.toContain('truncated')
  1856. })
  1857. it('renders empty event relationships and neighbors without semantic text', async () => {
  1858. const mounted = await mount()
  1859. const session = createSession(mounted.ctx, 'empty-relations', '/work')
  1860. session.append('step/start', { turn: 1, step: 1 })
  1861. session.append('step/end', { turn: 1, step: 1 })
  1862. const trace = text(await mounted.call('session_event_trace', {
  1863. session_id: session.id,
  1864. seq: 0,
  1865. }))
  1866. expect(trace).toContain('Replaced by: none')
  1867. expect(trace).toContain('Replacement chain: none')
  1868. const onlyAfter = text(await mounted.call('session_event_read', {
  1869. session_id: session.id,
  1870. seq: 0,
  1871. after: 1,
  1872. }))
  1873. expect(onlyAfter).not.toContain('Before:')
  1874. expect(onlyAfter).toContain('(no semantic text)')
  1875. const onlyBefore = text(await mounted.call('session_event_read', {
  1876. session_id: session.id,
  1877. seq: 1,
  1878. before: 1,
  1879. }))
  1880. expect(onlyBefore).toContain('Before:')
  1881. expect(onlyBefore).not.toContain('After:')
  1882. })
  1883. it.each([
  1884. ['session_event_trace', { seq: -1 }],
  1885. ['session_event_read', { seq: Number.MAX_SAFE_INTEGER + 1 }],
  1886. ['session_event_read', { seq: 0, before: -1 }],
  1887. ['session_event_read', { seq: 0, after: 1.5 }, 'INVALID_ARGS'],
  1888. ])('rejects invalid exact-read integers for %s', async (name, args, expected = 'SESSION_QUERY_INVALID_FILTER') => {
  1889. const mounted = await mount()
  1890. expect(errorCode(await mounted.call(name, args))).toBe(expected)
  1891. })
  1892. })