host-integration-verifier-charge-rearm.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. digestThreadGoalObjective,
  7. type ThreadGoalState,
  8. type TranscriptWindowReader,
  9. type VerificationResult,
  10. type VerifierPort,
  11. } from "@mavis/goal";
  12. import { closeLocalRuntimeDb } from "../../../src/persistence/db.js";
  13. import { LocalThreadGoalIntegration } from "../../../src/thread-goal/host-integration.js";
  14. import { LocalActiveTurnTimingRegistry } from "../../../src/turns/active-turn-timing.js";
  15. /**
  16. * The combination !6769 left open: an explicit user message re-arms the
  17. * continuation and the rebuilt Turn is admitted, and only *then* does the
  18. * subagent verifier that was still running get charged.
  19. *
  20. * That charge is stale by construction — the user's breaker reset moved the
  21. * epoch out from under the verifier's binding — but it is not a decision: it
  22. * only records tokens that were already spent. While it also advanced the
  23. * decision epoch, it silently retired the binding of the Turn the queue had
  24. * just admitted, so that Turn's first tool call was refused with
  25. * `GOAL_TURN_NOT_CURRENT`, its own settlement stopped at the stale stage, and
  26. * the re-arm marker was already spent. The Goal was left `active` with an
  27. * empty queue and an idle session until the next process restart.
  28. *
  29. * These tests drive the real SQLite store and the real verifier dispatch so
  30. * the epoch writes, the tool gate and the settlement CAS are the production
  31. * ones, and they pin both interleavings of the charge against the admission.
  32. */
  33. const SESSION = "sess_verifier_charge_rearm";
  34. const OBJECTIVE = "Ship the release candidate";
  35. const MAIN_TURN = "turn_goal_main";
  36. const USER_TURN = "turn_user";
  37. const REARMED_TURN = "turn_goal_rearmed";
  38. const MAIN_TOKENS = 1_752;
  39. const VERIFIER_TOKENS = 1_887;
  40. const REARMED_TOKENS = 636;
  41. let dataDir: string;
  42. let now: number;
  43. let integration: LocalThreadGoalIntegration;
  44. let turnTimings: LocalActiveTurnTimingRegistry;
  45. let enqueuePostTurnContinuation: ReturnType<typeof vi.fn>;
  46. let verifierStarted: Deferred<void>;
  47. let verifierVerdict: Deferred<VerificationResult>;
  48. interface Deferred<T> {
  49. readonly promise: Promise<T>;
  50. resolve(value: T): void;
  51. }
  52. function deferred<T>(): Deferred<T> {
  53. let resolve!: (value: T) => void;
  54. const promise = new Promise<T>((next) => {
  55. resolve = next;
  56. });
  57. return { promise, resolve };
  58. }
  59. beforeEach(async () => {
  60. dataDir = await mkdtemp(join(tmpdir(), "goal-verifier-charge-rearm-"));
  61. now = 1_700_000_000_000;
  62. turnTimings = new LocalActiveTurnTimingRegistry(() => now);
  63. enqueuePostTurnContinuation = vi.fn(async () => undefined);
  64. verifierStarted = deferred<void>();
  65. verifierVerdict = deferred<VerificationResult>();
  66. const verifier: VerifierPort = {
  67. dispatch: vi.fn(async () => {
  68. verifierStarted.resolve();
  69. return verifierVerdict.promise;
  70. }),
  71. };
  72. const transcriptReader: TranscriptWindowReader = {
  73. capture: vi.fn(async () => ({
  74. messages: [{ role: "assistant", content: "Release checks finished." }],
  75. truncated: false,
  76. })),
  77. };
  78. integration = new LocalThreadGoalIntegration({
  79. dataDir,
  80. nowMs: () => now,
  81. turnTimingReader: turnTimings,
  82. publishGlobalEvent: vi.fn(),
  83. isSessionBusy: (sessionId) =>
  84. turnTimings.getBySession(sessionId) !== undefined,
  85. hasPendingQuestionnaire: async () => false,
  86. retireGoalQuestionnaire: async () => false,
  87. hasPendingPermission: async () => false,
  88. hasAutomationOwnerConflict: async () => false,
  89. hasRequiredBackgroundWork: async () => false,
  90. startContinuationTurn: async () => undefined,
  91. enqueueInitialContinuationTurn: async () => undefined,
  92. enqueuePostTurnContinuation,
  93. cancelInitialContinuation: async () => undefined,
  94. requestQueueDispatch: vi.fn(),
  95. hasPendingInitialContinuation: async () => false,
  96. reportFailure: vi.fn(),
  97. emitRuntimeEvent: vi.fn(),
  98. formatError: (error) =>
  99. error instanceof Error ? error.message : String(error),
  100. isEnabled: () => true,
  101. });
  102. integration.bindConfigGetter(() => ({
  103. goal: {
  104. verification: "subagent",
  105. budget: {
  106. defaultTokens: 5_000_000,
  107. defaultMainTurns: 50,
  108. defaultActiveSeconds: 14_400,
  109. graceSteps: 1,
  110. },
  111. verifier: { repeatedNotMetLimit: 5, evidence: "brief" },
  112. evaluator: { maxTokens: 32_000 },
  113. subagent: { maxTokens: 500_000 },
  114. },
  115. }));
  116. integration.bindVerifier(verifier, transcriptReader);
  117. });
  118. afterEach(async () => {
  119. closeLocalRuntimeDb(dataDir);
  120. await rm(dataDir, { recursive: true, force: true });
  121. });
  122. async function seedRunningGoal(): Promise<ThreadGoalState> {
  123. const created = await integration.store.create({
  124. sessionId: SESSION,
  125. objective: OBJECTIVE,
  126. });
  127. const enqueued = await integration.store.transitionKickoffState(
  128. created.goalId,
  129. created.kickoffState,
  130. "enqueued",
  131. );
  132. const consumed = await integration.store.transitionKickoffState(
  133. created.goalId,
  134. enqueued?.kickoffState ?? "enqueued",
  135. "consumed",
  136. );
  137. if (!consumed) throw new Error("expected a kickoff-consumed Goal");
  138. return consumed;
  139. }
  140. async function admitGoalTurn(
  141. goal: ThreadGoalState,
  142. turnId: string,
  143. ): Promise<void> {
  144. turnTimings.begin(SESSION, turnId);
  145. const prepared = await integration.prepareTurnAdmission({
  146. sessionId: SESSION,
  147. turnId,
  148. provenance: {
  149. source: "thread-goal",
  150. sourceContext: {
  151. origin: {
  152. type: "thread-goal-continuation",
  153. goalId: goal.goalId,
  154. goalUpdatedAt: goal.updatedAt,
  155. objectiveDigest: digestThreadGoalObjective(goal.objective),
  156. kind: "active",
  157. },
  158. },
  159. },
  160. hasPendingPlan: async () => false,
  161. hasPriorityMailboxWork: async () => false,
  162. });
  163. if (prepared?.status !== "ready") {
  164. throw new Error(
  165. `expected a ready Goal admission, got ${JSON.stringify(prepared)}`,
  166. );
  167. }
  168. await prepared.commit();
  169. }
  170. /** Admit the explicit user message exactly the way TurnSystem does. */
  171. async function admitUserTurn(turnId: string): Promise<void> {
  172. const prepared = await integration.prepareTurnAdmission({
  173. sessionId: SESSION,
  174. turnId,
  175. provenance: { source: "api" },
  176. hasPendingPlan: async () => false,
  177. hasPriorityMailboxWork: async () => false,
  178. });
  179. if (prepared?.status !== "ready") {
  180. throw new Error(
  181. `expected a ready user admission, got ${JSON.stringify(prepared)}`,
  182. );
  183. }
  184. turnTimings.begin(SESSION, turnId);
  185. await prepared.commit();
  186. }
  187. async function proposeCompletion(turnId: string): Promise<void> {
  188. const updateGoal = (await integration.runtimeToolsFor(false, SESSION)).find(
  189. (tool) => tool.def.name === "update_goal",
  190. );
  191. if (!updateGoal) throw new Error("expected the update_goal tool");
  192. await updateGoal.impl.execute(
  193. { sessionId: SESSION, turnId },
  194. { status: "complete" },
  195. );
  196. }
  197. function settleInput(turnId: string, tokens: number) {
  198. return {
  199. sessionId: SESSION,
  200. turnId,
  201. status: "completed" as const,
  202. tokens,
  203. retracted: false,
  204. workerModelKey: "configured-provider/worker-model",
  205. };
  206. }
  207. /** The re-armed follow-up origin, as it was handed to the Queue transport. */
  208. function rearmedOrigin(): Record<string, unknown> {
  209. const [submitted] = enqueuePostTurnContinuation.mock.calls.at(-1) as [
  210. { readonly message: { readonly origin?: unknown } },
  211. ];
  212. return submitted.message.origin as Record<string, unknown>;
  213. }
  214. /**
  215. * Run the shared prefix: main Turn settles into a subagent verification, the
  216. * user interrupts, and the drain rebuilds the follow-up at the new epoch.
  217. * Returns the in-flight main settlement so the caller can choose when the
  218. * verifier verdict — and with it the stale charge — lands.
  219. */
  220. async function interruptVerifiedGoal(): Promise<{
  221. readonly settlement: Promise<unknown>;
  222. readonly rearmed: ThreadGoalState;
  223. }> {
  224. const goal = await seedRunningGoal();
  225. await admitGoalTurn(goal, MAIN_TURN);
  226. await proposeCompletion(MAIN_TURN);
  227. now += 1;
  228. const settlement = integration.settleInjectedTurn(
  229. settleInput(MAIN_TURN, MAIN_TOKENS),
  230. );
  231. await verifierStarted.promise;
  232. turnTimings.finish(SESSION, MAIN_TURN);
  233. // The user types while the verifier is still running: the breaker reset
  234. // advances the epoch and arms the re-arm marker.
  235. now += 1;
  236. await admitUserTurn(USER_TURN);
  237. now += 1;
  238. await integration.settleInjectedTurn(settleInput(USER_TURN, 0));
  239. turnTimings.finish(SESSION, USER_TURN);
  240. expect(enqueuePostTurnContinuation).toHaveBeenCalled();
  241. const rearmed = await integration.store.getBySession(SESSION);
  242. if (!rearmed) throw new Error("expected the Goal to survive the user Turn");
  243. expect(rearmedOrigin()).toMatchObject({
  244. type: "thread-goal-continuation",
  245. goalId: rearmed.goalId,
  246. goalUpdatedAt: rearmed.updatedAt,
  247. });
  248. return { settlement, rearmed };
  249. }
  250. describe("LocalThreadGoalIntegration stale verifier charge vs. re-armed continuation", () => {
  251. it("keeps a re-armed continuation runnable when the stale verifier charge lands after it was admitted", async () => {
  252. const { settlement, rearmed } = await interruptVerifiedGoal();
  253. // The rebuilt follow-up is admitted at the current epoch and starts.
  254. now += 1;
  255. await admitGoalTurn(rearmed, REARMED_TURN);
  256. await expect(
  257. integration.checkTurnBudget({
  258. sessionId: SESSION,
  259. turnId: REARMED_TURN,
  260. observedTokens: 0,
  261. }),
  262. ).resolves.toMatchObject({ decision: "allow" });
  263. // Only now does the verifier finish. Its verdict is stale and rejected —
  264. // which is correct — but its charge must not retire the running Turn.
  265. now += 1;
  266. verifierVerdict.resolve({
  267. backend: "subagent",
  268. verdict: { verdict: "met", reason: "The release evidence is complete." },
  269. usage: {
  270. tokens: VERIFIER_TOKENS,
  271. activeSeconds: 4,
  272. incomplete: false,
  273. childTurns: 4,
  274. },
  275. });
  276. await settlement;
  277. const charged = await integration.store.getById(rearmed.goalId);
  278. // The stale verdict never completes the Goal, but the spend is recorded.
  279. expect(charged).toMatchObject({
  280. status: "active",
  281. tokensUsed: MAIN_TOKENS + VERIFIER_TOKENS,
  282. });
  283. expect(charged?.updatedAt).toBe(rearmed.updatedAt);
  284. // The running Turn keeps its tools ...
  285. await expect(
  286. integration.checkTurnBudget({
  287. sessionId: SESSION,
  288. turnId: REARMED_TURN,
  289. observedTokens: 0,
  290. }),
  291. ).resolves.toMatchObject({ decision: "allow" });
  292. // ... and settles as a real Turn, so something owns the next step.
  293. now += 1;
  294. enqueuePostTurnContinuation.mockClear();
  295. const decision = await integration.settleInjectedTurn(
  296. settleInput(REARMED_TURN, REARMED_TOKENS),
  297. );
  298. turnTimings.finish(SESSION, REARMED_TURN);
  299. expect(decision).not.toMatchObject({ action: "stale" });
  300. const final = await integration.store.getById(rearmed.goalId);
  301. // No token is lost: main Turn + verifier + re-armed Turn.
  302. expect(final?.tokensUsed).toBe(
  303. MAIN_TOKENS + VERIFIER_TOKENS + REARMED_TOKENS,
  304. );
  305. expect(final?.turnsUsed).toBe(2);
  306. // The Goal either moved on or has a follow-up queued — never `active`
  307. // with nothing left to run it.
  308. expect(
  309. final?.status !== "active" ||
  310. enqueuePostTurnContinuation.mock.calls.length > 0,
  311. ).toBe(true);
  312. });
  313. it("admits the re-armed continuation when the stale verifier charge lands first", async () => {
  314. // The other interleaving: the charge commits before the follow-up is
  315. // admitted. The admission then has to observe an epoch the charge did not
  316. // move, or the queue item is cancelled and nothing runs either.
  317. const { settlement } = await interruptVerifiedGoal();
  318. now += 1;
  319. verifierVerdict.resolve({
  320. backend: "subagent",
  321. verdict: { verdict: "met", reason: "The release evidence is complete." },
  322. usage: {
  323. tokens: VERIFIER_TOKENS,
  324. activeSeconds: 4,
  325. incomplete: false,
  326. childTurns: 4,
  327. },
  328. });
  329. await settlement;
  330. await expect(
  331. integration.classifyQueuedItem({
  332. sessionId: SESSION,
  333. clientRequestId: `thread-goal-followup:${MAIN_TURN}`,
  334. message: { origin: rearmedOrigin() },
  335. }),
  336. ).resolves.toBe("ready");
  337. const charged = await integration.store.getById(
  338. rearmedOrigin().goalId as string,
  339. );
  340. if (!charged) throw new Error("expected the charged Goal to persist");
  341. expect(charged).toMatchObject({
  342. status: "active",
  343. tokensUsed: MAIN_TOKENS + VERIFIER_TOKENS,
  344. });
  345. now += 1;
  346. await admitGoalTurn(charged, REARMED_TURN);
  347. await expect(
  348. integration.checkTurnBudget({
  349. sessionId: SESSION,
  350. turnId: REARMED_TURN,
  351. observedTokens: 0,
  352. }),
  353. ).resolves.toMatchObject({ decision: "allow" });
  354. });
  355. });