test-invariants.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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/compact/compact/tests/invariant.spec.ts',
  30. '/packages/context/time-context/tests/invariant.spec.ts',
  31. '/packages/core/session/tests/invariant.spec.ts',
  32. '/packages/core/agent/tests/invariant.spec.ts',
  33. '/packages/core/scope/tests/invariant.spec.ts',
  34. '/packages/core/agent-loop/tests/invariant.spec.ts',
  35. '/packages/core/system-prompt/tests/invariant.spec.ts',
  36. '/packages/core/tools/tests/invariant.spec.ts',
  37. '/packages/fs/fs/tests/invariant.spec.ts',
  38. '/packages/hooks/hook-protocol/tests/invariant.spec.ts',
  39. '/packages/llm/llm/tests/invariant.spec.ts',
  40. '/packages/sandbox/sandbox-policy/tests/invariant.spec.ts',
  41. '/packages/subagent/subagent/tests/invariant.spec.ts',
  42. '/packages/tasks/tasks/tests/invariant.spec.ts',
  43. '/packages/todo/tool-todo/tests/invariant.spec.ts',
  44. '/packages/ui/permission/tests/invariant.spec.ts',
  45. '/packages/ui/user-approval/tests/invariant.spec.ts',
  46. '/packages/workflow/workflow/tests/invariant.spec.ts',
  47. '/packages/examples/agent-spine-demo/tests/agent-core.spec.ts',
  48. ] as const
  49. interface InvariantHost {
  50. readonly fibers: readonly PluginFiber[]
  51. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  52. readonly ready: Promise<void>
  53. }
  54. type PluginFiber = ReturnType<RegistryService['plugin']>
  55. const hosts = new WeakMap<Context, InvariantHost>()
  56. // eslint-disable-next-line @typescript-eslint/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  57. const originalPlugin = RegistryService.prototype.plugin
  58. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  59. if (usesManualInvariantTree()) return originalPlugin.call(this, plugin, config, getOuterStack)
  60. const root = this.ctx.root
  61. const host = hosts.get(root) ?? startInvariantHost(root)
  62. const callback = this.resolve(plugin)
  63. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  64. if (existing !== undefined) {
  65. return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
  66. }
  67. const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
  68. // A root-level await is the test's composition boundary. Nested plugin
  69. // fibers must not await their own companion parent through the global host.
  70. if (this.ctx !== root) return fiber
  71. return joinInvariantStartup(fiber, host.ready)
  72. }
  73. function usesManualInvariantTree(): boolean {
  74. const testPath = expect.getState().testPath?.replaceAll('\\', '/') ?? ''
  75. return MANUAL_INVARIANT_TESTS.some(path => testPath.endsWith(path))
  76. }
  77. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  78. /**
  79. * Select the package companions that an ordinary test root must register.
  80. * Package tests receive their owner's checks; the dedicated topology test
  81. * receives every owner so coverage and exhaustive runtime registration remain
  82. * independently enforced.
  83. * @param testPath - absolute or repo-relative normalized Vitest file path.
  84. * @returns sorted `import.meta.glob` keys for companions to mount.
  85. */
  86. export function testInvariantCompanionPaths(testPath: string): string[] {
  87. const normalized = testPath.replaceAll('\\', '/')
  88. const allPaths = Object.keys(testInvariantCompanions).sort()
  89. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  90. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  91. if (owner === null) return []
  92. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  93. if (testInvariantCompanions[companionPath] === undefined) {
  94. throw new Error(`test invariants: package test has no companion at ${companionPath}`)
  95. }
  96. return [companionPath]
  97. }
  98. function startInvariantHost(root: Context): InvariantHost {
  99. const fibers: PluginFiber[] = []
  100. const byCallback = new Map<unknown, PluginFiber>()
  101. const mount = (plugin: Plugin, config?: unknown): void => {
  102. const fiber = originalPlugin.call(root.registry, plugin, config)
  103. const callback = root.registry.resolve(plugin)
  104. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  105. fibers.push(fiber)
  106. byCallback.set(callback, fiber)
  107. }
  108. mount(InvariantService, { enabled: true })
  109. const testPath = expect.getState().testPath ?? ''
  110. const companionPaths = testInvariantCompanionPaths(testPath)
  111. for (const path of companionPaths) {
  112. const companion = testInvariantCompanions[path]
  113. if (companion === undefined) {
  114. throw new Error(`test invariants: selected companion vanished at ${path}`)
  115. }
  116. if (!companion.inject.includes('invariants')) {
  117. throw new Error(`test invariants: ${path} must inject the invariant service`)
  118. }
  119. mount(companion)
  120. }
  121. const [serviceFiber, ...companionFibers] = fibers
  122. if (serviceFiber === undefined) throw new Error('test invariants: service fiber was not mounted')
  123. // A companion is initially PENDING on the invariant service, and Cordis
  124. // Fiber.await() only joins work already in flight. Wait for the service to
  125. // activate its dependants before joining their startup and failures.
  126. const ready = serviceFiber.await()
  127. .then(() => Promise.all(companionFibers.map(fiber => fiber.await())))
  128. .then(() => undefined)
  129. const host = { fibers, byCallback, ready }
  130. hosts.set(root, host)
  131. return host
  132. }
  133. function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
  134. const readiness = fiber.await().then(async (loaded) => {
  135. await invariantReady
  136. return loaded
  137. })
  138. const joined = Object.create(fiber) as PluginFiber
  139. joined.then = readiness.then.bind(readiness)
  140. return joined
  141. }