command-goal.spec.ts 10 KB

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