test-invariants.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. /**
  2. * Vitest-wide invariant host. Ordinary Cordis roots receive the invariant
  3. * service with global enablement plus the current test package's companion.
  4. * One topology test mounts every companion; focused invariant tests own their
  5. * service topology explicitly.
  6. */
  7. import { expect } from 'vitest'
  8. import { RegistryService } from 'cordis'
  9. import type { Context, Plugin } from 'cordis'
  10. import InvariantService from '@deepseek-ai/dsh-invariants'
  11. declare global {
  12. interface ImportMeta {
  13. /** Eager Vite module-glob expansion used by the Vitest setup file. */
  14. glob<TModule>(pattern: string, options: { eager: true }): Record<string, TModule>
  15. }
  16. }
  17. /** Loader-safe shape shared by every package invariant companion. */
  18. export interface TestInvariantCompanion {
  19. readonly name: string
  20. readonly inject: readonly string[]
  21. apply(ctx: Context): Promise<() => void>
  22. }
  23. /** Every package companion, discovered eagerly so coverage observes each registration. */
  24. export const testInvariantCompanions: Readonly<Record<string, TestInvariantCompanion>> =
  25. import.meta.glob<TestInvariantCompanion>('../packages/*/*/src/invariant.ts', { eager: true })
  26. /** Tests that exercise selection or companion lifecycle with a deliberately hand-built service tree. */
  27. export const MANUAL_INVARIANT_TESTS = [
  28. '/packages/support/invariants/tests/service.spec.ts',
  29. '/packages/core/session/tests/invariant.spec.ts',
  30. '/packages/core/agent/tests/invariant.spec.ts',
  31. '/packages/core/scope/tests/invariant.spec.ts',
  32. '/packages/core/agent-loop/tests/invariant.spec.ts',
  33. '/packages/examples/agent-spine-demo/tests/agent-core.spec.ts',
  34. ] as const
  35. interface InvariantHost {
  36. readonly fibers: readonly PluginFiber[]
  37. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  38. readonly ready: Promise<void>
  39. }
  40. type PluginFiber = ReturnType<RegistryService['plugin']>
  41. const hosts = new WeakMap<Context, InvariantHost>()
  42. // eslint-disable-next-line @typescript-eslint/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  43. const originalPlugin = RegistryService.prototype.plugin
  44. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  45. if (usesManualInvariantTree()) return originalPlugin.call(this, plugin, config, getOuterStack)
  46. const root = this.ctx.root
  47. const host = hosts.get(root) ?? startInvariantHost(root)
  48. const callback = this.resolve(plugin)
  49. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  50. if (existing !== undefined) {
  51. return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
  52. }
  53. const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
  54. // A root-level await is the test's composition boundary. Nested plugin
  55. // fibers must not await their own companion parent through the global host.
  56. if (this.ctx !== root) return fiber
  57. return joinInvariantStartup(fiber, host.ready)
  58. }
  59. function usesManualInvariantTree(): boolean {
  60. const testPath = expect.getState().testPath?.replaceAll('\\', '/') ?? ''
  61. return MANUAL_INVARIANT_TESTS.some(path => testPath.endsWith(path))
  62. }
  63. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  64. /**
  65. * Select the package companions that an ordinary test root must register.
  66. * Package tests receive their owner's checks; the dedicated topology test
  67. * receives every owner so coverage and exhaustive runtime registration remain
  68. * independently enforced.
  69. * @param testPath - absolute or repo-relative normalized Vitest file path.
  70. * @returns sorted `import.meta.glob` keys for companions to mount.
  71. */
  72. export function testInvariantCompanionPaths(testPath: string): string[] {
  73. const normalized = testPath.replaceAll('\\', '/')
  74. const allPaths = Object.keys(testInvariantCompanions).sort()
  75. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  76. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  77. if (owner === null) return []
  78. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  79. if (testInvariantCompanions[companionPath] === undefined) {
  80. throw new Error(`test invariants: package test has no companion at ${companionPath}`)
  81. }
  82. return [companionPath]
  83. }
  84. function startInvariantHost(root: Context): InvariantHost {
  85. const fibers: PluginFiber[] = []
  86. const byCallback = new Map<unknown, PluginFiber>()
  87. const mount = (plugin: Plugin, config?: unknown): void => {
  88. const fiber = originalPlugin.call(root.registry, plugin, config)
  89. const callback = root.registry.resolve(plugin)
  90. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  91. fibers.push(fiber)
  92. byCallback.set(callback, fiber)
  93. }
  94. mount(InvariantService, { enabled: true })
  95. const testPath = expect.getState().testPath ?? ''
  96. const companionPaths = testInvariantCompanionPaths(testPath)
  97. for (const path of companionPaths) {
  98. const companion = testInvariantCompanions[path]
  99. if (companion === undefined) {
  100. throw new Error(`test invariants: selected companion vanished at ${path}`)
  101. }
  102. if (!companion.inject.includes('invariants')) {
  103. throw new Error(`test invariants: ${path} must inject the invariant service`)
  104. }
  105. mount(companion)
  106. }
  107. const [serviceFiber, ...companionFibers] = fibers
  108. if (serviceFiber === undefined) throw new Error('test invariants: service fiber was not mounted')
  109. // A companion is initially PENDING on the invariant service, and Cordis
  110. // Fiber.await() only joins work already in flight. Wait for the service to
  111. // activate its dependants before joining their startup and failures.
  112. const ready = serviceFiber.await()
  113. .then(() => Promise.all(companionFibers.map(fiber => fiber.await())))
  114. .then(() => undefined)
  115. const host = { fibers, byCallback, ready }
  116. hosts.set(root, host)
  117. return host
  118. }
  119. function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
  120. const readiness = fiber.await().then(async (loaded) => {
  121. await invariantReady
  122. return loaded
  123. })
  124. const joined = Object.create(fiber) as PluginFiber
  125. joined.then = readiness.then.bind(readiness)
  126. return joined
  127. }