host-integration-four-fix-combination.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { tmpdir } from "node:os";
  5. import { digestThreadGoalObjective, type ThreadGoalState } from "@mavis/goal";
  6. import { closeLocalRuntimeDb } from "../../../src/persistence/db.js";
  7. import { LocalThreadGoalIntegration } from "../../../src/thread-goal/host-integration.js";
  8. import { LocalActiveTurnTimingRegistry } from "../../../src/turns/active-turn-timing.js";
  9. /**
  10. * Cross-fix combination coverage for the consolidated Goal MR.
  11. *
  12. * Each of the four fixes is already covered on its own source branch. What no
  13. * single branch could cover is the behaviour that only exists once they sit in
  14. * the same tree, because each one changed a touchpoint the others also use:
  15. *
  16. * - the explicit-user-Turn breaker reset (M1) now also has to clear the
  17. * no-tool counter (M3), and its re-arm has to survive an epoch that the
  18. * breaker itself may have moved,
  19. * - the breaker writes and advances the epoch at stage 8 (M3), which is
  20. * exactly the epoch the re-arm generation guard (M1) compares against,
  21. * - a verification wait (M2) is projected without advancing the epoch, so it
  22. * must leave the breaker counters and the re-arm alone,
  23. * - a dependency wait clears the streak before it enqueues the deferable
  24. * continuation (M3), which is the ordering the Queue-local exclusion (M6)
  25. * relies on to keep the deferred item while user work overtakes it.
  26. *
  27. * These drive the real SQLite store, so the epoch bumps, the breaker CAS and
  28. * the queue classification are the production ones rather than mocks.
  29. */
  30. const NOW = 1_700_000_000_000;
  31. const SESSION = "sess_four_fix_combination";
  32. const OBJECTIVE = "Consolidate the Goal runtime fixes";
  33. let dataDir: string;
  34. let integration: LocalThreadGoalIntegration;
  35. let turnTimings: LocalActiveTurnTimingRegistry;
  36. let enqueuePostTurnContinuation: ReturnType<typeof vi.fn>;
  37. let enqueueInitialContinuationTurn: ReturnType<typeof vi.fn>;
  38. let cancelInitialContinuation: ReturnType<typeof vi.fn>;
  39. let hasPendingInitialContinuation: ReturnType<typeof vi.fn>;
  40. let reportFailure: ReturnType<typeof vi.fn>;
  41. let kickoffQueued: boolean;
  42. let permissionPending: boolean;
  43. beforeEach(async () => {
  44. dataDir = await mkdtemp(join(tmpdir(), "goal-four-fix-combination-"));
  45. turnTimings = new LocalActiveTurnTimingRegistry(() => NOW);
  46. kickoffQueued = false;
  47. permissionPending = false;
  48. enqueuePostTurnContinuation = vi.fn(async () => undefined);
  49. enqueueInitialContinuationTurn = vi.fn(async () => {
  50. kickoffQueued = true;
  51. });
  52. cancelInitialContinuation = vi.fn(async () => {
  53. kickoffQueued = false;
  54. });
  55. hasPendingInitialContinuation = vi.fn(async () => kickoffQueued);
  56. reportFailure = vi.fn();
  57. integration = new LocalThreadGoalIntegration({
  58. dataDir,
  59. nowMs: () => NOW,
  60. turnTimingReader: turnTimings,
  61. publishGlobalEvent: () => undefined,
  62. isSessionBusy: (sessionId) =>
  63. turnTimings.getBySession(sessionId) !== undefined,
  64. hasPendingQuestionnaire: async () => false,
  65. retireGoalQuestionnaire: async () => false,
  66. hasPendingPermission: async () => permissionPending,
  67. hasAutomationOwnerConflict: async () => false,
  68. hasRequiredBackgroundWork: async () => false,
  69. startContinuationTurn: vi.fn(async () => undefined),
  70. enqueuePostTurnContinuation,
  71. enqueueInitialContinuationTurn,
  72. hasPendingInitialContinuation,
  73. cancelInitialContinuation,
  74. requestQueueDispatch: () => undefined,
  75. reportFailure,
  76. emitRuntimeEvent: vi.fn(),
  77. formatError: (error) =>
  78. error instanceof Error ? error.message : String(error),
  79. isEnabled: () => true,
  80. });
  81. });
  82. afterEach(async () => {
  83. closeLocalRuntimeDb(dataDir);
  84. await rm(dataDir, { recursive: true, force: true });
  85. });
  86. async function seedRunningGoal(): Promise<ThreadGoalState> {
  87. await integration.createGoal({ sessionId: SESSION, objective: OBJECTIVE });
  88. const enqueued = await integration.store.getBySession(SESSION);
  89. if (!enqueued) throw new Error("expected the seeded Goal to persist");
  90. await integration.store.transitionKickoffState(
  91. enqueued.goalId,
  92. enqueued.kickoffState,
  93. "consumed",
  94. );
  95. const goal = await integration.store.getBySession(SESSION);
  96. if (goal?.kickoffState !== "consumed") {
  97. throw new Error(
  98. `expected a kickoff-consumed Goal, got ${goal?.kickoffState}`,
  99. );
  100. }
  101. kickoffQueued = false;
  102. return goal;
  103. }
  104. function continuationOrigin(goal: ThreadGoalState): Record<string, unknown> {
  105. return {
  106. type: "thread-goal-continuation",
  107. goalId: goal.goalId,
  108. goalUpdatedAt: goal.updatedAt,
  109. objectiveDigest: digestThreadGoalObjective(goal.objective),
  110. kind: "active",
  111. };
  112. }
  113. async function admitGoalTurn(
  114. goal: ThreadGoalState,
  115. turnId: string,
  116. ): Promise<void> {
  117. turnTimings.begin(SESSION, turnId);
  118. const prepared = await integration.prepareTurnAdmission({
  119. sessionId: SESSION,
  120. turnId,
  121. provenance: {
  122. source: "thread-goal",
  123. sourceContext: { origin: continuationOrigin(goal) },
  124. },
  125. hasPendingPlan: async () => false,
  126. hasPriorityMailboxWork: async () => false,
  127. });
  128. if (prepared?.status !== "ready") {
  129. throw new Error(
  130. `expected a ready Goal admission, got ${JSON.stringify(prepared)}`,
  131. );
  132. }
  133. await prepared.commit();
  134. }
  135. /**
  136. * Admit an explicit user Turn the way TurnSystem does. `startTiming` stays off
  137. * while a Goal Turn is still in flight, so the in-flight binding is preserved
  138. * and only the committed breaker reset invalidates it.
  139. */
  140. async function admitUserTurn(
  141. turnId: string,
  142. startTiming = true,
  143. ): Promise<void> {
  144. const prepared = await integration.prepareTurnAdmission({
  145. sessionId: SESSION,
  146. turnId,
  147. provenance: { source: "api" },
  148. hasPendingPlan: async () => false,
  149. hasPriorityMailboxWork: async () => false,
  150. });
  151. if (prepared?.status !== "ready") {
  152. throw new Error(
  153. `expected a ready user admission, got ${JSON.stringify(prepared)}`,
  154. );
  155. }
  156. if (startTiming) turnTimings.begin(SESSION, turnId);
  157. await prepared.commit();
  158. }
  159. /** Settle a Goal-bound Turn that produced no tool call at all. */
  160. async function settleToolLessGoalTurn(turnId: string, replyText: string) {
  161. const settled = await integration.settleInjectedTurn({
  162. sessionId: SESSION,
  163. turnId,
  164. status: "completed",
  165. tokens: 100,
  166. retracted: false,
  167. workSignals: { toolCalls: 0 },
  168. finalAssistantText: replyText,
  169. });
  170. turnTimings.finish(SESSION, turnId);
  171. return settled;
  172. }
  173. async function currentGoal(): Promise<ThreadGoalState> {
  174. const goal = await integration.store.getBySession(SESSION);
  175. if (!goal) throw new Error("expected the Goal to still exist");
  176. return goal;
  177. }
  178. describe("Goal consolidated MR cross-fix combination", () => {
  179. it("lets an explicit user Turn clear the no-tool streak and still re-arm the follow-up", async () => {
  180. // M1 owns the re-arm, M3 owns the no-tool counter, and the explicit reset
  181. // is the single write that has to do both. On either source branch alone
  182. // only half of this assertion could even be expressed.
  183. let goal = await seedRunningGoal();
  184. await admitGoalTurn(goal, "turn_goal_1");
  185. await settleToolLessGoalTurn("turn_goal_1", "still thinking about it");
  186. goal = await currentGoal();
  187. await admitGoalTurn(goal, "turn_goal_2");
  188. await settleToolLessGoalTurn("turn_goal_2", "still thinking about it");
  189. // One more tool-less Turn would pause the Goal on both conditions at once.
  190. const primed = await currentGoal();
  191. expect(primed).toMatchObject({
  192. noToolStreak: 2,
  193. noProgressStreak: 1,
  194. status: "active",
  195. });
  196. // Each Goal Turn above queued its own stage-10 follow-up, so measure the
  197. // re-arm as the delta this user Turn is responsible for.
  198. const enqueuedBeforeUserTurn =
  199. enqueuePostTurnContinuation.mock.calls.length;
  200. // The user intervenes. This single admission resets the breaker, advances
  201. // the epoch, and therefore owes the Goal a rebuilt follow-up.
  202. await admitUserTurn("turn_user");
  203. const afterReset = await currentGoal();
  204. expect(afterReset).toMatchObject({
  205. noToolStreak: 0,
  206. noProgressStreak: 0,
  207. replyFingerprint: null,
  208. status: "active",
  209. });
  210. await integration.settleInjectedTurn({
  211. sessionId: SESSION,
  212. turnId: "turn_user",
  213. status: "completed",
  214. tokens: 10,
  215. retracted: false,
  216. });
  217. turnTimings.finish(SESSION, "turn_user");
  218. // M1's half: the Goal did not lose its runner. Exactly one rebuilt
  219. // follow-up is attributable to the user Turn's reset.
  220. expect(enqueuePostTurnContinuation.mock.calls.length).toBe(
  221. enqueuedBeforeUserTurn + 1,
  222. );
  223. // M3's half: the next tool-less Turn restarts the streak at 1 instead of
  224. // completing an interrupted run of three and pausing.
  225. const rearmed = await currentGoal();
  226. await admitGoalTurn(rearmed, "turn_goal_3");
  227. await settleToolLessGoalTurn("turn_goal_3", "still thinking about it");
  228. expect(await currentGoal()).toMatchObject({
  229. noToolStreak: 1,
  230. status: "active",
  231. });
  232. });
  233. it("still pauses on three consecutive tool-less Turns once the user stops intervening", async () => {
  234. // The reset must interrupt the run, not disable the policy: the approved
  235. // threshold stays 3 and the outcome stays `paused`, never `complete`.
  236. let goal = await seedRunningGoal();
  237. for (const turnId of ["turn_a", "turn_b"]) {
  238. await admitGoalTurn(goal, turnId);
  239. await settleToolLessGoalTurn(turnId, `distinct reply ${turnId}`);
  240. goal = await currentGoal();
  241. }
  242. expect(goal).toMatchObject({ noToolStreak: 2, status: "active" });
  243. await admitGoalTurn(goal, "turn_c");
  244. await settleToolLessGoalTurn("turn_c", "distinct reply turn_c");
  245. const paused = await currentGoal();
  246. expect(paused).toMatchObject({ noToolStreak: 3, status: "paused" });
  247. expect(paused.status).not.toBe("completed");
  248. });
  249. it("keeps the breaker epoch advance from swallowing the re-arm a later user Turn installed", async () => {
  250. // M3 made stage 8 a writer, so a settling Turn now moves the epoch itself.
  251. // M1's generation guard is what stops that older settlement from clearing a
  252. // re-arm installed after it started.
  253. const goal = await seedRunningGoal();
  254. await admitGoalTurn(goal, "turn_goal");
  255. // The user's message lands while the Goal Turn is still in flight.
  256. await admitUserTurn("turn_user", false);
  257. // The Goal Turn is now stale, so it stops before stage 10 and schedules
  258. // nothing itself; only the drain can rebuild the follow-up.
  259. const stale = await integration.settleInjectedTurn({
  260. sessionId: SESSION,
  261. turnId: "turn_goal",
  262. status: "completed",
  263. tokens: 100,
  264. retracted: false,
  265. workSignals: { toolCalls: 0 },
  266. finalAssistantText: "superseded work",
  267. });
  268. expect(stale).toMatchObject({ action: "stale" });
  269. turnTimings.finish(SESSION, "turn_goal");
  270. // Exactly one follow-up, rebuilt at the current epoch so it admits cleanly.
  271. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  272. const [submitted] = enqueuePostTurnContinuation.mock.calls[0] as [
  273. { readonly message: { readonly origin?: unknown } },
  274. ];
  275. const origin = submitted.message.origin as Record<string, unknown>;
  276. expect(origin).toMatchObject({
  277. goalUpdatedAt: (await currentGoal()).updatedAt,
  278. });
  279. await expect(
  280. integration.classifyQueuedItem({
  281. sessionId: SESSION,
  282. clientRequestId: "thread-goal-followup:turn_goal",
  283. message: { origin },
  284. }),
  285. ).resolves.toBe("ready");
  286. // The stale Turn's own settlement must not have counted toward the streak.
  287. expect(await currentGoal()).toMatchObject({
  288. noToolStreak: 0,
  289. status: "active",
  290. });
  291. });
  292. it("clears a live no-tool streak on a dependency wait before deferring the continuation", async () => {
  293. // M3 made the dependency wait a writer; M6 relies on the deferred item still
  294. // being enqueued afterwards so the Queue can retain it while user work
  295. // overtakes the blocked Goal.
  296. let goal = await seedRunningGoal();
  297. await admitGoalTurn(goal, "turn_1");
  298. await settleToolLessGoalTurn("turn_1", "no tools yet");
  299. goal = await currentGoal();
  300. expect(goal.noToolStreak).toBe(1);
  301. await admitGoalTurn(goal, "turn_2");
  302. // The dependency appears during the Turn, and that Turn really used tools.
  303. permissionPending = true;
  304. const deferred = await integration.settleInjectedTurn({
  305. sessionId: SESSION,
  306. turnId: "turn_2",
  307. status: "completed",
  308. tokens: 100,
  309. retracted: false,
  310. workSignals: { toolCalls: 2 },
  311. });
  312. turnTimings.finish(SESSION, "turn_2");
  313. // Stage 5 returned, and the real tool calls still interrupted the streak.
  314. expect(deferred).toMatchObject({ stage: 5 });
  315. const blocked = await currentGoal();
  316. expect(blocked).toMatchObject({ noToolStreak: 0, status: "active" });
  317. // The deferable continuation is still queued: that item is what M6 keeps.
  318. // turn_1 queued its own follow-up earlier, so this is the second call.
  319. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  320. });
  321. it("does not let a verification wait disturb the breaker counters", async () => {
  322. // M2's wait projection is a visibility write that must not advance the
  323. // epoch, so it can neither score nor clear M3's counters.
  324. let goal = await seedRunningGoal();
  325. await admitGoalTurn(goal, "turn_1");
  326. await settleToolLessGoalTurn("turn_1", "no tools yet");
  327. goal = await currentGoal();
  328. const beforeWait = goal.updatedAt;
  329. expect(goal.noToolStreak).toBe(1);
  330. await integration.store.setExecutionWaitAtEpoch({
  331. goalId: goal.goalId,
  332. expectedUpdatedAt: beforeWait,
  333. reason: "verification",
  334. });
  335. const waiting = await currentGoal();
  336. expect(waiting).toMatchObject({ noToolStreak: 1, updatedAt: beforeWait });
  337. expect(waiting.executionWait?.reason).toBe("verification");
  338. await integration.store.clearExecutionWaitAtEpoch({
  339. goalId: goal.goalId,
  340. expectedUpdatedAt: beforeWait,
  341. });
  342. expect(await currentGoal()).toMatchObject({
  343. noToolStreak: 1,
  344. updatedAt: beforeWait,
  345. });
  346. });
  347. });