scope.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import { describe, expect, expectTypeOf, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { carrierKeyOf, createScope, isScopeCarrier, scopeHost, scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope'
  4. import type { Scope, ScopeKey, Scoped } from '@deepseek-ai/dsh-scope'
  5. declare module 'cordis' {
  6. interface Events {
  7. /**
  8. * Test-only event for exercising scope-filtered dispatch.
  9. * @param value - opaque payload recorded by listeners.
  10. * @mode emit
  11. */
  12. 'scope-test/ping'(value: string): void
  13. /**
  14. * Test-only waterfall for exercising carrier `this` shape.
  15. * @param value - seed value listeners may wrap.
  16. * @mode waterfall
  17. */
  18. 'scope-test/echo'(value: string, next: () => string): string
  19. }
  20. }
  21. /** Mount a host plugin and mint a scope inside it, returning both. */
  22. async function mintScope(ctx: Context, key: object): Promise<Scope> {
  23. let scope!: Scope
  24. await ctx.plugin((inner: Context) => {
  25. scope = createScope(inner, key)
  26. })
  27. return scope
  28. }
  29. describe('createScope', () => {
  30. it('rejects primitive keys but accepts callable objects (matching ScopeKey)', async () => {
  31. const ctx = new Context()
  32. // Typed through `unknown` so the ScopeKey type cannot argue the assertion
  33. // away: this test exercises exactly the callers the typechecker misses.
  34. const badKeys: unknown[] = ['k', null]
  35. for (const bad of badKeys) {
  36. expect(() => createScope(ctx, bad as ScopeKey)).toThrow(/must be a non-null object or function/)
  37. }
  38. const callable = Object.assign(() => {}, { nameForTest: 'callable-key' })
  39. const scope = await mintScope(ctx, callable)
  40. expect(scopeOf(scope.ctx)).toBe(callable)
  41. await scope.dispose()
  42. })
  43. it('tags the scoped context, readable through derivations (nearest tag wins)', async () => {
  44. const ctx = new Context()
  45. const key = { name: 'a' }
  46. const inner = { name: 'a.inner' }
  47. const scope = await mintScope(ctx, key)
  48. expect(scopeOf(scope.ctx)).toBe(key)
  49. // An extend of the scoped context inherits the tag through the prototype chain.
  50. expect(scopeOf(scope.ctx.extend({}))).toBe(key)
  51. // A plain context carries no tag.
  52. expect(scopeOf(ctx)).toBeUndefined()
  53. // A fiber mounted UNDER the scoped context reads as that scope…
  54. let mountedCtx!: Context
  55. await scope.ctx.plugin((c: Context) => { mountedCtx = c })
  56. expect(scopeOf(mountedCtx)).toBe(key)
  57. // …and a nested scope shadows the outer tag (nearest wins).
  58. const nested = createScope(scope.ctx, inner)
  59. expect(scopeOf(nested.ctx)).toBe(inner)
  60. })
  61. it('is usable synchronously: registrations land before the fiber activates', async () => {
  62. const ctx = new Context()
  63. const events: string[] = []
  64. await ctx.plugin((inner: Context) => {
  65. const scope = createScope(inner, { name: 'sync' })
  66. // Same tick as createScope — no await between mint and use.
  67. scope.ctx.effect(() => () => void events.push('effect-disposed'))
  68. scope.ctx.on('scope-test/ping', value => void events.push(`heard:${value}`))
  69. events.push('registered')
  70. })
  71. ctx.emit(scopeTarget(ctx, undefined), 'scope-test/ping', 'nobody')
  72. expect(events).toEqual(['registered'])
  73. })
  74. it('dispose() unwinds registrations, is idempotent, and inerts the context', async () => {
  75. const ctx = new Context()
  76. const scope = await mintScope(ctx, { name: 'd' })
  77. const order: string[] = []
  78. scope.ctx.effect(() => () => void order.push('a'))
  79. scope.ctx.effect(() => () => void order.push('b'))
  80. await scope.dispose()
  81. expect(order).toEqual(['b', 'a']) // LIFO within the scope fiber
  82. // Repeat dispose: the underlying cordis disposer returns undefined; the
  83. // wrapper still resolves.
  84. await expect(scope.dispose()).resolves.toBeUndefined()
  85. // Registration through a disposed scope throws INACTIVE_EFFECT.
  86. expect(() => scope.ctx.effect(() => () => {})).toThrow(/inactive context/)
  87. })
  88. it('dispose() follows a rawDispose-first race through async quiescence', async () => {
  89. const ctx = new Context()
  90. const scope = await mintScope(ctx, { name: 'raw-first' })
  91. const gate = Promise.withResolvers<undefined>()
  92. let cleanupFinished = false
  93. scope.ctx.effect(() => async () => {
  94. await gate.promise
  95. cleanupFinished = true
  96. })
  97. const raw = Promise.resolve(scope.rawDispose())
  98. let publicSettled = false
  99. const publicDispose = scope.dispose().then(() => { publicSettled = true })
  100. await Promise.resolve()
  101. expect(publicSettled).toBe(false)
  102. expect(cleanupFinished).toBe(false)
  103. gate.resolve(undefined)
  104. await Promise.all([raw, publicDispose])
  105. expect(cleanupFinished).toBe(true)
  106. await expect(scope.dispose()).resolves.toBeUndefined()
  107. })
  108. it('rawDispose is the exact cordis disposer: yielding it nests the scope at its position', async () => {
  109. const ctx = new Context()
  110. const order: string[] = []
  111. let composite!: () => Promise<void> | void
  112. await ctx.plugin((inner: Context) => {
  113. composite = inner.effect(function* () {
  114. yield () => void order.push('outermost') // disposed LAST
  115. const scope = createScope(inner, { name: 'nested' })
  116. scope.ctx.effect(() => () => void order.push('scope-registration'))
  117. yield scope.rawDispose // disposed SECOND — nested by identity
  118. yield () => void order.push('innermost') // disposed FIRST
  119. })
  120. })
  121. await composite()
  122. // The scope disposed exactly at its yield position (between the two
  123. // neighbours), not as a concurrent sibling of the composite.
  124. expect(order).toEqual(['innermost', 'scope-registration', 'outermost'])
  125. })
  126. })
  127. describe('scopeTarget dispatch filtering', () => {
  128. it('scoped listeners hear only their key; untagged listeners hear everything', async () => {
  129. const ctx = new Context()
  130. const keyA = { name: 'A' }
  131. const keyB = { name: 'B' }
  132. const scopeA = await mintScope(ctx, keyA)
  133. const scopeB = await mintScope(ctx, keyB)
  134. const heard: string[] = []
  135. ctx.on('scope-test/ping', value => void heard.push(`global:${value}`))
  136. scopeA.ctx.on('scope-test/ping', value => void heard.push(`A:${value}`))
  137. scopeB.ctx.on('scope-test/ping', value => void heard.push(`B:${value}`))
  138. ctx.emit(scopeTarget(ctx, keyA), 'scope-test/ping', 'to-A')
  139. ctx.emit(scopeTarget(ctx, keyB), 'scope-test/ping', 'to-B')
  140. ctx.emit(scopeTarget(ctx, undefined), 'scope-test/ping', 'to-nobody')
  141. expect(heard).toEqual([
  142. 'global:to-A', 'A:to-A',
  143. 'global:to-B', 'B:to-B',
  144. 'global:to-nobody',
  145. ])
  146. })
  147. it('{ global: true } listeners bypass scope filtering entirely', async () => {
  148. const ctx = new Context()
  149. const keyA = { name: 'A' }
  150. const scopeA = await mintScope(ctx, keyA)
  151. const heard: string[] = []
  152. scopeA.ctx.on('scope-test/ping', value => void heard.push(`escape:${value}`), { global: true })
  153. ctx.emit(scopeTarget(ctx, { name: 'other' }), 'scope-test/ping', 'foreign')
  154. ctx.emit(scopeTarget(ctx, undefined), 'scope-test/ping', 'nobody')
  155. expect(heard).toEqual(['escape:foreign', 'escape:nobody'])
  156. })
  157. it("composes the base's own Context.filter (a rejecting base filter wins)", async () => {
  158. const ctx = new Context()
  159. const keyA = { name: 'A' }
  160. const scopeA = await mintScope(ctx, keyA)
  161. const heard: string[] = []
  162. ctx.on('scope-test/ping', value => void heard.push(`global:${value}`))
  163. scopeA.ctx.on('scope-test/ping', value => void heard.push(`A:${value}`))
  164. // A base whose own filter rejects every listener context: nothing fires,
  165. // scoped or not — the scope predicate never overrides the base's veto.
  166. const vetoBase = { [Context.filter]: () => false }
  167. ctx.emit(scopeTarget(vetoBase, keyA), 'scope-test/ping', 'vetoed')
  168. expect(heard).toEqual([])
  169. // A base whose filter accepts delegates to the scope predicate.
  170. const openBase = { [Context.filter]: () => true }
  171. ctx.emit(scopeTarget(openBase, keyA), 'scope-test/ping', 'open')
  172. expect(heard).toEqual(['global:open', 'A:open'])
  173. })
  174. it('keeps listener `this` base-shaped through the carrier (waterfall)', async () => {
  175. const ctx = new Context()
  176. const base = { label: 'the-base' }
  177. let seenLabel: string | undefined
  178. ctx.on('scope-test/echo', function (this: { label: string }, value, next) {
  179. seenLabel = this.label
  180. return `${next()}+${value}`
  181. })
  182. const result = ctx.waterfall(scopeTarget(base, undefined), 'scope-test/echo', 'v', () => 'seed')
  183. expect(result).toBe('seed+v')
  184. expect(seenLabel).toBe('the-base')
  185. })
  186. it('is transparent for subjects with native #private fields: methods and getters through the carrier reach the real object', () => {
  187. // The ds-review-bot regression: cordis hands the carrier to listeners as
  188. // `this` (typed Scoped<Agent>), so subject method calls through it are a
  189. // supported shape. A proxy that delegates with the PROXY as receiver
  190. // (cordis withProps) throws TypeError on any native #private the method
  191. // or getter touches; the carrier must delegate with the BASE as receiver
  192. // and bind retrieved methods to it.
  193. class Subject {
  194. #count = 0
  195. bump(): number { return ++this.#count }
  196. get count(): number { return this.#count }
  197. }
  198. const subject = new Subject()
  199. const carrier = scopeTarget(subject, subject)
  200. expect(carrier.bump()).toBe(1) // method call: bound to the base
  201. expect(subject.count).toBe(1) // ...and it mutated the REAL object
  202. expect(carrier.count).toBe(1) // getter: runs with the base as receiver
  203. // The get trap returns the method already bound to the base;
  204. // detachability IS the assertion.
  205. // eslint-disable-next-line @typescript-eslint/unbound-method
  206. const detached = carrier.bump
  207. expect(detached()).toBe(2)
  208. })
  209. it('delegates sets to the base and leaves frozen own function props unbound (proxy invariant)', () => {
  210. const frozenFn = (): string => 'frozen'
  211. const base: { mutable: number; pinned: () => string; toString: () => string } = {
  212. mutable: 0,
  213. pinned: frozenFn,
  214. toString: () => 'base-str',
  215. }
  216. Object.defineProperty(base, 'pinned', { value: frozenFn, writable: false, configurable: false })
  217. const carrier = scopeTarget(base, undefined)
  218. carrier.mutable = 7
  219. expect(base.mutable).toBe(7) // sets land on the base, not a detached overlay
  220. // A non-configurable, non-writable own data prop must be reported
  221. // unchanged (binding it would violate the proxy get invariant).
  222. expect(carrier.pinned).toBe(frozenFn)
  223. // The overlay literal inherits Object.prototype; hasOwn (not `in`) keeps
  224. // it from shadowing the subject's own prototype-surface members.
  225. expect(String(carrier)).toBe('base-str')
  226. })
  227. it('honors the get invariant even when an overlay key collides with a frozen own prop of the base', () => {
  228. // Pathological but engine-enforced: a base whose own [Context.filter] is
  229. // a non-configurable, non-writable data prop pins what any proxy over it
  230. // may report for that key. The carrier must yield the base's value (an
  231. // overlay there would be a runtime TypeError from the engine, not a
  232. // filtering choice). Such a base forgoes scope filtering by construction.
  233. const pinnedFilter = (): boolean => true
  234. const base = {}
  235. Object.defineProperty(base, Context.filter, { value: pinnedFilter, writable: false, configurable: false })
  236. const carrier = scopeTarget(base, { name: 'key' })
  237. expect((carrier as Record<symbol, unknown>)[Context.filter]).toBe(pinnedFilter)
  238. })
  239. it('keeps the real constructor: class identity survives the carrier', () => {
  240. class Subject { work(): string { return 'w' } }
  241. const subject = new Subject()
  242. const carrier = scopeTarget(subject, subject)
  243. // `constructor` is looked up, never invoked as a subject method — binding
  244. // it would break `carrier.constructor === Subject` for no benefit.
  245. expect(carrier.constructor).toBe(Subject)
  246. })
  247. })
  248. describe('carrier marks', () => {
  249. it('isScopeCarrier / carrierKeyOf distinguish carriers, keys, and bare subjects', () => {
  250. const base = { name: 'base' }
  251. const key = { name: 'key' }
  252. const keyed = scopeTarget(base, key)
  253. const subjectless = scopeTarget(base, undefined)
  254. expect(isScopeCarrier(keyed)).toBe(true)
  255. expect(carrierKeyOf(keyed)).toBe(key)
  256. expect(isScopeCarrier(subjectless)).toBe(true)
  257. expect(carrierKeyOf(subjectless)).toBeUndefined()
  258. expect(isScopeCarrier(base)).toBe(false)
  259. expect(carrierKeyOf(base)).toBeUndefined()
  260. expect(isScopeCarrier(null)).toBe(false)
  261. expect(isScopeCarrier('x')).toBe(false)
  262. })
  263. it('brands the carrier type (compile-time)', () => {
  264. const base = { name: 'base' }
  265. const carrier = scopeTarget(base, undefined)
  266. expectTypeOf(carrier).toExtend<Scoped<{ name: string }>>()
  267. // A bare subject is NOT assignable where a carrier is demanded.
  268. expectTypeOf(base).not.toExtend<Scoped<{ name: string }>>()
  269. })
  270. })
  271. describe('scopeHost', () => {
  272. it('mints scopes that reach the injected services; dispose unwinds them all', async () => {
  273. const ctx = new Context()
  274. ctx.provide('answers', { value: 42 })
  275. const host = await scopeHost(ctx, ['answers'])
  276. const scope = host.mint({ name: 'a' })
  277. expect((scope.ctx as Context & { answers: { value: number } }).answers.value).toBe(42)
  278. const order: string[] = []
  279. scope.ctx.effect(() => () => void order.push('scoped-disposed'))
  280. await host.dispose()
  281. expect(order).toEqual(['scoped-disposed'])
  282. expect(() => scope.ctx.effect(() => () => {})).toThrow(/inactive context/)
  283. })
  284. it('dispose waits for a child whose raw disposer won the race', async () => {
  285. const ctx = new Context()
  286. ctx.provide('answers', { value: 42 })
  287. const host = await scopeHost(ctx, ['answers'])
  288. const scope = host.mint({ name: 'raw-first-child' })
  289. const gate = Promise.withResolvers<undefined>()
  290. let cleanupFinished = false
  291. scope.ctx.effect(() => async () => {
  292. await gate.promise
  293. cleanupFinished = true
  294. })
  295. const raw = Promise.resolve(scope.rawDispose())
  296. let hostSettled = false
  297. const hostDispose = host.dispose().then(() => { hostSettled = true })
  298. await Promise.resolve()
  299. expect(hostSettled).toBe(false)
  300. gate.resolve(undefined)
  301. await Promise.all([raw, hostDispose])
  302. expect(cleanupFinished).toBe(true)
  303. await expect(host.dispose()).resolves.toBeUndefined()
  304. })
  305. it('reaches every child before surfacing one or multiple disposal failures', async () => {
  306. const oneCtx = new Context()
  307. oneCtx.provide('answers', { value: 42 })
  308. const oneHost = await scopeHost(oneCtx, ['answers'])
  309. const one = oneHost.mint({ name: 'one' })
  310. one.dispose = () => Promise.reject(new Error('one failed'))
  311. await expect(oneHost.dispose()).rejects.toThrow('one failed')
  312. const manyCtx = new Context()
  313. manyCtx.provide('answers', { value: 42 })
  314. const manyHost = await scopeHost(manyCtx, ['answers'])
  315. const a = manyHost.mint({ name: 'a' })
  316. const b = manyHost.mint({ name: 'b' })
  317. a.dispose = () => Promise.reject(new Error('a failed'))
  318. b.dispose = () => Promise.reject(new Error('b failed'))
  319. await expect(manyHost.dispose()).rejects.toMatchObject({
  320. name: 'AggregateError',
  321. message: 'scopeHost: disposal failed',
  322. errors: [expect.objectContaining({ message: 'a failed' }), expect.objectContaining({ message: 'b failed' })],
  323. })
  324. })
  325. it('fails LOUD naming absent services instead of resolving as a silent no-op host', async () => {
  326. const ctx = new Context()
  327. await expect(scopeHost(ctx, ['tools', 'systemPrompt']))
  328. .rejects.toThrow('scopeHost: services "tools", "systemPrompt" not available')
  329. })
  330. it('names a single absent service in the singular', async () => {
  331. const ctx = new Context()
  332. await expect(scopeHost(ctx, ['tools'])).rejects.toThrow('scopeHost: service "tools" not available')
  333. })
  334. })