command-goal.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import AgentRegistry, { AgentMessageId } from '@deepseek-ai/dsh-agent'
  5. import type { Agent, AgentStatus, InjectOptions } from '@deepseek-ai/dsh-agent'
  6. import CommandService from '@deepseek-ai/dsh-commands'
  7. import GoalService from '@deepseek-ai/dsh-goal'
  8. import type { GoalRef } from '@deepseek-ai/dsh-goal'
  9. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  10. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  11. import * as commandGoal from '@deepseek-ai/dsh-command-goal'
  12. interface Harness {
  13. readonly ctx: Context
  14. readonly agent: Agent
  15. readonly session: Session
  16. readonly plugin: Awaited<ReturnType<Context['plugin']>>
  17. }
  18. /** Number the next balanced injection or message turn. */
  19. function nextTurn(session: Session): number {
  20. return session.events.reduce(
  21. (maximum, event) => event.type === 'turn/start' ? Math.max(maximum, event.data.turn) : maximum,
  22. 0,
  23. ) + 1
  24. }
  25. /** Append one idle injection using the public Agent contract's balanced shape. */
  26. function appendInjection(session: Session, content: ContentBlock[], options?: InjectOptions): void {
  27. const source: MessageSource = options?.source ?? { kind: 'plugin', plugin: '' }
  28. const turn = nextTurn(session)
  29. session.append('turn/start', { turn, trigger: { kind: 'injection', source } })
  30. session.append('user/message', {
  31. content,
  32. source,
  33. ...options?.meta === undefined ? {} : { meta: options.meta },
  34. }, { surfaceOp: 'append' })
  35. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  36. }
  37. /** Build a live idle agent accepted by the exact-identity goal service. */
  38. function stubAgent(id: string): { agent: Agent; session: Session } {
  39. const session = new Session(SessionId(id))
  40. let status: AgentStatus = 'idle'
  41. const agent: Agent = {
  42. id: session.id,
  43. options: {},
  44. session,
  45. ctx: new Context(),
  46. get status() { return status },
  47. followup: () => AgentMessageId('stub'),
  48. queue: () => AgentMessageId('stub'),
  49. steer: () => AgentMessageId('stub'),
  50. inject(content, options) { appendInjection(session, content, options); return AgentMessageId('stub') },
  51. send: () => AgentMessageId('stub'),
  52. cancel() { status = 'idle' },
  53. whenIdle() { return Promise.resolve() },
  54. }
  55. return { agent, session }
  56. }
  57. /** Mount the real command registry, goal domain, and producer. */
  58. async function harness(): Promise<Harness> {
  59. const ctx = new Context()
  60. await ctx.plugin(CommandService)
  61. await ctx.plugin(AgentRegistry)
  62. await ctx.plugin(GoalService)
  63. const plugin = await ctx.plugin(commandGoal)
  64. const { agent, session } = stubAgent(`command-goal-${Math.random()}`)
  65. ctx.agents.register(agent)
  66. return { ctx, agent, session, plugin }
  67. }
  68. /** Execute `/goal` through the same registry boundary as a UI adapter. */
  69. async function run(test: Harness, suffix = ''): Promise<NonNullable<Awaited<ReturnType<CommandService['execute']>>>> {
  70. const result = await test.ctx.commands.execute(
  71. test.agent,
  72. `/goal${suffix}`,
  73. new AbortController().signal,
  74. )
  75. if (result === undefined) throw new Error('goal command was not registered')
  76. return result
  77. }
  78. /** Current exact compare-and-set ref. */
  79. function ref(goal: NonNullable<ReturnType<GoalService['get']>>): GoalRef {
  80. return { id: goal.id, revision: goal.revision }
  81. }
  82. describe('@deepseek-ai/dsh-command-goal registration', () => {
  83. it('registers one global command with Loader-safe exports and disposes it', async () => {
  84. const test = await harness()
  85. expect(commandGoal.name).toBe('command-goal')
  86. expect(commandGoal.inject).toEqual(['commands', 'goals'])
  87. expect('default' in commandGoal).toBe(false)
  88. const loader = Object.create(Loader.prototype) as Loader
  89. expect(loader.unwrapExports(commandGoal)).toBe(commandGoal)
  90. expect(test.ctx.commands.list(test.agent)).toContainEqual({
  91. name: 'goal',
  92. description: 'set or view the goal for a long-running task',
  93. input: { hint: '[<objective>|clear|edit <objective>|pause|resume]' },
  94. })
  95. expect(test.ctx.commands.find(test.agent, 'goal')).toBeDefined()
  96. await test.plugin.dispose()
  97. expect(test.ctx.commands.find(test.agent, 'goal')).toBeUndefined()
  98. })
  99. })
  100. describe('/goal human command', () => {
  101. it('shows an empty status without mutating the session', async () => {
  102. const test = await harness()
  103. await expect(run(test)).resolves.toEqual({
  104. kind: 'success',
  105. text: 'No goal is currently set.\nUsage: /goal [<objective>|clear|edit <objective>|pause|resume]',
  106. })
  107. expect(test.session.events).toEqual([])
  108. })
  109. it('creates a trimmed objective and refuses silent replacement of unfinished work', async () => {
  110. const test = await harness()
  111. const created = await run(test, '\n finish the release ')
  112. expect(created.kind).toBe('success')
  113. expect(created.text).toContain('Goal created\nStatus: active')
  114. expect(created.text).toContain('Objective: finish the release')
  115. expect(created.text).toContain('Rounds: 0/256')
  116. expect(created.text).toContain('Activation: armed')
  117. expect(test.ctx.goals.get(test.agent)?.objective).toBe('finish the release')
  118. expect(test.session.events.map(event => event.type)).toEqual(['turn/start', 'user/message', 'turn/end'])
  119. const count = test.session.events.length
  120. await expect(run(test, ' replacement')).resolves.toEqual({
  121. kind: 'error',
  122. text: 'A goal is already active. Use /goal edit <objective> to change it or /goal clear before replacing it.',
  123. })
  124. expect(test.session.events).toHaveLength(count)
  125. })
  126. it('treats only exact control words as controls', async () => {
  127. const test = await harness()
  128. await run(test, ' pause everything only after verification')
  129. expect(test.ctx.goals.get(test.agent)?.objective).toBe('pause everything only after verification')
  130. })
  131. it('edits inline, requires an objective, and starts a new goal when the old one is complete', async () => {
  132. const empty = await harness()
  133. const invalidEdit = await run(empty, ' edit')
  134. expect(invalidEdit.kind).toBe('error')
  135. expect(invalidEdit.text).toContain('requires a replacement objective')
  136. const missingEdit = await run(empty, ' edit replacement')
  137. expect(missingEdit.kind).toBe('error')
  138. expect(missingEdit.text).toContain('/goal edit requires one')
  139. const test = await harness()
  140. await run(test, ' first')
  141. const first = test.ctx.goals.get(test.agent)!
  142. const updated = await run(test, ' EDIT\n second ')
  143. expect(updated.kind).toBe('success')
  144. expect(updated.text).toContain('Goal updated')
  145. expect(test.ctx.goals.get(test.agent)).toMatchObject({ id: first.id, objective: 'second', revision: 2 })
  146. const current = test.ctx.goals.get(test.agent)!
  147. test.ctx.goals.complete(test.agent, ref(current))
  148. const replacement = await run(test, ' edit third')
  149. expect(replacement.kind).toBe('success')
  150. expect(replacement.text).toContain('Goal created')
  151. expect(test.ctx.goals.get(test.agent)).toMatchObject({ objective: 'third', revision: 1 })
  152. expect(test.ctx.goals.get(test.agent)?.id).not.toBe(first.id)
  153. })
  154. it('returns direct missing-state results for pause, resume, and clear', async () => {
  155. const test = await harness()
  156. const missingPause = await run(test, ' pause')
  157. expect(missingPause.kind).toBe('error')
  158. expect(missingPause.text).toContain('/goal pause requires one')
  159. const missingResume = await run(test, ' resume')
  160. expect(missingResume.kind).toBe('error')
  161. expect(missingResume.text).toContain('/goal resume requires one')
  162. await expect(run(test, ' clear')).resolves.toEqual({ kind: 'success', text: 'No goal to clear.' })
  163. })
  164. it('pauses, resumes, clears, and converts expected domain rejections to command errors', async () => {
  165. const test = await harness()
  166. await run(test, ' work')
  167. const redundantResume = await run(test, ' RESUME')
  168. expect(redundantResume).toEqual({
  169. kind: 'error',
  170. text: 'The goal command is not valid for the current state. Run /goal to view available commands.',
  171. })
  172. const paused = await run(test, ' PAUSE')
  173. expect(paused.kind).toBe('success')
  174. expect(paused.text).toContain('Goal paused')
  175. expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'paused', activation: 'disarmed' })
  176. const resumed = await run(test, ' resume')
  177. expect(resumed.kind).toBe('success')
  178. expect(resumed.text).toContain('Goal resumed')
  179. expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', activation: 'armed' })
  180. await expect(run(test, ' clear')).resolves.toEqual({ kind: 'success', text: 'Goal cleared.' })
  181. expect(test.ctx.goals.get(test.agent)).toBeUndefined()
  182. })
  183. it('shows every durable phase and distinguishes disarmed active state', async () => {
  184. const test = await harness()
  185. test.ctx.goals.create(test.agent, { objective: 'state matrix', maxGoalRounds: 1 })
  186. test.ctx.goals.disarm(test.agent)
  187. expect((await run(test)).text)
  188. .toContain('Status: active\nObjective: state matrix\nRounds: 0/1\nActivation: disarmed')
  189. expect((await run(test)).text).toContain('/goal resume')
  190. let goal = test.ctx.goals.get(test.agent)!
  191. goal = test.ctx.goals.resume(test.agent, ref(goal))
  192. goal = test.ctx.goals.pause(test.agent, ref(goal))
  193. expect((await run(test)).text).toContain('Status: paused')
  194. goal = test.ctx.goals.resume(test.agent, ref(goal))
  195. goal = test.ctx.goals.block(test.agent, ref(goal), {
  196. code: 'upstream-unavailable',
  197. message: 'Provider unavailable',
  198. })
  199. const blocked = await run(test)
  200. expect(blocked.text).toContain('Status: blocked')
  201. expect(blocked.text).toContain('Blocker: upstream-unavailable: Provider unavailable')
  202. goal = test.ctx.goals.resume(test.agent, ref(goal))
  203. test.ctx.goals.complete(test.agent, ref(goal))
  204. const complete = await run(test)
  205. expect(complete.text).toContain('Status: complete')
  206. expect(complete.text).toContain('Commands: /goal <objective>, /goal clear')
  207. })
  208. it('does not turn unexpected implementation failures into expected command results', async () => {
  209. const test = await harness()
  210. vi.spyOn(test.ctx.goals, 'get').mockImplementationOnce(() => { throw new Error('unexpected failure') })
  211. await expect(run(test)).rejects.toThrow('unexpected failure')
  212. })
  213. })