local-thread-goal-orchestrator.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /**
  2. * Tests for the Thread Goal continuation orchestrator.
  3. *
  4. * Mocks the `runOneTurn` callback and the `ThreadGoalStore` to verify:
  5. * (a) active goal triggers continuation turns,
  6. * (b) terminal status breaks the loop,
  7. * (c) paused breaks the loop without marking blocked,
  8. * (d) an unclassified legacy turn error pauses the goal as retryable,
  9. * (e) safety retraction pauses the goal and short-circuits,
  10. * (f) abort signal short-circuits.
  11. */
  12. import { beforeEach, describe, expect, it, vi } from "vitest";
  13. import {
  14. ThreadGoalAlreadyExistsError,
  15. type ThreadGoalBreakerResult,
  16. type ThreadGoalCreateInput,
  17. type ThreadGoalPatchInput,
  18. type ThreadGoalState,
  19. type ThreadGoalStore,
  20. } from "@mavis/goal";
  21. import {
  22. createThreadGoalContinuationOrchestrator,
  23. type ThreadGoalTurnStatus,
  24. } from "../../src/thread-goal/orchestrator.js";
  25. class InMemoryThreadGoalStore implements ThreadGoalStore {
  26. private bySession = new Map<string, ThreadGoalState>();
  27. private byId = new Map<string, ThreadGoalState>();
  28. private seq = 0;
  29. public now = 1_700_000_000_000;
  30. async getBySession(sessionId: string): Promise<ThreadGoalState | undefined> {
  31. return this.bySession.get(sessionId);
  32. }
  33. async getById(goalId: string): Promise<ThreadGoalState | undefined> {
  34. return this.byId.get(goalId);
  35. }
  36. async create(input: ThreadGoalCreateInput): Promise<ThreadGoalState> {
  37. const existing = this.bySession.get(input.sessionId);
  38. // codex parity: only a complete goal is replaceable.
  39. if (existing && existing.status !== "complete") {
  40. throw new ThreadGoalAlreadyExistsError(existing.goalId);
  41. }
  42. if (existing) {
  43. this.byId.delete(existing.goalId);
  44. }
  45. this.seq += 1;
  46. const goal: ThreadGoalState = {
  47. goalId: `tg_${this.seq}`,
  48. sessionId: input.sessionId,
  49. objective: input.objective,
  50. status: "active",
  51. createdAt: this.now,
  52. updatedAt: this.now,
  53. tokensUsed: 0,
  54. turnsUsed: 0,
  55. timeUsedSeconds: 0,
  56. tokenBudget: input.tokenBudget ?? null,
  57. replyFingerprint: null,
  58. noProgressStreak: 0,
  59. noToolStreak: 0,
  60. lastVerification: undefined,
  61. statusReason: null,
  62. kickoffAttachments: (input.kickoffAttachments ?? []).map(
  63. (attachment) => ({
  64. ...attachment,
  65. }),
  66. ),
  67. kickoffState: "pending",
  68. };
  69. this.bySession.set(input.sessionId, goal);
  70. this.byId.set(goal.goalId, goal);
  71. return goal;
  72. }
  73. async patch(
  74. goalId: string,
  75. input: ThreadGoalPatchInput,
  76. ): Promise<ThreadGoalState> {
  77. const existing = this.byId.get(goalId);
  78. if (!existing) throw new Error(`goal ${goalId} not found`);
  79. this.now += 1;
  80. const next: ThreadGoalState = {
  81. ...existing,
  82. status: input.status ?? existing.status,
  83. objective: input.objective ?? existing.objective,
  84. statusReason:
  85. input.statusReason === undefined
  86. ? existing.statusReason
  87. : input.statusReason,
  88. updatedAt: this.now,
  89. };
  90. this.byId.set(goalId, next);
  91. this.bySession.set(existing.sessionId, next);
  92. return next;
  93. }
  94. async updateBreaker(): Promise<ThreadGoalBreakerResult> {
  95. return { action: "stale", staleReason: "missing_goal" };
  96. }
  97. async delete(goalId: string): Promise<void> {
  98. const existing = this.byId.get(goalId);
  99. if (!existing) return;
  100. this.byId.delete(goalId);
  101. this.bySession.delete(existing.sessionId);
  102. }
  103. }
  104. const SESSION_ID = "sess_orch_a";
  105. let turnSeq = 0;
  106. function nextTurn(): string {
  107. turnSeq += 1;
  108. return `turn_${turnSeq}`;
  109. }
  110. describe("ThreadGoalContinuationOrchestrator", () => {
  111. let store: InMemoryThreadGoalStore;
  112. beforeEach(() => {
  113. store = new InMemoryThreadGoalStore();
  114. turnSeq = 0;
  115. });
  116. it("runs exactly one turn when no goal exists", async () => {
  117. const runOneTurn = vi.fn(async () => "finished" as ThreadGoalTurnStatus);
  118. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  119. const outcome = await orchestrator.run({
  120. sessionId: SESSION_ID,
  121. initialPromptText: "hello",
  122. initialTurnId: "turn_0",
  123. generateTurnId: nextTurn,
  124. runOneTurn,
  125. });
  126. expect(outcome).toEqual({
  127. outcome: "no-active-goal",
  128. turnsRun: 1,
  129. lastStatus: "finished",
  130. });
  131. expect(runOneTurn).toHaveBeenCalledTimes(1);
  132. });
  133. it("continues turns while the goal is active, then stops on complete", async () => {
  134. await store.create({ sessionId: SESSION_ID, objective: "x" });
  135. const runOneTurn = vi.fn(async (input) => {
  136. // On the SECOND turn the model "calls update_goal complete".
  137. if (input.turnId === "turn_1") {
  138. const g = await store.getBySession(SESSION_ID);
  139. if (g) await store.patch(g.goalId, { status: "complete" });
  140. }
  141. return "finished" as ThreadGoalTurnStatus;
  142. });
  143. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  144. const outcome = await orchestrator.run({
  145. sessionId: SESSION_ID,
  146. initialPromptText: "kickoff",
  147. initialTurnId: "turn_0",
  148. generateTurnId: nextTurn,
  149. runOneTurn,
  150. });
  151. expect(outcome.outcome).toBe("goal-finalized");
  152. expect(runOneTurn).toHaveBeenCalledTimes(2);
  153. expect((outcome as { finalGoal: ThreadGoalState }).finalGoal.status).toBe(
  154. "complete",
  155. );
  156. // Turn #2 is a continuation — verify the prompt is the rendered template.
  157. const secondCall = runOneTurn.mock.calls[1][0];
  158. expect(secondCall.isContinuation).toBe(true);
  159. expect(secondCall.promptText).toContain(
  160. "Continue working toward the active thread goal",
  161. );
  162. });
  163. it("uses the provided renderContinuation override for continuation turns (objective edit pivot)", async () => {
  164. await store.create({ sessionId: SESSION_ID, objective: "x" });
  165. const runOneTurn = vi.fn(async (input) => {
  166. // Stop after the continuation turn so the loop is bounded.
  167. if (input.isContinuation) {
  168. const g = await store.getBySession(SESSION_ID);
  169. if (g) await store.patch(g.goalId, { status: "complete" });
  170. }
  171. return "finished" as ThreadGoalTurnStatus;
  172. });
  173. const orchestrator = createThreadGoalContinuationOrchestrator(
  174. store,
  175. undefined,
  176. (g) => `OBJECTIVE_UPDATED_PROMPT for ${g.objective}`,
  177. );
  178. await orchestrator.run({
  179. sessionId: SESSION_ID,
  180. initialPromptText: "kickoff",
  181. initialTurnId: "turn_0",
  182. generateTurnId: nextTurn,
  183. runOneTurn,
  184. });
  185. // The continuation turn used the override, not the default template.
  186. const secondCall = runOneTurn.mock.calls[1][0];
  187. expect(secondCall.isContinuation).toBe(true);
  188. expect(secondCall.promptText).toBe("OBJECTIVE_UPDATED_PROMPT for x");
  189. });
  190. it("stops when goal status flips to paused mid-loop (user paused)", async () => {
  191. const goal = await store.create({ sessionId: SESSION_ID, objective: "x" });
  192. const runOneTurn = vi.fn(async () => {
  193. // Simulate the user pausing via UI: store flips status, the
  194. // orchestrator notices on the next iteration.
  195. await store.patch(goal.goalId, { status: "paused" });
  196. return "finished" as ThreadGoalTurnStatus;
  197. });
  198. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  199. const outcome = await orchestrator.run({
  200. sessionId: SESSION_ID,
  201. initialPromptText: "x",
  202. initialTurnId: "turn_0",
  203. generateTurnId: nextTurn,
  204. runOneTurn,
  205. });
  206. expect(outcome.outcome).toBe("goal-finalized");
  207. expect((outcome as { finalGoal: ThreadGoalState }).finalGoal.status).toBe(
  208. "paused",
  209. );
  210. expect(runOneTurn).toHaveBeenCalledTimes(1);
  211. });
  212. it("stops without blocking when the turn is waiting for the user", async () => {
  213. await store.create({ sessionId: SESSION_ID, objective: "x" });
  214. const runOneTurn = vi.fn(
  215. async () => "waiting_for_user" as ThreadGoalTurnStatus,
  216. );
  217. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  218. const outcome = await orchestrator.run({
  219. sessionId: SESSION_ID,
  220. initialPromptText: "x",
  221. initialTurnId: "turn_0",
  222. generateTurnId: nextTurn,
  223. runOneTurn,
  224. });
  225. expect(outcome).toEqual({ outcome: "waiting-for-user", turnsRun: 1 });
  226. expect(runOneTurn).toHaveBeenCalledTimes(1);
  227. expect((await store.getBySession(SESSION_ID))?.status).toBe("active");
  228. });
  229. it("pauses and stops after one turn when output safety retracts the turn", async () => {
  230. const active = await store.create({
  231. sessionId: SESSION_ID,
  232. objective: "x",
  233. });
  234. const onTurnRetracted = vi.fn(async (sessionId: string) => {
  235. expect(sessionId).toBe(SESSION_ID);
  236. return store.patch(active.goalId, { status: "paused" });
  237. });
  238. const runOneTurn = vi.fn(async () => "retracted" as ThreadGoalTurnStatus);
  239. const orchestrator = createThreadGoalContinuationOrchestrator(
  240. store,
  241. undefined,
  242. undefined,
  243. onTurnRetracted,
  244. );
  245. const outcome = await orchestrator.run({
  246. sessionId: SESSION_ID,
  247. initialPromptText: "x",
  248. initialTurnId: "turn_0",
  249. generateTurnId: nextTurn,
  250. runOneTurn,
  251. });
  252. expect(outcome).toEqual({
  253. outcome: "turn-retracted",
  254. turnsRun: 1,
  255. finalGoal: expect.objectContaining({ status: "paused" }),
  256. });
  257. expect(runOneTurn).toHaveBeenCalledTimes(1);
  258. expect(onTurnRetracted).toHaveBeenCalledTimes(1);
  259. expect((await store.getBySession(SESSION_ID))?.status).toBe("paused");
  260. });
  261. it("pauses the goal as retryable when the legacy loop sees an unclassified error", async () => {
  262. await store.create({ sessionId: SESSION_ID, objective: "x" });
  263. const runOneTurn = vi.fn(async () => "error" as ThreadGoalTurnStatus);
  264. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  265. const outcome = await orchestrator.run({
  266. sessionId: SESSION_ID,
  267. initialPromptText: "x",
  268. initialTurnId: "turn_0",
  269. generateTurnId: nextTurn,
  270. runOneTurn,
  271. });
  272. expect(outcome.outcome).toBe("turn-errored");
  273. const goal = await store.getBySession(SESSION_ID);
  274. expect(goal).toMatchObject({
  275. status: "paused",
  276. statusReason: "paused(infra_retryable)",
  277. });
  278. });
  279. it("does NOT block when the abort signal fires after a clean turn (codex on_turn_abort)", async () => {
  280. const goal = await store.create({ sessionId: SESSION_ID, objective: "x" });
  281. const abort = new AbortController();
  282. const runOneTurn = vi.fn(async () => {
  283. // Trip the abort signal during the first turn; the orchestrator
  284. // should detect it before scheduling a continuation.
  285. abort.abort();
  286. return "finished" as ThreadGoalTurnStatus;
  287. });
  288. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  289. const outcome = await orchestrator.run({
  290. sessionId: SESSION_ID,
  291. initialPromptText: "x",
  292. initialTurnId: "turn_0",
  293. generateTurnId: nextTurn,
  294. runOneTurn,
  295. signal: abort.signal,
  296. });
  297. expect(outcome.outcome).toBe("aborted");
  298. expect(runOneTurn).toHaveBeenCalledTimes(1);
  299. const after = await store.getBySession(SESSION_ID);
  300. // codex parity: an abort accounts progress but never blocks — the goal
  301. // stays active for the next kick / objective-edit restart.
  302. expect(after?.status).toBe("active");
  303. expect(after?.goalId).toBe(goal.goalId);
  304. });
  305. it("does NOT block the goal when a turn returns aborted (user cancel or objective-edit restart)", async () => {
  306. await store.create({ sessionId: SESSION_ID, objective: "x" });
  307. const runOneTurn = vi.fn(async () => "aborted" as ThreadGoalTurnStatus);
  308. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  309. const outcome = await orchestrator.run({
  310. sessionId: SESSION_ID,
  311. initialPromptText: "x",
  312. initialTurnId: "turn_0",
  313. generateTurnId: nextTurn,
  314. runOneTurn,
  315. });
  316. expect(outcome.outcome).toBe("aborted");
  317. // Stays active — this is the regression fix: editing an objective aborts
  318. // the turn to restart, and that must NOT leave the goal stuck on blocked.
  319. expect((await store.getBySession(SESSION_ID))?.status).toBe("active");
  320. });
  321. it("does not loop when goal status is already terminal at turn #1", async () => {
  322. const goal = await store.create({ sessionId: SESSION_ID, objective: "x" });
  323. await store.patch(goal.goalId, { status: "complete" });
  324. const runOneTurn = vi.fn(async () => "finished" as ThreadGoalTurnStatus);
  325. const orchestrator = createThreadGoalContinuationOrchestrator(store);
  326. const outcome = await orchestrator.run({
  327. sessionId: SESSION_ID,
  328. initialPromptText: "x",
  329. initialTurnId: "turn_0",
  330. generateTurnId: nextTurn,
  331. runOneTurn,
  332. });
  333. expect(outcome.outcome).toBe("goal-finalized");
  334. expect(runOneTurn).toHaveBeenCalledTimes(1);
  335. });
  336. });