command-goal.spec.ts 9.5 KB

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