thread-goal-kickoff-host.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import { digestThreadGoalObjective, type ThreadGoalState } from "@mavis/goal";
  2. import type { RuntimeConversation } from "@mavis/conversation-contract";
  3. import { describe, expect, it, vi } from "vitest";
  4. import type { LocalSessionRecord } from "../../src/sessions/controller.js";
  5. import type { LocalThreadGoalIntegration } from "../../src/thread-goal/host-integration.js";
  6. import { LocalThreadGoalKickoffQueue } from "../../src/thread-goal/kickoff-host.js";
  7. import {
  8. buildThreadGoalKickoffMessage,
  9. threadGoalBudgetLimitClientRequestId,
  10. threadGoalRecoveryClientRequestId,
  11. } from "../../src/thread-goal/kickoff.js";
  12. const session = {
  13. sessionId: "session-a",
  14. agentName: "mavis",
  15. } as LocalSessionRecord;
  16. const goal = {
  17. goalId: "tg_1",
  18. sessionId: session.sessionId,
  19. objective: "Review the spec",
  20. status: "active",
  21. createdAt: 1_000,
  22. updatedAt: 1_000,
  23. tokensUsed: 0,
  24. timeUsedSeconds: 0,
  25. tokenBudget: null,
  26. kickoffAttachments: [
  27. {
  28. type: "file",
  29. filePath: "/tmp/spec.md",
  30. fileName: "spec.md",
  31. mimeType: "text/markdown",
  32. },
  33. ],
  34. kickoffState: "pending",
  35. } as ThreadGoalState;
  36. function makeQueueHost(
  37. options: {
  38. recoverInitialContinuation?: (goal: ThreadGoalState) => Promise<void>;
  39. recoverableGoals?: ThreadGoalState[];
  40. listRecoverableKickoffs?: () => Promise<ThreadGoalState[]>;
  41. recoverableContinuations?: ThreadGoalState[];
  42. recoverableBudgetLimitSummaries?: ThreadGoalState[];
  43. shouldRecoverActiveContinuation?: (
  44. goal: ThreadGoalState,
  45. ) => Promise<boolean>;
  46. clearStaleVerificationWaits?: () => Promise<number>;
  47. renderRecoveryContinuationPrompt?: (
  48. goal: ThreadGoalState,
  49. ) => Promise<string>;
  50. renderRecoveryContinuationPromptRead?: (goal: ThreadGoalState) => Promise<{
  51. readonly content: string;
  52. readonly promptRead?: never;
  53. }>;
  54. conversation?: Pick<RuntimeConversation, "query" | "ingress">;
  55. } = {},
  56. ) {
  57. const recoverInitialContinuation = vi.fn(
  58. options.recoverInitialContinuation ?? (async () => undefined),
  59. );
  60. const clearStaleVerificationWaits = vi.fn(
  61. options.clearStaleVerificationWaits ?? (async () => 0),
  62. );
  63. const reportFailure = vi.fn();
  64. const reportRecoveryFailure = vi.fn();
  65. const rebindInternalPromptRead = vi.fn();
  66. const discardInternalPromptRead = vi.fn();
  67. const host = new LocalThreadGoalKickoffQueue({
  68. ...(options.conversation ? { conversation: options.conversation } : {}),
  69. getIntegration: () =>
  70. ({
  71. store: {
  72. listRecoverableKickoffs:
  73. options.listRecoverableKickoffs ??
  74. (async () => options.recoverableGoals ?? []),
  75. listRecoverableActiveGoals: async () =>
  76. options.recoverableContinuations ?? [],
  77. listRecoverableBudgetLimitSummaries: async () =>
  78. options.recoverableBudgetLimitSummaries ?? [],
  79. },
  80. recoverInitialContinuation,
  81. clearStaleVerificationWaits,
  82. shouldRecoverActiveContinuation:
  83. options.shouldRecoverActiveContinuation ?? (async () => true),
  84. preparePrompt: async (
  85. _recoverableGoal: ThreadGoalState,
  86. kind: string,
  87. ) => ({
  88. content:
  89. kind === "budget-limit"
  90. ? "The active thread goal has reached its token budget."
  91. : kind === "recovery"
  92. ? "Before taking any other action, call get_goal and recover durable Goal state."
  93. : "Continue working toward the active thread goal and follow the goal contract from the kickoff context.",
  94. }),
  95. prepareRecoveryPrompt: async (recoverableGoal: ThreadGoalState) => ({
  96. content:
  97. recoverableGoal.turnsUsed > 0 && recoverableGoal.turnsUsed % 5 === 0
  98. ? "Call get_goal once for the recovery and scheduled five-Turn checkpoint."
  99. : "Before taking any other action, call get_goal and recover durable Goal state.",
  100. kind:
  101. recoverableGoal.turnsUsed > 0 && recoverableGoal.turnsUsed % 5 === 0
  102. ? "recovery-terminal-audit"
  103. : "recovery",
  104. }),
  105. recordPromptSubmitted: vi.fn(),
  106. renderRecoveryContinuationPrompt:
  107. options.renderRecoveryContinuationPrompt ??
  108. (async (recoverableGoal) => `Continue: ${recoverableGoal.objective}`),
  109. renderRecoveryContinuationPromptRead:
  110. options.renderRecoveryContinuationPromptRead ??
  111. (async (recoverableGoal) => ({
  112. content: `Continue: ${recoverableGoal.objective}`,
  113. })),
  114. reserveInternalPromptRead: vi.fn(() => undefined),
  115. rebindInternalPromptRead,
  116. discardInternalPromptRead,
  117. }) as unknown as LocalThreadGoalIntegration,
  118. reportFailure,
  119. reportRecoveryFailure,
  120. });
  121. return {
  122. host,
  123. recoverInitialContinuation,
  124. clearStaleVerificationWaits,
  125. reportFailure,
  126. reportRecoveryFailure,
  127. rebindInternalPromptRead,
  128. discardInternalPromptRead,
  129. };
  130. }
  131. describe("LocalThreadGoalKickoffQueue", () => {
  132. it("derives a restart-stable budget summary identity from Goal id and epoch", () => {
  133. expect(
  134. threadGoalBudgetLimitClientRequestId({
  135. goalId: "tg_1",
  136. updatedAt: 1_700_000_000_123,
  137. }),
  138. ).toBe("thread-goal-followup:budget-limit:tg_1:1700000000123");
  139. });
  140. it("recovers Goal-owned pending kickoffs and reports scan failures", async () => {
  141. const recovery = makeQueueHost({ recoverableGoals: [goal] });
  142. await recovery.host.recover();
  143. expect(recovery.recoverInitialContinuation).toHaveBeenCalledWith(goal);
  144. expect(recovery.reportRecoveryFailure).not.toHaveBeenCalled();
  145. const failed = makeQueueHost({
  146. listRecoverableKickoffs: async () => {
  147. throw new Error("goal scan failed");
  148. },
  149. });
  150. await failed.host.recover();
  151. expect(failed.reportRecoveryFailure).toHaveBeenCalledWith(
  152. "goal scan failed",
  153. );
  154. });
  155. /**
  156. * A verification wait cannot survive the process that issued it, so startup
  157. * must retire it. The cleanup runs ahead of every recovery scan on purpose:
  158. * continuation recovery skips Goals for unrelated reasons (runtime disabled,
  159. * a session already started, an existing queue entry), and those are exactly
  160. * the Goals that would otherwise be left reading "Verifying" forever.
  161. */
  162. it("clears stale verification waits before any gated recovery scan", async () => {
  163. const order: string[] = [];
  164. const recovery = makeQueueHost({
  165. recoverableGoals: [goal],
  166. clearStaleVerificationWaits: async () => {
  167. order.push("cleanup");
  168. return 1;
  169. },
  170. recoverInitialContinuation: async () => {
  171. order.push("kickoff-recovery");
  172. },
  173. });
  174. await recovery.host.recover();
  175. expect(recovery.clearStaleVerificationWaits).toHaveBeenCalledOnce();
  176. expect(order).toEqual(["cleanup", "kickoff-recovery"]);
  177. });
  178. it("still clears stale verification waits when recovery gates skip every Goal", async () => {
  179. const recovery = makeQueueHost({
  180. recoverableGoals: [],
  181. recoverableContinuations: [goal],
  182. // The gate that made this reachable in the field: recovery declines, so
  183. // nothing downstream would ever touch the wait.
  184. shouldRecoverActiveContinuation: async () => false,
  185. conversation: {
  186. query: {
  187. getSession: async () => session,
  188. listSessions: async () => [session],
  189. },
  190. ingress: {
  191. findQueuedByClientRequestId: async () => undefined,
  192. submit: vi.fn(),
  193. dispatchQueue: vi.fn(),
  194. listQueued: async () => [],
  195. },
  196. } as unknown as Pick<RuntimeConversation, "query" | "ingress">,
  197. });
  198. await recovery.host.recover();
  199. expect(recovery.clearStaleVerificationWaits).toHaveBeenCalledOnce();
  200. expect(recovery.reportRecoveryFailure).not.toHaveBeenCalled();
  201. });
  202. it("reports a cleanup failure without stopping the recovery scans behind it", async () => {
  203. const recovery = makeQueueHost({
  204. recoverableGoals: [goal],
  205. clearStaleVerificationWaits: async () => {
  206. throw new Error("cleanup unavailable");
  207. },
  208. });
  209. await recovery.host.recover();
  210. expect(recovery.reportRecoveryFailure).toHaveBeenCalledWith(
  211. "thread_goal_stale_verification_wait_cleanup_failed:cleanup unavailable",
  212. );
  213. expect(recovery.recoverInitialContinuation).toHaveBeenCalledWith(goal);
  214. });
  215. it("materializes and recovers kickoffs only through the injected queue", async () => {
  216. const submit = vi.fn(async () => acceptedQueueTurn());
  217. const dispatchQueue = vi.fn(async () => undefined);
  218. const findQueuedByClientRequestId = vi.fn(async () => undefined);
  219. const fixture = makeQueueHost({
  220. recoverableGoals: [goal],
  221. conversation: {
  222. query: {
  223. getSession: async () => session,
  224. listSessions: async () => [session],
  225. },
  226. ingress: {
  227. findQueuedByClientRequestId,
  228. submit,
  229. dispatchQueue,
  230. },
  231. } as Pick<RuntimeConversation, "query" | "ingress">,
  232. });
  233. await fixture.host.integrationDeps().enqueueInitialContinuationTurn(
  234. goal,
  235. buildThreadGoalKickoffMessage(
  236. goal,
  237. "hidden continuation",
  238. goal.kickoffAttachments.map((attachment) => ({ ...attachment })),
  239. ),
  240. `thread-goal-kickoff:${goal.goalId}`,
  241. );
  242. expect(submit).toHaveBeenCalledWith(
  243. expect.objectContaining({
  244. sessionId: session.sessionId,
  245. source: "thread-goal",
  246. allowQueue: true,
  247. message: expect.objectContaining({
  248. hideUserMessage: true,
  249. displayContent: goal.objective,
  250. origin: {
  251. type: "thread-goal-kickoff",
  252. goalId: goal.goalId,
  253. goalUpdatedAt: goal.updatedAt,
  254. objectiveDigest: digestThreadGoalObjective(goal.objective),
  255. displayContent: goal.objective,
  256. },
  257. attachments: [expect.objectContaining({ fileName: "spec.md" })],
  258. }),
  259. clientRequestId: `thread-goal-kickoff:${goal.goalId}`,
  260. }),
  261. );
  262. expect(dispatchQueue).not.toHaveBeenCalled();
  263. await fixture.host.recover();
  264. expect(fixture.recoverInitialContinuation).toHaveBeenCalledWith(goal);
  265. expect(dispatchQueue).not.toHaveBeenCalled();
  266. fixture.host.integrationDeps().requestQueueDispatch(session.sessionId);
  267. expect(dispatchQueue).toHaveBeenCalledWith(session.sessionId);
  268. });
  269. it("keeps an initial continuation prompt snapshot with its admitted Turn", async () => {
  270. const submit = vi.fn(async () => acceptedQueueTurn());
  271. const fixture = makeQueueHost({
  272. conversation: {
  273. query: {
  274. getSession: async () => session,
  275. listSessions: async () => [session],
  276. },
  277. ingress: {
  278. findQueuedByClientRequestId: vi.fn(async () => undefined),
  279. submit,
  280. dispatchQueue: vi.fn(async () => undefined),
  281. },
  282. } as Pick<RuntimeConversation, "query" | "ingress">,
  283. });
  284. const internalPromptRead = {
  285. requestedTurnId: "turn_goal_requested",
  286. promptRead: {} as never,
  287. };
  288. await fixture.host
  289. .integrationDeps()
  290. .enqueueInitialContinuationTurn(
  291. goal,
  292. buildThreadGoalKickoffMessage(goal, "hidden continuation", []),
  293. `thread-goal-kickoff:${goal.goalId}`,
  294. internalPromptRead,
  295. );
  296. expect(submit).toHaveBeenCalledWith(
  297. expect.objectContaining({
  298. requestedTurnId: internalPromptRead.requestedTurnId,
  299. }),
  300. );
  301. expect(fixture.rebindInternalPromptRead).toHaveBeenCalledWith(
  302. internalPromptRead,
  303. "turn-v2",
  304. );
  305. });
  306. it("recovers a consumed active Goal when no Turn or Goal continuation survived restart", async () => {
  307. const consumed = {
  308. ...goal,
  309. kickoffState: "consumed" as const,
  310. kickoffAttachments: [],
  311. };
  312. const submit = vi.fn(async () => acceptedQueueTurn());
  313. const listQueued = vi.fn(async () => []);
  314. const fixture = makeQueueHost({
  315. recoverableContinuations: [consumed],
  316. conversation: {
  317. query: {
  318. getSession: async () => ({ ...session, status: "idle" }),
  319. listSessions: async () => [session],
  320. },
  321. ingress: {
  322. findQueuedByClientRequestId: vi.fn(async () => undefined),
  323. listQueued,
  324. submit,
  325. dispatchQueue: vi.fn(async () => undefined),
  326. },
  327. } as Pick<RuntimeConversation, "query" | "ingress">,
  328. });
  329. await fixture.host.recover();
  330. expect(listQueued).toHaveBeenCalledWith(consumed.sessionId);
  331. expect(submit).toHaveBeenCalledWith({
  332. sessionId: consumed.sessionId,
  333. source: "thread-goal",
  334. allowQueue: true,
  335. message: expect.objectContaining({
  336. hideUserMessage: true,
  337. content: expect.stringContaining("call get_goal"),
  338. origin: expect.objectContaining({
  339. type: "thread-goal-continuation",
  340. goalId: consumed.goalId,
  341. kind: "active",
  342. }),
  343. }),
  344. clientRequestId: threadGoalRecoveryClientRequestId(consumed),
  345. });
  346. const recoveredContent = submit.mock.calls[0]?.[0].message.content;
  347. expect(recoveredContent).toContain("call get_goal");
  348. expect(recoveredContent).not.toContain(consumed.objective);
  349. expect(recoveredContent).not.toContain("<objective>");
  350. });
  351. it("replays a crashed budget-limit transition once with its stable identity", async () => {
  352. const limited = {
  353. ...goal,
  354. status: "budget_limited" as const,
  355. kickoffState: "consumed" as const,
  356. kickoffAttachments: [],
  357. tokensUsed: 100,
  358. tokenBudget: 100,
  359. updatedAt: 2_000,
  360. };
  361. let queued: ReturnType<typeof injectedQueueItem> | undefined;
  362. const submit = vi.fn(async (input: { clientRequestId?: string }) => {
  363. queued = {
  364. ...injectedQueueItem("thread-goal"),
  365. clientRequestId: input.clientRequestId ?? "missing-client-request-id",
  366. };
  367. return acceptedQueueTurn();
  368. });
  369. const fixture = makeQueueHost({
  370. recoverableBudgetLimitSummaries: [limited],
  371. conversation: {
  372. query: {
  373. getSession: async () => ({ ...session, status: "idle" }),
  374. listSessions: async () => [session],
  375. },
  376. ingress: {
  377. findQueuedByClientRequestId: vi.fn(async () => queued),
  378. submit,
  379. dispatchQueue: vi.fn(async () => undefined),
  380. },
  381. } as Pick<RuntimeConversation, "query" | "ingress">,
  382. });
  383. await fixture.host.recover();
  384. await fixture.host.recover();
  385. expect(submit).toHaveBeenCalledTimes(1);
  386. expect(submit).toHaveBeenCalledWith(
  387. expect.objectContaining({
  388. sessionId: limited.sessionId,
  389. source: "thread-goal",
  390. allowQueue: true,
  391. clientRequestId: threadGoalBudgetLimitClientRequestId(limited),
  392. message: expect.objectContaining({
  393. hideUserMessage: true,
  394. content: expect.stringContaining("reached its token budget"),
  395. origin: expect.objectContaining({
  396. type: "thread-goal-continuation",
  397. goalId: limited.goalId,
  398. goalUpdatedAt: limited.updatedAt,
  399. kind: "budget-limit",
  400. }),
  401. }),
  402. }),
  403. );
  404. });
  405. it("does not duplicate an active Goal continuation that already survived restart", async () => {
  406. const consumed = {
  407. ...goal,
  408. kickoffState: "consumed" as const,
  409. kickoffAttachments: [],
  410. };
  411. const submit = vi.fn();
  412. const fixture = makeQueueHost({
  413. recoverableContinuations: [consumed],
  414. conversation: {
  415. query: {
  416. getSession: async () => ({ ...session, status: "idle" }),
  417. listSessions: async () => [session],
  418. },
  419. ingress: {
  420. findQueuedByClientRequestId: vi.fn(async () => undefined),
  421. listQueued: vi.fn(async () => [
  422. {
  423. ...injectedQueueItem("thread-goal"),
  424. message: {
  425. content: "hidden continuation",
  426. attachments: [],
  427. origin: {
  428. type: "thread-goal-continuation",
  429. goalId: consumed.goalId,
  430. goalUpdatedAt: consumed.updatedAt,
  431. objectiveDigest: digestThreadGoalObjective(
  432. consumed.objective,
  433. ),
  434. kind: "active",
  435. },
  436. },
  437. },
  438. ]),
  439. submit,
  440. dispatchQueue: vi.fn(async () => undefined),
  441. },
  442. } as Pick<RuntimeConversation, "query" | "ingress">,
  443. });
  444. await fixture.host.recover();
  445. expect(submit).not.toHaveBeenCalled();
  446. });
  447. it("reports an injected queue wake failure without leaking the rejection", async () => {
  448. const dispatchQueue = vi.fn(async () => {
  449. throw new Error("dispatch failed");
  450. });
  451. const fixture = makeQueueHost({
  452. conversation: {
  453. query: {
  454. getSession: async () => session,
  455. listSessions: async () => [session],
  456. },
  457. ingress: {
  458. findQueuedByClientRequestId: vi.fn(async () => undefined),
  459. submit: vi.fn(async () => acceptedQueueTurn()),
  460. dispatchQueue,
  461. },
  462. } as Pick<RuntimeConversation, "query" | "ingress">,
  463. });
  464. fixture.host.integrationDeps().requestQueueDispatch(session.sessionId);
  465. await vi.waitFor(() =>
  466. expect(fixture.reportFailure).toHaveBeenCalledWith(
  467. session.sessionId,
  468. "thread_goal_queue_dispatch_failed:dispatch failed",
  469. ),
  470. );
  471. });
  472. it("treats an exact claimed kickoff as already materialized", async () => {
  473. const submit = vi.fn();
  474. const claimed = {
  475. ...injectedQueueItem("thread-goal"),
  476. status: "claimed" as const,
  477. claimId: "claim-1",
  478. };
  479. const findQueuedByClientRequestId = vi.fn(async () => claimed);
  480. const fixture = makeQueueHost({
  481. conversation: {
  482. query: {
  483. getSession: async () => session,
  484. listSessions: async () => [session],
  485. },
  486. ingress: {
  487. findQueuedByClientRequestId,
  488. submit,
  489. dispatchQueue: vi.fn(),
  490. },
  491. } as Pick<RuntimeConversation, "query" | "ingress">,
  492. });
  493. await fixture.host
  494. .integrationDeps()
  495. .enqueueInitialContinuationTurn(
  496. goal,
  497. buildThreadGoalKickoffMessage(
  498. goal,
  499. "hidden continuation",
  500. goal.kickoffAttachments,
  501. ),
  502. `thread-goal-kickoff:${goal.goalId}`,
  503. );
  504. expect(findQueuedByClientRequestId).toHaveBeenCalledWith(
  505. session.sessionId,
  506. `thread-goal-kickoff:${goal.goalId}`,
  507. );
  508. expect(submit).not.toHaveBeenCalled();
  509. });
  510. });
  511. function injectedQueueItem(source: "api" | "thread-goal") {
  512. return {
  513. itemId: "queue-v2",
  514. sessionId: session.sessionId,
  515. agentName: session.agentName,
  516. source,
  517. status: "queued" as const,
  518. message: { content: goal.objective, attachments: [] },
  519. createdAt: 1_000,
  520. clientRequestId: `thread-goal-kickoff:${goal.goalId}`,
  521. };
  522. }
  523. function acceptedQueueTurn() {
  524. return {
  525. turnId: "turn-v2",
  526. mode: "queued" as const,
  527. queue: { itemId: "queue-v2", position: 1, ahead: 0 },
  528. completion: Promise.resolve({
  529. turnId: "turn-v2",
  530. status: "completed" as const,
  531. messages: [],
  532. }),
  533. };
  534. }