app-boot.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join, resolve, sep } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from 'cordis'
  6. import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  7. import {
  8. addHarnessSourceSection, assertEntriesLoaded, boot, HARNESS_SOURCE_SECTION,
  9. installFailLoud, loadEnv, resolveConfigPath, type FailLoudProcess,
  10. } from '../src/index.ts'
  11. const NAME = 'dsh-test-bin'
  12. const tmp = (): string => mkdtempSync(join(tmpdir(), 'dsh-app-boot-'))
  13. describe('resolveConfigPath', () => {
  14. it('resolves relative to the given cwd outside replay mode', () => {
  15. expect(resolveConfigPath('./cordis.yml', undefined, `${sep}base`)).toBe(resolve(`${sep}base`, 'cordis.yml'))
  16. expect(resolveConfigPath('conf/app.yaml', 'record', `${sep}base`)).toBe(resolve(`${sep}base`, 'conf/app.yaml'))
  17. })
  18. it('swaps a cordis.yml/.yaml basename for cordis.snapshot.yml in replay mode', () => {
  19. expect(resolveConfigPath('./cordis.yml', 'replay', `${sep}base`)).toBe(resolve(`${sep}base`, 'cordis.snapshot.yml'))
  20. expect(resolveConfigPath('deep/cordis.yaml', 'replay', `${sep}base`)).toBe(resolve(`${sep}base`, 'deep/cordis.snapshot.yml'))
  21. })
  22. it('leaves a non-cordis basename alone in replay mode and defaults cwd to the process cwd', () => {
  23. expect(resolveConfigPath('custom.yml', 'replay', `${sep}base`)).toBe(resolve(`${sep}base`, 'custom.yml'))
  24. expect(resolveConfigPath('./x.yml', undefined)).toBe(resolve(process.cwd(), 'x.yml'))
  25. })
  26. })
  27. describe('loadEnv', () => {
  28. it('loads variables from .env in the given dir', () => {
  29. const dir = tmp()
  30. writeFileSync(join(dir, '.env'), 'DSH_APP_BOOT_SPEC_VAR=loaded\n')
  31. const warn = vi.fn()
  32. loadEnv(NAME, dir, warn)
  33. expect(process.env['DSH_APP_BOOT_SPEC_VAR']).toBe('loaded')
  34. expect(warn).not.toHaveBeenCalled()
  35. delete process.env['DSH_APP_BOOT_SPEC_VAR']
  36. })
  37. it('stays silent when no .env exists (ambient environment wins)', () => {
  38. const warn = vi.fn()
  39. loadEnv(NAME, tmp(), warn)
  40. expect(warn).not.toHaveBeenCalled()
  41. })
  42. it('warns (labelled, single line) when .env exists but cannot be loaded', () => {
  43. const dir = tmp()
  44. mkdirSync(join(dir, '.env')) // a directory named .env: present, unreadable as a file
  45. const warn = vi.fn()
  46. loadEnv(NAME, dir, warn)
  47. expect(warn).toHaveBeenCalledTimes(1)
  48. expect(warn.mock.calls[0]?.[0]).toMatch(new RegExp(`^${NAME}: failed to load \\.env: `))
  49. })
  50. it('defaults dir to the process cwd and warn to a stderr write', () => {
  51. const dir = tmp()
  52. writeFileSync(join(dir, '.env'), 'DSH_APP_BOOT_SPEC_DEFAULTS=yes\n')
  53. const previous = process.cwd()
  54. process.chdir(dir)
  55. try {
  56. loadEnv(NAME) // happy path: the default warn sink is never invoked
  57. } finally {
  58. process.chdir(previous)
  59. }
  60. expect(process.env['DSH_APP_BOOT_SPEC_DEFAULTS']).toBe('yes')
  61. delete process.env['DSH_APP_BOOT_SPEC_DEFAULTS']
  62. // The default warn sink itself: point it at a broken .env with stderr
  63. // spied, so the arrow body runs without polluting the test output.
  64. const broken = tmp()
  65. mkdirSync(join(broken, '.env'))
  66. const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
  67. let written: string[]
  68. try {
  69. loadEnv(NAME, broken)
  70. written = write.mock.calls.map(call => String(call[0]))
  71. } finally {
  72. write.mockRestore()
  73. }
  74. expect(written).toHaveLength(1)
  75. expect(written[0]).toContain(`${NAME}: failed to load .env: `)
  76. })
  77. })
  78. describe('installFailLoud', () => {
  79. function fakeProc(): FailLoudProcess & { handlers: Array<(err: unknown) => void>; written: string[]; exits: number[] } {
  80. const handlers: Array<(err: unknown) => void> = []
  81. const written: string[] = []
  82. const exits: number[] = []
  83. return {
  84. handlers, written, exits,
  85. on: (_event, handler) => { handlers.push(handler) },
  86. off: (_event, handler) => { handlers.splice(handlers.indexOf(handler), 1) },
  87. stderr: { write: (chunk: string) => { written.push(chunk) } },
  88. exit: (code: number) => { exits.push(code) },
  89. }
  90. }
  91. it('writes one labelled line with the stack and exits 1 on an Error rejection', () => {
  92. const proc = fakeProc()
  93. installFailLoud(NAME, proc)
  94. const error = new Error('boom')
  95. proc.handlers[0]!(error)
  96. expect(proc.written[0]).toContain(`${NAME}: fatal load failure: `)
  97. expect(proc.written[0]).toContain(error.stack)
  98. expect(proc.exits).toEqual([1])
  99. })
  100. it('stringifies a non-Error rejection and an Error without a stack falls back to its message', () => {
  101. const proc = fakeProc()
  102. installFailLoud(NAME, proc)
  103. proc.handlers[0]!('plain failure')
  104. expect(proc.written[0]).toContain('plain failure')
  105. const stackless = new Error('no stack')
  106. delete (stackless as { stack?: string }).stack
  107. proc.handlers[0]!(stackless)
  108. expect(proc.written[1]).toContain('no stack')
  109. expect(proc.exits).toEqual([1, 1])
  110. })
  111. it('returns an uninstaller that removes the handler (and defaults to the real process)', () => {
  112. const proc = fakeProc()
  113. const uninstall = installFailLoud(NAME, proc)
  114. expect(proc.handlers).toHaveLength(1)
  115. uninstall()
  116. expect(proc.handlers).toHaveLength(0)
  117. // Default-proc arm: install on the real process, then immediately uninstall
  118. // so the suite leaks no handler and can never exit the runner.
  119. const before = process.listenerCount('unhandledRejection')
  120. const uninstallReal = installFailLoud(NAME)
  121. expect(process.listenerCount('unhandledRejection')).toBe(before + 1)
  122. uninstallReal()
  123. expect(process.listenerCount('unhandledRejection')).toBe(before)
  124. })
  125. })
  126. describe('assertEntriesLoaded', () => {
  127. const ctxWith = (entries: Array<{ fiber?: unknown; disabled?: boolean; options: { name?: string } }>): Context =>
  128. ({ loader: { entries: () => entries } }) as unknown as Context
  129. it('passes when every enabled entry has a fiber', () => {
  130. expect(() => { assertEntriesLoaded(ctxWith([
  131. { fiber: {}, options: { name: 'a' } },
  132. { disabled: true, options: { name: 'off' } },
  133. ]), NAME) }).not.toThrow()
  134. })
  135. it('throws naming every enabled fiber-less entry', () => {
  136. expect(() => { assertEntriesLoaded(ctxWith([
  137. { fiber: {}, options: { name: 'ok' } },
  138. { options: { name: 'broken-a' } },
  139. { options: { name: 'broken-b' } },
  140. ]), NAME) }).toThrow(`${NAME}: plugin(s) failed to load: broken-a, broken-b`)
  141. })
  142. })
  143. describe('boot', () => {
  144. it('boots a leaf config through the real Loader and settles the tree', async () => {
  145. const dir = tmp()
  146. writeFileSync(join(dir, 'noop.mjs'), 'export const name = "noop"\nexport function apply() {}\n')
  147. writeFileSync(join(dir, 'cordis.yml'), '- id: noop\n name: ./noop.mjs\n')
  148. const ctx = await boot(NAME, join(dir, 'cordis.yml'))
  149. try {
  150. const entries = [...ctx.loader.entries()]
  151. expect(entries.some(entry => entry.options.name === './noop.mjs' && entry.fiber !== undefined)).toBe(true)
  152. } finally {
  153. await ctx.fiber.dispose()
  154. }
  155. })
  156. it('runs host preparation before the Loader tree mounts', async () => {
  157. const dir = tmp()
  158. writeFileSync(join(dir, 'noop.mjs'), 'export const name = "noop"\nexport function apply() {}\n')
  159. writeFileSync(join(dir, 'cordis.yml'), '- id: noop\n name: ./noop.mjs\n')
  160. const prepared: Context[] = []
  161. const ctx = await boot(NAME, join(dir, 'cordis.yml'), undefined, (hostCtx) => { prepared.push(hostCtx) })
  162. try {
  163. expect(prepared).toEqual([ctx])
  164. } finally {
  165. await ctx.fiber.dispose()
  166. }
  167. })
  168. it('rejects (never exits 0 half-empty) when a config names a plugin that cannot be imported', async () => {
  169. const dir = tmp()
  170. writeFileSync(join(dir, 'cordis.yml'), '- id: ghost\n name: ./missing.mjs\n')
  171. await expect(boot(NAME, join(dir, 'cordis.yml'))).rejects.toThrow(`${NAME}: plugin(s) failed to load: ./missing.mjs`)
  172. })
  173. })
  174. describe('addHarnessSourceSection', () => {
  175. const SOURCE_ROOT = `${sep}opt${sep}harness-src`
  176. const EXPECTED = `Your own source code is the checkout at ${SOURCE_ROOT}; you can read it there to learn how dsh works and how to extend it.`
  177. it('adds the source path between the harness identity and the deployment persona', async () => {
  178. const ctx = new Context()
  179. try {
  180. await ctx.plugin(SystemPrompt, { persona: 'You are a coding agent.' })
  181. const dispose = addHarnessSourceSection(ctx, SOURCE_ROOT)
  182. expect(dispose).toBeTypeOf('function')
  183. const systemPrompt = ctx.get('systemPrompt')!
  184. const rendered = renderPrompt(await systemPrompt.assemble())
  185. expect(rendered).toContain(EXPECTED)
  186. // Harness-owned opener (-100) → source (-99) → persona (0). The >= 0 guards
  187. // keep a drifted opener/persona string from a false pass through `-1 < n`.
  188. const identityAt = rendered.indexOf('You are an AI agent powered by the DeepSeek Harness SDK.')
  189. const sourceAt = rendered.indexOf(EXPECTED)
  190. const personaAt = rendered.indexOf('You are a coding agent.')
  191. expect(identityAt).toBeGreaterThanOrEqual(0)
  192. expect(personaAt).toBeGreaterThanOrEqual(0)
  193. expect(identityAt).toBeLessThan(sourceAt)
  194. expect(sourceAt).toBeLessThan(personaAt)
  195. } finally {
  196. await ctx.fiber.dispose()
  197. }
  198. })
  199. it('is a no-op returning undefined when no systemPrompt service is mounted', async () => {
  200. const ctx = new Context()
  201. try {
  202. expect(addHarnessSourceSection(ctx, SOURCE_ROOT)).toBeUndefined()
  203. } finally {
  204. await ctx.fiber.dispose()
  205. }
  206. })
  207. it('disposes the section it added, so a systemPrompt reload leaves no residue', async () => {
  208. const ctx = new Context()
  209. try {
  210. await ctx.plugin(SystemPrompt, {})
  211. const systemPrompt = ctx.get('systemPrompt')!
  212. const dispose = addHarnessSourceSection(ctx, SOURCE_ROOT)!
  213. const present = await systemPrompt.assemble()
  214. expect(present.sections.some(section => section.name === HARNESS_SOURCE_SECTION)).toBe(true)
  215. dispose()
  216. const gone = await systemPrompt.assemble()
  217. expect(gone.sections.some(section => section.name === HARNESS_SOURCE_SECTION)).toBe(false)
  218. } finally {
  219. await ctx.fiber.dispose()
  220. }
  221. })
  222. })