sdk.snapshot.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /**
  2. * Keyless snapshot coverage for the TypeScript SDK path: each scenario spawns
  3. * the real `dsh --profile sdk` runtime through
  4. * `@deepseek-ai/dsh-sdk-client`, drives one turn over stdio JSON-RPC,
  5. * and pins the SDK `RunResult`, the complete notification stream, and the
  6. * persisted session logs. Replay serves recorded model
  7. * responses via `llm-replay` (`cordis.snapshot.yml`); `DSH_SNAPSHOT=record`
  8. * re-records against the live API; `DSH_SNAPSHOT=refresh` replays committed
  9. * fixtures and rewrites expected outputs.
  10. */
  11. import { existsSync } from 'node:fs'
  12. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
  13. import { tmpdir } from 'node:os'
  14. import { basename, delimiter, join } from 'node:path'
  15. import { fileURLToPath, pathToFileURL } from 'node:url'
  16. import { describe, expect, it } from 'vitest'
  17. import {
  18. normalizeSessionLog,
  19. normalizeSessionSnapshot,
  20. normalizeStdout,
  21. parseSnapshotManifest,
  22. refreshFixtureReplacements,
  23. scrubRequestHeaders,
  24. scrubSessionSnapshot,
  25. stabilizeFixtureMessageIds,
  26. stabilizeRefreshLog,
  27. tokenizeSessionFixtureCwd,
  28. type HarvestedLog,
  29. type NormalizeContext,
  30. } from '@deepseek-ai/dsh-session-snapshot'
  31. import { DeepSeekHarness, type HarnessNotification, type RunResult } from '@deepseek-ai/dsh-sdk-client'
  32. const testsDir = dirOf(import.meta.url)
  33. const snapshotsDir = fileURLToPath(new URL('../../../snapshots/sdk/', import.meta.url))
  34. const liveConfig = join(testsDir, '..', 'typescript-sdk.cordis.yml')
  35. const replayConfig = join(testsDir, '..', 'typescript-sdk.cordis.snapshot.yml')
  36. const minimalLiveConfig = join(testsDir, '..', 'typescript-sdk-minimal.cordis.yml')
  37. const minimalReplayConfig = join(testsDir, '..', 'typescript-sdk-minimal.cordis.snapshot.yml')
  38. const sessionUploadLivePatch = join(testsDir, '..', 'session-upload.cordis.yml')
  39. const sessionUploadReplayPatch = join(testsDir, '..', 'session-upload.snapshot.cordis.yml')
  40. const exampleMode = process.env.DSH_EXAMPLE_MODE ?? 'src'
  41. const replayPlugin = fileURLToPath(new URL(
  42. exampleMode === 'lib'
  43. ? '../../../packages/test-support/llm-replay/lib/index.js'
  44. : '../../../packages/test-support/llm-replay/src/index.ts',
  45. import.meta.url,
  46. ))
  47. const MINIMAL_SYSTEM_PROMPT = 'You are the environment-selected minimal software engineer.'
  48. const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
  49. * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
  50. * You don't have access to the internet via this tool.
  51. * You do have access to a mirror of common linux and python packages via apt and pip.
  52. * State is persistent across command calls and discussions with the user.
  53. * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
  54. * Please avoid commands that may produce a very large amount of output.
  55. * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.`
  56. const mode = process.env.DSH_SNAPSHOT ?? 'replay'
  57. const recording = mode === 'record'
  58. const refreshing = mode === 'refresh'
  59. function dirOf(url: string): string {
  60. return fileURLToPath(new URL('.', url))
  61. }
  62. interface SdkScenario {
  63. /** Scenario name; the `snapshots/sdk/<name>` fixture directory. */
  64. name: string
  65. /** The user prompt for the single SDK turn. */
  66. prompt: string
  67. /** Fixed SDK session id, so fixtures and replay binding stay stable. */
  68. sessionId: string
  69. /** How many child sessions the turn persists (subagent scenarios). */
  70. children: number
  71. /** Optional scenario-specific live and replay compositions. */
  72. configs?: { live: string; replay: string }
  73. /** Additional ordered patches applied after the selected live or replay patch. */
  74. additionalPatches?: { live: readonly string[]; replay: readonly string[] }
  75. /** Environment overrides passed to the runtime subprocess. */
  76. environment?: Readonly<Record<string, string>>
  77. /** Cwd-relative files whose final contents are part of the scenario contract. */
  78. expectedFiles?: Readonly<Record<string, string>>
  79. /** Assembled model-facing tool names and required argument keys. */
  80. expectedTools?: Readonly<Record<string, readonly string[]>>
  81. /** Exact assembled system prompt for the root request. */
  82. expectedSystem?: string
  83. /** Exact model-facing descriptions for selected tools. */
  84. expectedToolDescriptions?: Readonly<Record<string, string>>
  85. /** Expected runtime-context state in the real assembled request. */
  86. runtimeContext?: false | { includes: readonly string[]; excludes: readonly string[] }
  87. }
  88. const SCENARIOS: SdkScenario[] = [
  89. {
  90. name: 'text-turn',
  91. prompt: 'Reply with exactly: SDK snapshot OK',
  92. sessionId: 'sdk-snapshot-text',
  93. children: 0,
  94. additionalPatches: { live: [sessionUploadLivePatch], replay: [sessionUploadReplayPatch] },
  95. },
  96. {
  97. name: 'bash-tool',
  98. prompt: 'Run this exact command with your bash tool, then reply with its stdout only: echo dsh-sdk-proof-7391',
  99. sessionId: 'sdk-snapshot-bash',
  100. children: 0,
  101. },
  102. {
  103. name: 'subagent-spawn-in-process',
  104. prompt: "Use the subagent tool exactly once with description 'echo probe' and prompt: Reply with exactly: child answer 42. Then reply with the subagent's final answer verbatim.",
  105. sessionId: 'sdk-snapshot-subagent',
  106. children: 1,
  107. },
  108. {
  109. name: 'persistent-tools',
  110. prompt: 'Prove that bash state persists. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9.',
  111. sessionId: 'persistent-tools-snapshot',
  112. children: 0,
  113. configs: { live: minimalLiveConfig, replay: minimalReplayConfig },
  114. environment: { DSH_SYSTEM_PROMPT: MINIMAL_SYSTEM_PROMPT },
  115. expectedFiles: { 'note.txt': 'target:\n\tnew\n' },
  116. expectedTools: { bash: ['command'], str_replace_editor: ['command', 'path'] },
  117. expectedSystem: MINIMAL_SYSTEM_PROMPT,
  118. expectedToolDescriptions: { bash: MINIMAL_BASH_DESCRIPTION },
  119. runtimeContext: {
  120. includes: ['Current DSH file policy: danger-full-access', 'Approval prompts are disabled in this session'],
  121. excludes: ['workspace-write'],
  122. },
  123. },
  124. ]
  125. interface PersistedLog {
  126. readonly path: string
  127. readonly content: string
  128. readonly header: Record<string, unknown>
  129. }
  130. interface MissingFile {
  131. readonly missing: true
  132. }
  133. async function jsonlFiles(dir: string): Promise<string[]> {
  134. const entries = await readdir(dir, { recursive: true })
  135. return entries.filter(entry => entry.endsWith('.jsonl')).map(entry => join(dir, entry)).sort()
  136. }
  137. async function persistedLogs(sessionsRoot: string): Promise<PersistedLog[]> {
  138. const files = await jsonlFiles(sessionsRoot)
  139. return Promise.all(files.map(async (path) => {
  140. const content = await readFile(path, 'utf8')
  141. const header = JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>
  142. return { path, content, header }
  143. }))
  144. }
  145. interface LoggedRequestHeader {
  146. type?: string
  147. data?: { header?: { system?: unknown; tools?: LoggedTool[] } }
  148. }
  149. interface LoggedTool {
  150. readonly name: string
  151. readonly description?: unknown
  152. readonly parameters: { readonly required?: string[] }
  153. }
  154. function assembledTools(log: PersistedLog): LoggedTool[] {
  155. const event = log.content.trimEnd().split('\n')
  156. .map(line => JSON.parse(line) as LoggedRequestHeader)
  157. .find(candidate => candidate.type === 'request/header')
  158. const tools = event?.data?.header?.tools
  159. if (tools === undefined) throw new Error('session log has no request/header tools')
  160. return tools
  161. }
  162. function assembledToolRequirements(log: PersistedLog): Record<string, string[]> {
  163. return Object.fromEntries(assembledTools(log).map(tool => [tool.name, tool.parameters.required ?? []]))
  164. }
  165. function assembledToolDescriptions(log: PersistedLog): Record<string, string> {
  166. return Object.fromEntries(assembledTools(log).map((tool) => {
  167. if (typeof tool.description !== 'string') throw new Error(`tool ${tool.name} has no description`)
  168. return [tool.name, tool.description]
  169. }))
  170. }
  171. function assembledSystem(log: PersistedLog): string {
  172. const event = log.content.trimEnd().split('\n')
  173. .map(line => JSON.parse(line) as LoggedRequestHeader)
  174. .find(candidate => candidate.type === 'request/header')
  175. const system = event?.data?.header?.system
  176. if (typeof system !== 'string') throw new Error('session log has no request/header system')
  177. return system
  178. }
  179. function assembledRuntimeContexts(log: PersistedLog): string[] {
  180. return log.content.trimEnd().split('\n').flatMap((line) => {
  181. const event = JSON.parse(line) as {
  182. type?: string
  183. data?: { source?: { kind?: string; plugin?: string }; content?: Array<{ type?: string; text?: unknown }> }
  184. }
  185. if (event.type !== 'user/message'
  186. || event.data?.source?.kind !== 'plugin'
  187. || event.data.source.plugin !== '@deepseek-ai/dsh-system-prompt') return []
  188. return event.data.content?.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []) ?? []
  189. })
  190. }
  191. function contextOf(logs: readonly { content: string; header: Record<string, unknown> }[], cwd: string): NormalizeContext {
  192. return {
  193. sessionIds: logs.flatMap(log => typeof log.header.id === 'string' ? [log.header.id] : []),
  194. cwd,
  195. }
  196. }
  197. function contextOfContents(contents: readonly string[]): NormalizeContext {
  198. const headers = contents.map(content => JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>)
  199. return {
  200. sessionIds: headers.flatMap(header => typeof header.id === 'string' ? [header.id] : []),
  201. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  202. }
  203. }
  204. async function hydrateReplayFixtures(scenario: SdkScenario, cwd: string): Promise<string[]> {
  205. const root = join(cwd, '.replay-fixtures')
  206. await mkdir(root, { recursive: true })
  207. return Promise.all(fixtureFiles(scenario).map(async (source) => {
  208. const destination = join(root, basename(source))
  209. await writeFile(destination, (await readFile(source, 'utf8')).replaceAll('{{cwd}}', cwd))
  210. return destination
  211. }))
  212. }
  213. async function readExpectedFile(path: string): Promise<string | MissingFile> {
  214. try {
  215. return await readFile(path, 'utf8')
  216. } catch (error: unknown) {
  217. if (error instanceof Error && (error as NodeJS.ErrnoException).code === 'ENOENT') return { missing: true }
  218. throw error
  219. }
  220. }
  221. /** Materialize a built-mode replay patch with an absolute test-plugin module URL. */
  222. async function materializeReplayPatch(source: string, cwd: string): Promise<string> {
  223. const target = join(cwd, `.sdk-${basename(source)}`)
  224. const content = (await readFile(source, 'utf8'))
  225. .replaceAll("'@deepseek-ai/dsh-llm-replay'", JSON.stringify(pathToFileURL(replayPlugin).href))
  226. await writeFile(target, content)
  227. return target
  228. }
  229. /**
  230. * Normalize the SDK-visible notification stream: embedded `session.event`
  231. * envelopes get the session-log treatment (times zeroed, headers tokenized),
  232. * then every record is scrubbed like a wire frame.
  233. */
  234. function normalizeNotifications(notifications: readonly HarnessNotification[], ctx: NormalizeContext): string {
  235. const events = notifications
  236. .filter(n => n.method === 'session.event')
  237. .map(n => n.params.event as Record<string, unknown>)
  238. const normalizedEvents = events.length === 0
  239. ? []
  240. : scrubRequestHeaders(normalizeSessionLog(
  241. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  242. ctx,
  243. )).trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
  244. let eventIndex = 0
  245. const records = notifications.map((notification) => {
  246. if (notification.method !== 'session.event') return { method: notification.method, params: notification.params }
  247. const event = normalizedEvents[eventIndex++]
  248. return { method: notification.method, params: { ...notification.params, event } }
  249. })
  250. return normalizeStdout(`${records.map(record => JSON.stringify(record)).join('\n')}\n`, ctx)
  251. }
  252. /** Normalize the owned-run projection. */
  253. function normalizeResult(result: RunResult, ctx: NormalizeContext): string {
  254. return normalizeStdout(`${JSON.stringify({
  255. sessionId: result.sessionId,
  256. finalResponse: result.finalResponse,
  257. })}\n`, ctx)
  258. }
  259. /** One SDK turn against a fresh runtime subprocess in an isolated cwd. */
  260. async function runScenario(scenario: SdkScenario): Promise<{
  261. result: RunResult
  262. notifications: HarnessNotification[]
  263. logs: PersistedLog[]
  264. observedFiles: Record<string, string | MissingFile>
  265. cwd: string
  266. }> {
  267. const cwd = await mkdtemp(join(tmpdir(), `sdk-snapshot-${scenario.name}-`))
  268. const dshHome = join(cwd, '.dsh')
  269. const sessionsRoot = join(dshHome, 'sessions')
  270. const replayFixtures = recording ? [] : await hydrateReplayFixtures(scenario, cwd)
  271. const livePatch = scenario.configs?.live ?? liveConfig
  272. const replayPatch = scenario.configs?.replay ?? replayConfig
  273. const resolvedReplayPatch = recording ? undefined : await materializeReplayPatch(replayPatch, cwd)
  274. const additionalPatches = recording
  275. ? scenario.additionalPatches?.live ?? []
  276. : scenario.additionalPatches?.replay ?? []
  277. const [parentFixture, ...childFixtures] = replayFixtures
  278. const env: Record<string, string> = {
  279. ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  280. DSH_SNAPSHOT: mode,
  281. DSH_TELEMETRY_DISABLED: '1',
  282. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  283. ...parentFixture === undefined ? {} : {
  284. DSH_SNAPSHOT_FILE: parentFixture,
  285. ...childFixtures.length > 0 ? { DSH_SNAPSHOT_CHILD_FILES: childFixtures.join(delimiter) } : {},
  286. },
  287. ...scenario.environment,
  288. }
  289. const harness = new DeepSeekHarness({
  290. profile: 'sdk',
  291. patches: [
  292. livePatch,
  293. ...resolvedReplayPatch === undefined ? [] : [resolvedReplayPatch],
  294. ...additionalPatches,
  295. ],
  296. dshHome,
  297. processCwd: cwd,
  298. env,
  299. requestTimeoutMs: 110_000,
  300. cwd,
  301. provider: 'deepseek-official',
  302. model: 'deepseek-v4-flash',
  303. })
  304. try {
  305. const notifications: HarnessNotification[] = []
  306. const result = await harness.run(scenario.prompt.replaceAll('{{cwd}}', cwd), {
  307. sessionId: scenario.sessionId,
  308. onNotification: (notification) => { notifications.push(notification) },
  309. })
  310. await harness.close()
  311. const logs = await persistedLogs(sessionsRoot)
  312. const observedFiles = Object.fromEntries(await Promise.all(
  313. Object.keys(scenario.expectedFiles ?? {}).map(async (path): Promise<[string, string | MissingFile]> => [
  314. path,
  315. await readExpectedFile(join(cwd, path)),
  316. ]),
  317. ))
  318. return { result, notifications, logs, observedFiles, cwd }
  319. } finally {
  320. await harness.close()
  321. await rm(cwd, { recursive: true, force: true })
  322. }
  323. }
  324. /** Order logs parent-first, children by creation time (fixture layout order). */
  325. function orderLogs(logs: PersistedLog[], scenario: SdkScenario): PersistedLog[] {
  326. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  327. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  328. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  329. expect(parents).toHaveLength(1)
  330. expect(children).toHaveLength(scenario.children)
  331. return [...parents, ...children]
  332. }
  333. function fixtureFiles(scenario: SdkScenario): string[] {
  334. const dir = join(snapshotsDir, scenario.name)
  335. return [
  336. join(dir, 'session.jsonl'),
  337. ...Array.from({ length: scenario.children }, (_, index) => join(dir, `session.${index + 1}.jsonl`)),
  338. ]
  339. }
  340. describe('TypeScript SDK snapshots over the jsonrpc runtime', () => {
  341. for (const scenario of SCENARIOS) {
  342. it(`replays ${scenario.name} through the SDK`, async () => {
  343. const scenarioDir = join(snapshotsDir, scenario.name)
  344. const manifest = parseSnapshotManifest(
  345. await readFile(join(scenarioDir, 'snapshot.yml'), 'utf8'),
  346. join(scenarioDir, 'snapshot.yml'),
  347. )
  348. expect(manifest).toEqual({ version: 1, profile: 'sdk' })
  349. const notificationsExpectedPath = join(scenarioDir, 'notifications.expected.jsonl')
  350. const resultExpectedPath = join(scenarioDir, 'result.expected.json')
  351. const { result, notifications, logs, observedFiles, cwd } = await runScenario(scenario)
  352. const ordered = orderLogs(logs, scenario)
  353. const actualContext = contextOf(ordered, cwd)
  354. const files = fixtureFiles(scenario)
  355. if (recording) {
  356. // Fixtures carry tokenized request headers; llm-replay reads only
  357. // assistant output and tool traffic, so scrubbing keeps prompts and
  358. // schemas out of the corpus without affecting replay.
  359. await mkdir(scenarioDir, { recursive: true })
  360. const existing = await Promise.all(files.map(async file => existsSync(file) ? readFile(file, 'utf8') : ''))
  361. const fixtures = stabilizeFixtureMessageIds(
  362. ordered.map(log => scrubSessionSnapshot(tokenizeSessionFixtureCwd(log.content))),
  363. existing,
  364. )
  365. await Promise.all(fixtures.map(async (fixture, index) => {
  366. const file = files[index]
  367. if (file === undefined) throw new Error(`no fixture path for persisted log ${index}`)
  368. await writeFile(file, fixture)
  369. }))
  370. }
  371. let expectedContents = await Promise.all(files.map(file => readFile(file, 'utf8')))
  372. if (refreshing) {
  373. const harvested = ordered.map((log): HarvestedLog => ({
  374. id: String(log.header.id),
  375. createdAt: Number(log.header.createdAt),
  376. ...typeof log.header.parentSession === 'string' ? { parentSession: log.header.parentSession } : {},
  377. content: log.content,
  378. }))
  379. const replacements = refreshFixtureReplacements(harvested, expectedContents)
  380. const refreshed = ordered.map((log, index) => {
  381. const existing = expectedContents[index]
  382. if (existing === undefined) throw new Error(`no fixture for persisted log ${index}`)
  383. return scrubSessionSnapshot(tokenizeSessionFixtureCwd(
  384. stabilizeRefreshLog(log.content, existing, replacements, actualContext),
  385. ))
  386. })
  387. expectedContents = stabilizeFixtureMessageIds(refreshed, expectedContents)
  388. await Promise.all(expectedContents.map(async (stable, index) => {
  389. const file = files[index]
  390. if (file === undefined) throw new Error(`no fixture for persisted log ${index}`)
  391. await writeFile(file, stable)
  392. }))
  393. }
  394. for (const [index, expected] of expectedContents.entries()) {
  395. expect(scrubRequestHeaders(expected), `${scenario.name} session fixture ${index} carries request-header bulk`)
  396. .toBe(expected)
  397. }
  398. // Persisted transcripts match the committed fixtures.
  399. const expectedContext = contextOfContents(expectedContents)
  400. for (const [index, log] of ordered.entries()) {
  401. const expected = expectedContents[index]
  402. if (expected === undefined) throw new Error(`no fixture for persisted log ${index}`)
  403. expect(normalizeSessionSnapshot(log.content, actualContext))
  404. .toBe(normalizeSessionSnapshot(expected, expectedContext))
  405. }
  406. // The SDK-visible wire stream and turn result match their expected outputs.
  407. const normalizedNotifications = normalizeNotifications(notifications, actualContext)
  408. const normalizedResult = normalizeResult(result, actualContext)
  409. if (recording || refreshing) {
  410. await writeFile(notificationsExpectedPath, normalizedNotifications)
  411. await writeFile(resultExpectedPath, normalizedResult)
  412. }
  413. expect(normalizedNotifications).toBe(await readFile(notificationsExpectedPath, 'utf8'))
  414. expect(normalizedResult).toBe(await readFile(resultExpectedPath, 'utf8'))
  415. // Wire-shape invariants that must hold in every mode.
  416. expect(notifications.at(-1)).toMatchObject({
  417. method: 'session.status',
  418. params: { status: 'idle' },
  419. })
  420. expect(observedFiles).toEqual(scenario.expectedFiles ?? {})
  421. if (scenario.expectedTools !== undefined) {
  422. const parent = ordered[0]
  423. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  424. expect(assembledToolRequirements(parent)).toEqual(scenario.expectedTools)
  425. }
  426. if (scenario.expectedSystem !== undefined) {
  427. const parent = ordered[0]
  428. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  429. expect(assembledSystem(parent)).toBe(scenario.expectedSystem)
  430. }
  431. if (scenario.expectedToolDescriptions !== undefined) {
  432. const parent = ordered[0]
  433. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  434. expect(assembledToolDescriptions(parent)).toMatchObject(scenario.expectedToolDescriptions)
  435. }
  436. if (scenario.runtimeContext !== undefined) {
  437. const parent = ordered[0]
  438. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  439. const contexts = assembledRuntimeContexts(parent)
  440. if (scenario.runtimeContext === false) {
  441. expect(contexts).toEqual([])
  442. } else {
  443. expect(contexts).toHaveLength(1)
  444. const context = contexts[0] as string
  445. for (const clause of scenario.runtimeContext.includes) expect(context).toContain(clause)
  446. for (const clause of scenario.runtimeContext.excludes) expect(context).not.toContain(clause)
  447. const system = assembledSystem(parent)
  448. for (const clause of scenario.runtimeContext.includes) expect(system).not.toContain(clause)
  449. }
  450. }
  451. if (scenario.children > 0) {
  452. expect(notifications.some(n => n.method === 'subagent.started')).toBe(true)
  453. expect(notifications.some(n => n.method === 'subagent.finished')).toBe(true)
  454. }
  455. })
  456. }
  457. })