local-thread-goal-wiring.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /**
  2. * Unit tests for the Thread Goal wiring helpers — SSE bus projection +
  3. * the codex `continue_if_idle` kick.
  4. *
  5. * Pins:
  6. * (a) external set-active on an idle session starts a hidden
  7. * continuation turn with the rendered append-only prompt,
  8. * (b) a busy session is never double-driven (the in-stream
  9. * orchestrator owns continuation mid-turn),
  10. * (c) non-active results and deletes never kick,
  11. * (d) kick failures are swallowed (busy-lock races are benign),
  12. * (e) handleThreadGoalChanged projects the bus event for every
  13. * mutation type and only kicks on active.
  14. */
  15. import { describe, expect, it, vi } from "vitest";
  16. import type { ThreadGoalState } from "@mavis/goal";
  17. import {
  18. buildThreadGoalRuntimeTools,
  19. handleThreadGoalChanged,
  20. maybeKickThreadGoalContinuation,
  21. } from "../../src/thread-goal/wiring.js";
  22. function goal(overrides: Partial<ThreadGoalState> = {}): ThreadGoalState {
  23. return {
  24. goalId: "tg_wiring_1",
  25. sessionId: "sess_wiring",
  26. objective: "Ship the wiring tests",
  27. status: "active",
  28. createdAt: 1_700_000_000_000,
  29. updatedAt: 1_700_000_000_000,
  30. tokensUsed: 0,
  31. turnsUsed: 0,
  32. timeUsedSeconds: 0,
  33. tokenBudget: null,
  34. replyFingerprint: null,
  35. noProgressStreak: 0,
  36. noToolStreak: 0,
  37. lastVerification: undefined,
  38. statusReason: null,
  39. kickoffAttachments: [],
  40. kickoffState: "consumed",
  41. executionWait: null,
  42. ...overrides,
  43. };
  44. }
  45. describe("maybeKickThreadGoalContinuation", () => {
  46. it("starts a continuation turn when the session is idle and the goal is active", async () => {
  47. const startContinuationTurn = vi.fn(async () => undefined);
  48. await maybeKickThreadGoalContinuation(
  49. { type: "updated", goal: goal() },
  50. { isSessionBusy: () => false, startContinuationTurn },
  51. );
  52. expect(startContinuationTurn).toHaveBeenCalledTimes(1);
  53. const [sessionId, content] = startContinuationTurn.mock.calls[0] as [
  54. string,
  55. string,
  56. ];
  57. expect(sessionId).toBe("sess_wiring");
  58. expect(content).toContain("Continue working toward the active thread goal");
  59. expect(content).not.toContain("Ship the wiring tests");
  60. expect(content).not.toContain("<objective>");
  61. });
  62. it("kicks on created events too (POST /goal while idle = start working)", async () => {
  63. const startContinuationTurn = vi.fn(async () => undefined);
  64. await maybeKickThreadGoalContinuation(
  65. { type: "created", goal: goal() },
  66. { isSessionBusy: () => false, startContinuationTurn },
  67. );
  68. expect(startContinuationTurn).toHaveBeenCalledTimes(1);
  69. const [, content] = startContinuationTurn.mock.calls[0] as [string, string];
  70. expect(content).toContain(
  71. "<objective>\nShip the wiring tests\n</objective>",
  72. );
  73. expect(content).toContain("Completion audit:");
  74. });
  75. it("does not kick while the session has a running turn", async () => {
  76. const startContinuationTurn = vi.fn(async () => undefined);
  77. await maybeKickThreadGoalContinuation(
  78. { type: "updated", goal: goal() },
  79. { isSessionBusy: () => true, startContinuationTurn },
  80. );
  81. expect(startContinuationTurn).not.toHaveBeenCalled();
  82. });
  83. it.each([
  84. "paused",
  85. "blocked",
  86. "complete",
  87. "budget_limited",
  88. "usage_limited",
  89. ] as const)(
  90. "does not kick when the resulting status is %s",
  91. async (status) => {
  92. const startContinuationTurn = vi.fn(async () => undefined);
  93. await maybeKickThreadGoalContinuation(
  94. { type: "updated", goal: goal({ status }) },
  95. { isSessionBusy: () => false, startContinuationTurn },
  96. );
  97. expect(startContinuationTurn).not.toHaveBeenCalled();
  98. },
  99. );
  100. it("does not kick on delete events", async () => {
  101. const startContinuationTurn = vi.fn(async () => undefined);
  102. await maybeKickThreadGoalContinuation(
  103. { type: "deleted", goalId: "tg_wiring_1", sessionId: "sess_wiring" },
  104. { isSessionBusy: () => false, startContinuationTurn },
  105. );
  106. expect(startContinuationTurn).not.toHaveBeenCalled();
  107. });
  108. it("swallows turn-start failures (busy-lock race is benign)", async () => {
  109. const startContinuationTurn = vi.fn(async () => {
  110. throw new Error("local_session_busy");
  111. });
  112. await expect(
  113. maybeKickThreadGoalContinuation(
  114. { type: "updated", goal: goal() },
  115. { isSessionBusy: () => false, startContinuationTurn },
  116. ),
  117. ).resolves.toBeUndefined();
  118. });
  119. });
  120. describe("handleThreadGoalChanged", () => {
  121. it("emits thread_goal.updated and kicks for an active mutation", async () => {
  122. const emitBusEvent = vi.fn();
  123. const startContinuationTurn = vi.fn(async () => undefined);
  124. handleThreadGoalChanged(
  125. { type: "updated", goal: goal() },
  126. {
  127. publishGlobalEvent: emitBusEvent,
  128. isSessionBusy: () => false,
  129. startContinuationTurn,
  130. },
  131. );
  132. expect(emitBusEvent).toHaveBeenCalledWith(
  133. expect.objectContaining({
  134. type: "thread_goal.updated",
  135. payload: expect.objectContaining({
  136. goal: expect.objectContaining({
  137. goalId: "tg_wiring_1",
  138. status: "active",
  139. }),
  140. }),
  141. }),
  142. );
  143. await vi.waitFor(() =>
  144. expect(startContinuationTurn).toHaveBeenCalledTimes(1),
  145. );
  146. });
  147. it("emits thread_goal.cleared and never kicks for deletes", () => {
  148. const emitBusEvent = vi.fn();
  149. const startContinuationTurn = vi.fn(async () => undefined);
  150. handleThreadGoalChanged(
  151. { type: "deleted", goalId: "tg_wiring_1", sessionId: "sess_wiring" },
  152. {
  153. publishGlobalEvent: emitBusEvent,
  154. isSessionBusy: () => false,
  155. startContinuationTurn,
  156. },
  157. );
  158. expect(emitBusEvent).toHaveBeenCalledWith({
  159. type: "thread_goal.cleared",
  160. payload: { goalId: "tg_wiring_1", sessionId: "sess_wiring" },
  161. });
  162. expect(startContinuationTurn).not.toHaveBeenCalled();
  163. });
  164. it("emits the bus event but does not kick for a paused mutation", () => {
  165. const emitBusEvent = vi.fn();
  166. const startContinuationTurn = vi.fn(async () => undefined);
  167. handleThreadGoalChanged(
  168. { type: "updated", goal: goal({ status: "paused" }) },
  169. {
  170. publishGlobalEvent: emitBusEvent,
  171. isSessionBusy: () => false,
  172. startContinuationTurn,
  173. },
  174. );
  175. expect(emitBusEvent).toHaveBeenCalledTimes(1);
  176. expect(startContinuationTurn).not.toHaveBeenCalled();
  177. });
  178. it("projects usage, reason, and verifier summary onto thread_goal.updated", () => {
  179. // MR-1 accounting parity: SSE payload must carry tokensUsed +
  180. // timeUsedSeconds + (MR-2) tokenBudget so the banner can render
  181. // `(12.5K / 50K)` or `(12.5K · 2m)` without a manual REST refresh.
  182. const emitBusEvent = vi.fn();
  183. const startContinuationTurn = vi.fn(async () => undefined);
  184. handleThreadGoalChanged(
  185. {
  186. type: "updated",
  187. goal: goal({
  188. status: "paused",
  189. tokensUsed: 12_500,
  190. turnsUsed: 4,
  191. timeUsedSeconds: 137,
  192. tokenBudget: 50_000,
  193. statusReason: "paused(no_progress)",
  194. lastVerification: {
  195. v: 1,
  196. backend: "evaluator",
  197. verdict: "not_met",
  198. reason: "Missing tests",
  199. missing: ["focused tests"],
  200. notMetStreak: 2,
  201. turnId: "turn_1",
  202. objectiveDigest: "digest",
  203. at: 1_700_000_000_000,
  204. },
  205. lastWorkerProposal: {
  206. v: 1,
  207. source: "worker",
  208. type: "blocked",
  209. turnId: "turn_1",
  210. summary: "private blocker detail",
  211. at: 1_700_000_000_001,
  212. },
  213. }),
  214. },
  215. {
  216. publishGlobalEvent: emitBusEvent,
  217. isSessionBusy: () => false,
  218. startContinuationTurn,
  219. },
  220. );
  221. expect(emitBusEvent).toHaveBeenCalledWith(
  222. expect.objectContaining({
  223. type: "thread_goal.updated",
  224. payload: expect.objectContaining({
  225. goal: expect.objectContaining({
  226. tokensUsed: 12_500,
  227. turnsUsed: 4,
  228. timeUsedSeconds: 137,
  229. tokenBudget: 50_000,
  230. statusReason: "paused(no_progress)",
  231. lastVerification: {
  232. backend: "evaluator",
  233. verdict: "not_met",
  234. reason: "Missing tests",
  235. missing: ["focused tests"],
  236. notMetStreak: 2,
  237. at: 1_700_000_000_000,
  238. },
  239. }),
  240. }),
  241. }),
  242. );
  243. expect(JSON.stringify(emitBusEvent.mock.calls[0]?.[0])).not.toContain(
  244. "private blocker detail",
  245. );
  246. });
  247. });
  248. describe("buildThreadGoalRuntimeTools", () => {
  249. const signalCollector = { collect: () => "accepted" as const };
  250. const fakeStore = {
  251. getBySession: async () => undefined,
  252. getById: async () => undefined,
  253. create: async () => goal(),
  254. patch: async () => goal(),
  255. updateBreaker: async () => ({
  256. action: "stale" as const,
  257. staleReason: "missing_goal" as const,
  258. }),
  259. delete: async () => undefined,
  260. };
  261. it("does not expose create_goal and returns only lifecycle tools when enabled", () => {
  262. const tools = buildThreadGoalRuntimeTools(
  263. fakeStore,
  264. false,
  265. signalCollector,
  266. );
  267. expect(tools.map((tool) => tool.def.name).sort()).toEqual([
  268. "get_goal",
  269. "update_goal",
  270. ]);
  271. });
  272. it("returns no tools when disabled", () => {
  273. expect(
  274. buildThreadGoalRuntimeTools(fakeStore, true, signalCollector),
  275. ).toEqual([]);
  276. });
  277. });