thread-goal-verifier-contract.test.ts 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  1. import { PNG } from "pngjs";
  2. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { describe, expect, it, vi } from "vitest";
  6. import {
  7. digestThreadGoalObjective,
  8. VerificationDispatchError,
  9. type ThreadGoalState,
  10. type TranscriptWindowReader,
  11. type VerificationAttempt,
  12. type VerificationDispatchFailureCode,
  13. type VerificationResult,
  14. type VerificationUsage,
  15. type VerificationVerdict,
  16. type VerifierPort,
  17. } from "@mavis/goal";
  18. import { closeLocalRuntimeDb } from "../../src/persistence/db.js";
  19. import type { ThreadGoalGateConfig } from "../../src/thread-goal/gate.js";
  20. import { LocalThreadGoalIntegration } from "../../src/thread-goal/host-integration.js";
  21. import { LocalActiveTurnTimingRegistry } from "../../src/turns/active-turn-timing.js";
  22. const SESSION_ID = "session-verifier-contract";
  23. const TURN_ID = "turn-verifier-contract";
  24. const OBJECTIVE = "Prove the release candidate is ready";
  25. const WORKER_MODEL_KEY = "configured-provider/worker-model";
  26. const KNOWN_USAGE = { tokens: 3, activeSeconds: 2, incomplete: false } as const;
  27. const VERDICT_CASES: ReadonlyArray<{
  28. readonly label: string;
  29. readonly verdict: VerificationVerdict;
  30. readonly expectedStatus: ThreadGoalState["status"];
  31. readonly expectedReason: ThreadGoalState["statusReason"];
  32. }> = [
  33. {
  34. label: "met",
  35. verdict: {
  36. verdict: "met",
  37. reason: "The transcript contains passing release evidence.",
  38. },
  39. expectedStatus: "complete",
  40. expectedReason: "complete(verifier_met)",
  41. },
  42. {
  43. label: "not_met",
  44. verdict: {
  45. verdict: "not_met",
  46. reason: "The release evidence is incomplete.",
  47. missing: ["production smoke test"],
  48. },
  49. expectedStatus: "active",
  50. expectedReason: null,
  51. },
  52. {
  53. label: "impossible",
  54. verdict: {
  55. verdict: "impossible",
  56. reason: "The required signing key is unavailable.",
  57. blocker: "Release signing key has been revoked.",
  58. },
  59. expectedStatus: "blocked",
  60. expectedReason: "blocked(verifier_impossible)",
  61. },
  62. {
  63. label: "inconclusive",
  64. verdict: {
  65. verdict: "inconclusive",
  66. reason: "The supplied evidence cannot be evaluated.",
  67. code: "evidence_ambiguous",
  68. },
  69. expectedStatus: "paused",
  70. expectedReason: "paused(verifier_unavailable)",
  71. },
  72. ];
  73. const HOST_VERDICT_CASES = VERDICT_CASES.flatMap((testCase) =>
  74. (["evaluator", "subagent"] as const).map((backend) => ({
  75. ...testCase,
  76. backend,
  77. })),
  78. );
  79. interface Harness {
  80. readonly integration: LocalThreadGoalIntegration;
  81. readonly initialGoal: ThreadGoalState;
  82. readonly verifier: VerifierPort;
  83. readonly transcriptReader: TranscriptWindowReader;
  84. readonly enqueuePostTurnContinuation: ReturnType<typeof vi.fn>;
  85. readonly emitRuntimeEvent: ReturnType<typeof vi.fn>;
  86. settle(input?: {
  87. readonly tokens?: number;
  88. readonly finalAssistantText?: string;
  89. readonly workerModelKey?: string | null;
  90. readonly workSignals?: { readonly toolCalls: number };
  91. }): ReturnType<LocalThreadGoalIntegration["settleInjectedTurn"]>;
  92. }
  93. async function withHarness(
  94. options: {
  95. readonly verifier: VerifierPort;
  96. /** `null` omits the config override and exercises route-derived policy. */
  97. readonly configuredVerification?: "none" | "evaluator" | "subagent" | null;
  98. readonly routeConfig?: Omit<ThreadGoalGateConfig, "goal" | "beta">;
  99. readonly tokenBudget?: number;
  100. readonly objectiveResources?: ThreadGoalState["objectiveResources"];
  101. readonly transcriptReader?: TranscriptWindowReader;
  102. readonly enqueuePostTurnContinuation?: ReturnType<typeof vi.fn>;
  103. },
  104. run: (harness: Harness) => Promise<void>,
  105. ): Promise<void> {
  106. const dataDir = await mkdtemp(join(tmpdir(), "goal-verifier-contract-"));
  107. let now = 1_700_000_000_000;
  108. const nowMs = () => now++;
  109. const turnTimings = new LocalActiveTurnTimingRegistry(nowMs);
  110. const enqueuePostTurnContinuation =
  111. options.enqueuePostTurnContinuation ?? vi.fn(async () => undefined);
  112. const emitRuntimeEvent = vi.fn();
  113. const transcriptReader =
  114. options.transcriptReader ??
  115. ({
  116. capture: vi.fn(async () => ({
  117. messages: [{ role: "assistant", content: "Release checks finished." }],
  118. truncated: false,
  119. })),
  120. } satisfies TranscriptWindowReader);
  121. const integration = new LocalThreadGoalIntegration({
  122. dataDir,
  123. nowMs,
  124. turnTimingReader: turnTimings,
  125. publishGlobalEvent: vi.fn(),
  126. isSessionBusy: () => false,
  127. hasPendingQuestionnaire: async () => false,
  128. retireGoalQuestionnaire: async () => false,
  129. hasPendingPermission: async () => false,
  130. hasAutomationOwnerConflict: async () => false,
  131. hasRequiredBackgroundWork: async () => false,
  132. startContinuationTurn: async () => undefined,
  133. enqueueInitialContinuationTurn: async () => undefined,
  134. enqueuePostTurnContinuation,
  135. cancelInitialContinuation: async () => undefined,
  136. requestQueueDispatch: vi.fn(),
  137. hasPendingInitialContinuation: async () => false,
  138. reportFailure: vi.fn(),
  139. formatError: (error) =>
  140. error instanceof Error ? error.message : String(error),
  141. isEnabled: () => true,
  142. emitRuntimeEvent,
  143. });
  144. const configuredVerification =
  145. options.configuredVerification ??
  146. (options.configuredVerification === null ? null : "evaluator");
  147. integration.bindConfigGetter(() => ({
  148. ...options.routeConfig,
  149. goal: {
  150. ...(configuredVerification !== null
  151. ? { verification: configuredVerification }
  152. : {}),
  153. budget: {
  154. defaultTokens: 5_000_000,
  155. defaultMainTurns: 50,
  156. defaultActiveSeconds: 14_400,
  157. graceSteps: 1,
  158. },
  159. verifier: { repeatedNotMetLimit: 5, evidence: "brief" },
  160. evaluator: { maxTokens: 32_000 },
  161. subagent: { maxTokens: 500_000 },
  162. },
  163. }));
  164. integration.bindVerifier(options.verifier, transcriptReader);
  165. try {
  166. let initialGoal = await integration.store.create({
  167. sessionId: SESSION_ID,
  168. objective: OBJECTIVE,
  169. objectiveResources: options.objectiveResources,
  170. ...(options.tokenBudget === undefined
  171. ? {}
  172. : { tokenBudget: options.tokenBudget }),
  173. });
  174. initialGoal =
  175. (await integration.store.transitionKickoffState(
  176. initialGoal.goalId,
  177. "pending",
  178. "enqueued",
  179. )) ?? initialGoal;
  180. initialGoal =
  181. (await integration.store.transitionKickoffState(
  182. initialGoal.goalId,
  183. "enqueued",
  184. "consumed",
  185. )) ?? initialGoal;
  186. turnTimings.begin(SESSION_ID, TURN_ID);
  187. const prepared = await integration.prepareTurnAdmission({
  188. sessionId: SESSION_ID,
  189. turnId: TURN_ID,
  190. provenance: {
  191. source: "thread-goal",
  192. sourceContext: {
  193. origin: {
  194. type: "thread-goal-continuation",
  195. goalId: initialGoal.goalId,
  196. goalUpdatedAt: initialGoal.updatedAt,
  197. objectiveDigest: digestThreadGoalObjective(initialGoal.objective),
  198. kind: "active",
  199. },
  200. },
  201. },
  202. hasPendingPlan: async () => false,
  203. hasPriorityMailboxWork: async () => false,
  204. });
  205. if (prepared?.status !== "ready")
  206. throw new Error("Expected ready Goal admission");
  207. await prepared.commit();
  208. await run({
  209. integration,
  210. initialGoal,
  211. verifier: options.verifier,
  212. transcriptReader,
  213. enqueuePostTurnContinuation,
  214. emitRuntimeEvent,
  215. settle: (input = {}) =>
  216. integration.settleInjectedTurn({
  217. sessionId: SESSION_ID,
  218. turnId: TURN_ID,
  219. status: "completed",
  220. tokens: input.tokens ?? 1,
  221. retracted: false,
  222. ...(input.workerModelKey === null
  223. ? {}
  224. : { workerModelKey: input.workerModelKey ?? WORKER_MODEL_KEY }),
  225. ...(input.finalAssistantText === undefined
  226. ? {}
  227. : { finalAssistantText: input.finalAssistantText }),
  228. ...(input.workSignals === undefined
  229. ? {}
  230. : { workSignals: input.workSignals }),
  231. }),
  232. });
  233. } finally {
  234. closeLocalRuntimeDb(dataDir);
  235. await rm(dataDir, { recursive: true, force: true });
  236. }
  237. }
  238. function verifierResult(
  239. verdict: VerificationVerdict,
  240. usage: VerificationUsage = KNOWN_USAGE,
  241. backend: VerificationResult["backend"] = "evaluator",
  242. ): VerificationResult {
  243. return { backend, verdict, usage };
  244. }
  245. function fixedVerifier(
  246. verdict: VerificationVerdict,
  247. usage: VerificationUsage = KNOWN_USAGE,
  248. backend: VerificationResult["backend"] = "evaluator",
  249. ): VerifierPort {
  250. return {
  251. dispatch: vi.fn(async () =>
  252. verifierResult(
  253. verdict,
  254. backend === "subagent" && usage.childTurns === undefined
  255. ? { ...usage, childTurns: 2 }
  256. : usage,
  257. backend,
  258. ),
  259. ),
  260. };
  261. }
  262. function deferred<T>(): {
  263. readonly promise: Promise<T>;
  264. resolve(value: T): void;
  265. } {
  266. let resolve!: (value: T) => void;
  267. const promise = new Promise<T>((next) => {
  268. resolve = next;
  269. });
  270. return { promise, resolve };
  271. }
  272. async function submitGoalProposal(
  273. harness: Harness,
  274. status: "complete" | "blocked",
  275. summary?: string,
  276. ): Promise<void> {
  277. const updateGoal = (
  278. await harness.integration.runtimeToolsFor(false, SESSION_ID)
  279. ).find((tool) => tool.def.name === "update_goal");
  280. if (!updateGoal) throw new Error("Expected update_goal tool");
  281. await updateGoal.impl.execute(
  282. { sessionId: SESSION_ID, turnId: TURN_ID },
  283. { status, ...(summary ? { summary } : {}) },
  284. );
  285. }
  286. async function proposeCompletion(harness: Harness): Promise<void> {
  287. await submitGoalProposal(harness, "complete");
  288. }
  289. async function proposeBlock(harness: Harness): Promise<void> {
  290. await submitGoalProposal(harness, "blocked");
  291. }
  292. describe("Thread Goal verifier host contract", () => {
  293. it.each([false, true])(
  294. "reloads persisted screenshot evidence and fails closed when missing: %s",
  295. async (missing) => {
  296. const dir = await mkdtemp(join(tmpdir(), "goal-verifier-image-"));
  297. const path = join(dir, "saved.png");
  298. const bytes = PNG.sync.write({
  299. width: 1,
  300. height: 1,
  301. data: Buffer.from([0, 128, 255, 255]),
  302. } as PNG);
  303. if (!missing) await writeFile(path, bytes);
  304. const verifier = fixedVerifier({
  305. verdict: "met",
  306. reason: "Checked all requirements.",
  307. });
  308. try {
  309. await withHarness(
  310. {
  311. verifier,
  312. objectiveResources: [
  313. {
  314. type: "image",
  315. filePath: path,
  316. fileName: "saved.png",
  317. mimeType: "image/png",
  318. assetId: "asset-1",
  319. },
  320. ],
  321. },
  322. async (h) => {
  323. await submitGoalProposal(h, "complete");
  324. await h.settle();
  325. const goal = await h.integration.store.getBySession(SESSION_ID);
  326. if (missing) {
  327. expect(verifier.dispatch).not.toHaveBeenCalled();
  328. expect(goal).toMatchObject({
  329. status: "paused",
  330. statusReason: "paused(verifier_unavailable)",
  331. });
  332. } else {
  333. expect(verifier.dispatch).toHaveBeenCalledWith(
  334. expect.objectContaining({
  335. objectiveResources: [
  336. expect.objectContaining({ filePath: path }),
  337. ],
  338. objectiveImages: [
  339. expect.objectContaining({
  340. data: expect.any(String),
  341. mimeType: expect.stringMatching(/^image\//),
  342. }),
  343. ],
  344. }),
  345. expect.any(AbortSignal),
  346. );
  347. expect(goal?.status).toBe("complete");
  348. }
  349. },
  350. );
  351. } finally {
  352. await rm(dir, { recursive: true, force: true });
  353. }
  354. },
  355. 15_000, // Includes cold image decoder startup and persisted evidence on Windows.
  356. );
  357. it("uses the optional update_goal summary ahead of the final assistant text", async () => {
  358. const verifier = fixedVerifier({
  359. verdict: "met",
  360. reason: "Evidence is sufficient.",
  361. });
  362. await withHarness({ verifier }, async (harness) => {
  363. await submitGoalProposal(
  364. harness,
  365. "complete",
  366. "Structured completion claim.",
  367. );
  368. await harness.settle({ finalAssistantText: "Longer final answer." });
  369. expect(verifier.dispatch).toHaveBeenCalledWith(
  370. expect.objectContaining({
  371. completionSummary: "Structured completion claim.",
  372. finalAssistantText: "Longer final answer.",
  373. hostContext: {
  374. completionProposal: {
  375. observed: true,
  376. status: "complete",
  377. turnId: TURN_ID,
  378. },
  379. settlement: {
  380. phase: "awaiting_verifier",
  381. durableStatusAtDispatch: "active",
  382. transitionOnMet: "complete(verifier_met)",
  383. },
  384. },
  385. evidence: expect.objectContaining({
  386. serializedBrief: expect.stringContaining(
  387. "Structured completion claim.",
  388. ),
  389. }),
  390. }),
  391. expect.any(AbortSignal),
  392. );
  393. });
  394. });
  395. it("falls back to finalAssistantText when update_goal has no summary", async () => {
  396. const verifier = fixedVerifier({
  397. verdict: "met",
  398. reason: "Evidence is sufficient.",
  399. });
  400. await withHarness({ verifier }, async (harness) => {
  401. await proposeCompletion(harness);
  402. await harness.settle({
  403. finalAssistantText: "Fallback completion claim.",
  404. });
  405. expect(verifier.dispatch).toHaveBeenCalledWith(
  406. expect.objectContaining({
  407. evidence: expect.objectContaining({
  408. serializedBrief: expect.stringContaining(
  409. "Fallback completion claim.",
  410. ),
  411. }),
  412. }),
  413. expect.any(AbortSignal),
  414. );
  415. });
  416. });
  417. it("keeps the verifier child trace on the final Goal decision event", async () => {
  418. const verifier: VerifierPort = {
  419. dispatch: vi.fn(async () => ({
  420. backend: "subagent",
  421. verdict: {
  422. verdict: "met",
  423. reason: "The child found complete evidence.",
  424. },
  425. usage: { ...KNOWN_USAGE, childTurns: 1 },
  426. traceRef: {
  427. sessionId: "session-verifier-child",
  428. turnId: "turn-verifier-child",
  429. },
  430. })),
  431. };
  432. await withHarness(
  433. { verifier, configuredVerification: "subagent" },
  434. async (harness) => {
  435. await proposeCompletion(harness);
  436. await harness.settle();
  437. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  438. expect.objectContaining({
  439. type: "goal.verification_decided",
  440. payload: expect.objectContaining({
  441. childSessionId: "session-verifier-child",
  442. childTurnId: "turn-verifier-child",
  443. }),
  444. }),
  445. );
  446. },
  447. );
  448. });
  449. it("lets explicit none override a managed route", async () => {
  450. const verifier = fixedVerifier(
  451. { verdict: "met", reason: "The evidence is sufficient." },
  452. KNOWN_USAGE,
  453. "subagent",
  454. );
  455. await withHarness(
  456. {
  457. verifier,
  458. configuredVerification: "none",
  459. routeConfig: {
  460. provider: { minimax: { options: { authMode: "managed-login" } } },
  461. },
  462. },
  463. async (harness) => {
  464. await proposeCompletion(harness);
  465. await harness.settle({ workerModelKey: "minimax/MiniMax-M3" });
  466. await expect(
  467. harness.integration.store.getById(harness.initialGoal.goalId),
  468. ).resolves.toMatchObject({
  469. status: "complete",
  470. statusReason: "complete(worker_proposal)",
  471. lastVerification: undefined,
  472. });
  473. expect(verifier.dispatch).not.toHaveBeenCalled();
  474. },
  475. );
  476. });
  477. it("lets explicit evaluator override a BYOK route", async () => {
  478. const verifier = fixedVerifier({
  479. verdict: "met",
  480. reason: "The evidence is sufficient.",
  481. });
  482. await withHarness(
  483. { verifier, configuredVerification: "evaluator" },
  484. async (harness) => {
  485. await proposeCompletion(harness);
  486. await harness.settle({
  487. workerModelKey: "custom_provider:work/worker-model",
  488. });
  489. expect(verifier.dispatch).toHaveBeenCalledWith(
  490. expect.objectContaining({ backend: "evaluator" }),
  491. expect.any(AbortSignal),
  492. );
  493. },
  494. );
  495. });
  496. it.each([
  497. [
  498. "managed token plan",
  499. "minimax/MiniMax-M3",
  500. {
  501. provider: {
  502. minimax: { options: { authMode: "managed-login" as const } },
  503. },
  504. },
  505. "subagent",
  506. ],
  507. ["MiniMax API key", "minimax_api/MiniMax-M3", {}, "subagent"],
  508. ["custom provider", "custom_provider:work/worker-model", {}, "none"],
  509. ["configured provider", "openai/worker-model", {}, "none"],
  510. ] as const)(
  511. "derives %s as %s without a config override",
  512. async (_label, workerModelKey, routeConfig, expectedBackend) => {
  513. const verifier = fixedVerifier(
  514. { verdict: "met", reason: "The evidence is sufficient." },
  515. KNOWN_USAGE,
  516. "subagent",
  517. );
  518. await withHarness(
  519. { verifier, configuredVerification: null, routeConfig },
  520. async (harness) => {
  521. await proposeCompletion(harness);
  522. await harness.settle({ workerModelKey });
  523. const persisted = await harness.integration.store.getById(
  524. harness.initialGoal.goalId,
  525. );
  526. if (expectedBackend === "subagent") {
  527. expect(verifier.dispatch).toHaveBeenCalledWith(
  528. expect.objectContaining({ backend: "subagent" }),
  529. expect.any(AbortSignal),
  530. );
  531. expect(persisted).toMatchObject({
  532. status: "complete",
  533. statusReason: "complete(verifier_met)",
  534. lastVerification: { backend: "subagent" },
  535. });
  536. } else {
  537. expect(verifier.dispatch).not.toHaveBeenCalled();
  538. expect(persisted).toMatchObject({
  539. status: "complete",
  540. statusReason: "complete(worker_proposal)",
  541. lastVerification: undefined,
  542. });
  543. }
  544. },
  545. );
  546. },
  547. );
  548. it.each([
  549. ["missing", null],
  550. ["unparseable", "bare-model"],
  551. ] as const)(
  552. "falls back to none for a %s worker model key",
  553. async (_label, workerModelKey) => {
  554. const verifier = fixedVerifier({
  555. verdict: "met",
  556. reason: "The evidence is sufficient.",
  557. });
  558. await withHarness(
  559. { verifier, configuredVerification: null },
  560. async (harness) => {
  561. await proposeCompletion(harness);
  562. await harness.settle({ workerModelKey });
  563. expect(verifier.dispatch).not.toHaveBeenCalled();
  564. await expect(
  565. harness.integration.store.getById(harness.initialGoal.goalId),
  566. ).resolves.toMatchObject({
  567. status: "complete",
  568. statusReason: "complete(worker_proposal)",
  569. });
  570. },
  571. );
  572. },
  573. );
  574. it.each(HOST_VERDICT_CASES)(
  575. "persists $backend $label and applies only the host-owned mapped decision",
  576. async ({ backend, verdict, expectedStatus, expectedReason }) => {
  577. const verifier = fixedVerifier(verdict, KNOWN_USAGE, backend);
  578. await withHarness(
  579. { verifier, configuredVerification: backend },
  580. async (harness) => {
  581. await proposeCompletion(harness);
  582. const decision = await harness.settle({
  583. tokens: 2,
  584. finalAssistantText: "same reply",
  585. });
  586. const persisted = await harness.integration.store.getById(
  587. harness.initialGoal.goalId,
  588. );
  589. expect(verifier.dispatch).toHaveBeenCalledOnce();
  590. expect(verifier.dispatch).toHaveBeenCalledWith(
  591. expect.objectContaining({
  592. backend,
  593. maxTokens: backend === "subagent" ? 500_000 : 32_000,
  594. }),
  595. expect.any(AbortSignal),
  596. );
  597. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  598. expect.objectContaining({
  599. type: "goal.verification_dispatched",
  600. payload: expect.objectContaining({ backend, turnId: TURN_ID }),
  601. }),
  602. );
  603. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  604. expect.objectContaining({
  605. type: "goal.verification_decided",
  606. payload: expect.objectContaining({
  607. verdict: verdict.verdict,
  608. disposition: "accepted",
  609. reportedTokens: 3,
  610. ...(backend === "subagent" ? { childTurns: 2 } : {}),
  611. }),
  612. }),
  613. );
  614. expect(persisted).toMatchObject({
  615. status: expectedStatus,
  616. statusReason: expectedReason,
  617. // The worker Turn's 2 tokens, plus the 3 verifier tokens when the
  618. // subagent backend ran: a subagent verifier is a real child agent
  619. // drawing from the Goal budget, while evaluator spend stays
  620. // report-only.
  621. tokensUsed: backend === "subagent" ? 5 : 2,
  622. turnsUsed: 1,
  623. lastVerification: {
  624. backend,
  625. verdict: verdict.verdict,
  626. turnId: TURN_ID,
  627. objectiveDigest: digestThreadGoalObjective(OBJECTIVE),
  628. },
  629. });
  630. if (verdict.verdict === "met") {
  631. expect(decision).toMatchObject({ stage: 7, action: "settled" });
  632. expect(persisted?.noProgressStreak).toBe(0);
  633. } else if (verdict.verdict === "not_met") {
  634. expect(decision).toMatchObject({ stage: 10, action: "continued" });
  635. expect(harness.enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  636. expect(harness.enqueuePostTurnContinuation).toHaveBeenCalledWith(
  637. expect.objectContaining({
  638. message: expect.objectContaining({
  639. content: expect.stringContaining("production smoke test"),
  640. }),
  641. }),
  642. );
  643. } else {
  644. expect(decision).toMatchObject({ stage: 7, action: "settled" });
  645. }
  646. },
  647. );
  648. },
  649. );
  650. /**
  651. * The budget gate stops the *worker*, at stage 4, before a verifier is ever
  652. * dispatched. What a verifier spends afterwards is charged (subagent) or
  653. * reported (evaluator) at settlement — never checked before dispatch.
  654. */
  655. it("lets an accepted `met` verification win over a tool-less final Turn", async () => {
  656. // GOAL-11: the no-tool breaker sits at stage 8, behind the verification
  657. // decision. A verifier-accepted completion must not be converted into
  658. // `paused(no_progress)` just because the deciding Turn only wrote text.
  659. const verifier = fixedVerifier({
  660. verdict: "met",
  661. reason: "Release evidence is complete.",
  662. });
  663. await withHarness({ verifier }, async (harness) => {
  664. await proposeCompletion(harness);
  665. const decision = await harness.settle({
  666. tokens: 2,
  667. finalAssistantText: "All checks are green.",
  668. workSignals: { toolCalls: 0 },
  669. });
  670. const persisted = await harness.integration.store.getById(
  671. harness.initialGoal.goalId,
  672. );
  673. expect(decision).toMatchObject({ stage: 7, action: "settled" });
  674. expect(persisted).toMatchObject({
  675. status: "complete",
  676. statusReason: "complete(verifier_met)",
  677. noToolStreak: 0,
  678. });
  679. });
  680. });
  681. it("lets the worker token budget win before the verifier is dispatched", async () => {
  682. const verifier = fixedVerifier({
  683. verdict: "met",
  684. reason: "The evidence is sufficient.",
  685. });
  686. await withHarness({ verifier, tokenBudget: 5 }, async (harness) => {
  687. // The claim is present, so only the budget gate can explain the absent
  688. // dispatch — without it this would pass on the completion gate instead.
  689. await proposeCompletion(harness);
  690. const decision = await harness.settle({ tokens: 6 });
  691. const persisted = await harness.integration.store.getById(
  692. harness.initialGoal.goalId,
  693. );
  694. expect(verifier.dispatch).not.toHaveBeenCalled();
  695. expect(decision).toMatchObject({
  696. stage: 4,
  697. action: "budget_limited",
  698. reason: "budget_limited(token)",
  699. });
  700. expect(persisted).toMatchObject({
  701. status: "budget_limited",
  702. statusReason: "budget_limited(token)",
  703. tokensUsed: 6,
  704. lastVerification: undefined,
  705. });
  706. });
  707. });
  708. it.each(VERDICT_CASES)(
  709. "leaves goal.tokensUsed untouched by a $label evaluator verification",
  710. async ({ verdict }) => {
  711. const verifier = fixedVerifier(verdict, {
  712. tokens: 4_000,
  713. activeSeconds: 2,
  714. incomplete: false,
  715. });
  716. await withHarness({ verifier, tokenBudget: 10 }, async (harness) => {
  717. await proposeCompletion(harness);
  718. await harness.settle({ tokens: 2 });
  719. const persisted = await harness.integration.store.getById(
  720. harness.initialGoal.goalId,
  721. );
  722. expect(verifier.dispatch).toHaveBeenCalledOnce();
  723. // 4_000 evaluator tokens against a 10-token budget: evaluator spend is
  724. // report-only, so nothing reaches the ledger and no gate moves.
  725. expect(persisted?.tokensUsed).toBe(2);
  726. expect(persisted?.status).not.toBe("budget_limited");
  727. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  728. expect.objectContaining({
  729. type: "goal.verification_decided",
  730. payload: expect.objectContaining({ reportedTokens: 4_000 }),
  731. }),
  732. );
  733. });
  734. },
  735. );
  736. it.each(VERDICT_CASES)(
  737. "charges subagent verifier tokens to the Goal ledger after a $label verdict",
  738. async ({ verdict, expectedStatus, expectedReason }) => {
  739. const verifier = fixedVerifier(
  740. verdict,
  741. { tokens: 40, activeSeconds: 2, incomplete: false },
  742. "subagent",
  743. );
  744. await withHarness(
  745. { verifier, configuredVerification: "subagent", tokenBudget: 1_000 },
  746. async (harness) => {
  747. await proposeCompletion(harness);
  748. await harness.settle({ tokens: 2 });
  749. const persisted = await harness.integration.store.getById(
  750. harness.initialGoal.goalId,
  751. );
  752. expect(verifier.dispatch).toHaveBeenCalledOnce();
  753. // The verdict-mapped status is unchanged by the charge; only the
  754. // ledger moves: 2 worker tokens + 40 verifier tokens.
  755. expect(persisted).toMatchObject({
  756. status: expectedStatus,
  757. statusReason: expectedReason,
  758. tokensUsed: 42,
  759. });
  760. },
  761. );
  762. },
  763. );
  764. /**
  765. * The verdict CAS runs before the charge, so a Goal the verifier judged
  766. * `met` completes even when the verifier's own spend blows the remaining
  767. * budget — the charge gates only future work, and a complete Goal has none.
  768. */
  769. it("completes a verifier-met Goal even when subagent spend exceeds the budget", async () => {
  770. const verifier = fixedVerifier(
  771. { verdict: "met", reason: "The evidence is sufficient." },
  772. { tokens: 4_000, activeSeconds: 2, incomplete: false },
  773. "subagent",
  774. );
  775. await withHarness(
  776. { verifier, configuredVerification: "subagent", tokenBudget: 10 },
  777. async (harness) => {
  778. await proposeCompletion(harness);
  779. const decision = await harness.settle({ tokens: 2 });
  780. const persisted = await harness.integration.store.getById(
  781. harness.initialGoal.goalId,
  782. );
  783. expect(decision).toMatchObject({ stage: 7, action: "settled" });
  784. expect(persisted).toMatchObject({
  785. status: "complete",
  786. statusReason: "complete(verifier_met)",
  787. tokensUsed: 4_002,
  788. });
  789. },
  790. );
  791. });
  792. it("limits the Goal when subagent verifier spend exhausts the budget after not_met", async () => {
  793. const verifier = fixedVerifier(
  794. {
  795. verdict: "not_met",
  796. reason: "The evidence is incomplete.",
  797. missing: ["smoke test"],
  798. },
  799. { tokens: 4_000, activeSeconds: 2, incomplete: false },
  800. "subagent",
  801. );
  802. await withHarness(
  803. { verifier, configuredVerification: "subagent", tokenBudget: 10 },
  804. async (harness) => {
  805. await proposeCompletion(harness);
  806. const decision = await harness.settle({ tokens: 2 });
  807. const persisted = await harness.integration.store.getById(
  808. harness.initialGoal.goalId,
  809. );
  810. expect(decision).toMatchObject({
  811. stage: 7,
  812. action: "budget_limited",
  813. reason: "budget_limited(token)",
  814. });
  815. expect(persisted).toMatchObject({
  816. status: "budget_limited",
  817. statusReason: "budget_limited(token)",
  818. tokensUsed: 4_002,
  819. lastVerification: { verdict: "not_met" },
  820. });
  821. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  822. expect.objectContaining({
  823. type: "goal.budget_decided",
  824. payload: expect.objectContaining({
  825. dimension: "token",
  826. tokensUsed: 4_002,
  827. }),
  828. }),
  829. );
  830. // The limited Goal gets the budget summary Turn, not the next active
  831. // continuation the not_met verdict would otherwise have enqueued.
  832. expect(harness.enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  833. expect(harness.enqueuePostTurnContinuation).toHaveBeenCalledWith(
  834. expect.objectContaining({
  835. message: expect.objectContaining({
  836. content: expect.stringContaining("reached its token budget"),
  837. }),
  838. }),
  839. );
  840. },
  841. );
  842. });
  843. it("does not charge an incomplete subagent usage sample", async () => {
  844. const verifier = fixedVerifier(
  845. { verdict: "met", reason: "The evidence is sufficient." },
  846. { tokens: null, activeSeconds: 1, incomplete: true },
  847. "subagent",
  848. );
  849. await withHarness(
  850. { verifier, configuredVerification: "subagent", tokenBudget: 1_000 },
  851. async (harness) => {
  852. await proposeCompletion(harness);
  853. await harness.settle({ tokens: 2 });
  854. const persisted = await harness.integration.store.getById(
  855. harness.initialGoal.goalId,
  856. );
  857. // No pessimistic estimate: an observation gap stays a gap.
  858. expect(persisted).toMatchObject({ status: "complete", tokensUsed: 2 });
  859. },
  860. );
  861. });
  862. it.each(VERDICT_CASES)(
  863. "rejects a late $label verdict after the Goal epoch changes",
  864. async ({ verdict }) => {
  865. const started = deferred<void>();
  866. const released = deferred<VerificationResult>();
  867. const verifier: VerifierPort = {
  868. dispatch: vi.fn(async () => {
  869. started.resolve();
  870. return released.promise;
  871. }),
  872. };
  873. await withHarness({ verifier }, async (harness) => {
  874. await proposeCompletion(harness);
  875. const settlement = harness.settle({ tokens: 1 });
  876. await started.promise;
  877. await harness.integration.store.patchByUser(
  878. harness.initialGoal.goalId,
  879. {
  880. objective: "A concurrent user-edited objective",
  881. },
  882. );
  883. released.resolve(
  884. verifierResult(verdict, {
  885. tokens: 2,
  886. activeSeconds: 1,
  887. incomplete: false,
  888. }),
  889. );
  890. const decision = await settlement;
  891. const persisted = await harness.integration.store.getById(
  892. harness.initialGoal.goalId,
  893. );
  894. expect(decision).toMatchObject({
  895. stage: 7,
  896. action: "stale",
  897. reason: "goal_epoch",
  898. });
  899. expect(persisted).toMatchObject({
  900. objective: "A concurrent user-edited objective",
  901. status: "active",
  902. tokensUsed: 1,
  903. lastVerification: undefined,
  904. });
  905. expect(harness.enqueuePostTurnContinuation).not.toHaveBeenCalled();
  906. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  907. expect.objectContaining({
  908. type: "goal.verification_decided",
  909. payload: expect.objectContaining({ disposition: "stale" }),
  910. }),
  911. );
  912. });
  913. },
  914. );
  915. // Every dispatch failure pauses; the reason names the layer that owns the
  916. // fix, so an on-call engineer can route from the persisted status alone.
  917. it.each([
  918. ["timeout", "paused(verifier_timeout)"],
  919. ["api_error", "paused(verifier_unavailable)"],
  920. ["schema_error", "paused(verifier_protocol)"],
  921. ["input_too_large", "paused(verifier_protocol)"],
  922. ["spawn_failed", "paused(verifier_runtime)"],
  923. ["child_crash", "paused(verifier_runtime)"],
  924. ["child_budget_exhausted", "paused(verifier_budget)"],
  925. ["capability_violation", "paused(verifier_capability)"],
  926. ["aborted", "paused(verifier_aborted)"],
  927. ["route_unavailable", "paused(route_unavailable)"],
  928. ] as const)(
  929. "accounts a %s failure and pauses without synthesizing completion",
  930. async (code, expectedReason) => {
  931. const verifier: VerifierPort = {
  932. dispatch: vi.fn(async () => {
  933. throw new VerificationDispatchError(
  934. code as VerificationDispatchFailureCode,
  935. `Verifier failed with ${code}`,
  936. { tokens: 2, activeSeconds: 1, incomplete: false },
  937. );
  938. }),
  939. };
  940. await withHarness({ verifier }, async (harness) => {
  941. await proposeCompletion(harness);
  942. const decision = await harness.settle({ tokens: 1 });
  943. const persisted = await harness.integration.store.getById(
  944. harness.initialGoal.goalId,
  945. );
  946. expect(decision).toMatchObject({
  947. stage: 9,
  948. action: "settled",
  949. reason: expectedReason,
  950. });
  951. expect(persisted).toMatchObject({
  952. status: "paused",
  953. statusReason: expectedReason,
  954. tokensUsed: 1,
  955. lastVerification: undefined,
  956. });
  957. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  958. expect.objectContaining({
  959. type: "goal.verification_decided",
  960. payload: expect.objectContaining({
  961. verdict: "inconclusive",
  962. disposition: "unavailable",
  963. failureCode: code,
  964. }),
  965. }),
  966. );
  967. });
  968. },
  969. );
  970. /**
  971. * A subagent verification can run for minutes. If the host handed the adapter
  972. * a signal nobody ever fires, a user pressing stop leaves a child running and
  973. * still charging the Goal it was just told to abandon.
  974. */
  975. it("aborts an in-flight verification when the host pauses the Goal", async () => {
  976. let observed: AbortSignal | undefined;
  977. let announceDispatch = (): void => undefined;
  978. const reachedVerifier = new Promise<void>((resolve) => {
  979. announceDispatch = resolve;
  980. });
  981. const verifier: VerifierPort = {
  982. dispatch: vi.fn(
  983. async (_attempt: VerificationAttempt, signal: AbortSignal) => {
  984. observed = signal;
  985. announceDispatch();
  986. await new Promise<void>((resolve) =>
  987. signal.addEventListener("abort", () => resolve()),
  988. );
  989. // Reject the way an adapter that does not classify would, so the host
  990. // has to derive `aborted` from the controller it owns.
  991. throw new Error("verifier child terminated");
  992. },
  993. ),
  994. };
  995. await withHarness({ verifier }, async (harness) => {
  996. await proposeCompletion(harness);
  997. const settling = harness.settle();
  998. await reachedVerifier;
  999. expect(observed?.aborted).toBe(false);
  1000. await harness.integration.pauseActiveGoalForAbort(SESSION_ID);
  1001. expect(observed?.aborted).toBe(true);
  1002. // The user's pause won the epoch race, so the verifier's own settlement
  1003. // must refuse rather than overwrite it.
  1004. await expect(settling).resolves.toMatchObject({ action: "stale" });
  1005. await expect(
  1006. harness.integration.store.getById(harness.initialGoal.goalId),
  1007. ).resolves.toMatchObject({
  1008. status: "paused",
  1009. statusReason: "paused(user_requested)",
  1010. });
  1011. });
  1012. });
  1013. /**
  1014. * The attempt cap is a response-size ceiling for one verifier call, not a
  1015. * draw against the Goal's remaining tokens. It stays at the configured
  1016. * maximum however little budget the Goal has left, and an incomplete usage
  1017. * sample is reported as such instead of being charged at the envelope.
  1018. */
  1019. it("caps the attempt at the configured maximum regardless of remaining budget", async () => {
  1020. const verifier = fixedVerifier(
  1021. { verdict: "met", reason: "The evidence is sufficient." },
  1022. { tokens: null, activeSeconds: 1, incomplete: true },
  1023. );
  1024. await withHarness({ verifier, tokenBudget: 101 }, async (harness) => {
  1025. await proposeCompletion(harness);
  1026. const decision = await harness.settle({ tokens: 1 });
  1027. const persisted = await harness.integration.store.getById(
  1028. harness.initialGoal.goalId,
  1029. );
  1030. expect(verifier.dispatch).toHaveBeenCalledWith(
  1031. expect.objectContaining({ maxTokens: 32_000 }),
  1032. expect.any(AbortSignal),
  1033. );
  1034. expect(decision).toMatchObject({ stage: 7, action: "settled" });
  1035. expect(persisted).toMatchObject({
  1036. status: "complete",
  1037. tokensUsed: 1,
  1038. lastVerification: { verdict: "met" },
  1039. });
  1040. expect(harness.emitRuntimeEvent).toHaveBeenCalledWith(
  1041. expect.objectContaining({
  1042. type: "goal.verification_decided",
  1043. payload: expect.objectContaining({
  1044. reportedTokens: null,
  1045. usageIncomplete: true,
  1046. disposition: "accepted",
  1047. }),
  1048. }),
  1049. );
  1050. });
  1051. });
  1052. /**
  1053. * Verification adjudicates the worker's completion claim and nothing else. A
  1054. * productive turn that makes no claim has nothing to adjudicate, so it costs
  1055. * no verifier call and simply continues.
  1056. */
  1057. it("leaves a turn without a completion claim unverified and continues", async () => {
  1058. const verifier = fixedVerifier({
  1059. verdict: "not_met",
  1060. reason: "More evidence is required.",
  1061. missing: ["release approval"],
  1062. });
  1063. const capture = vi.fn(async () => ({ messages: [], truncated: false }));
  1064. await withHarness(
  1065. { verifier, transcriptReader: { capture } },
  1066. async (harness) => {
  1067. const decision = await harness.settle();
  1068. const persisted = await harness.integration.store.getById(
  1069. harness.initialGoal.goalId,
  1070. );
  1071. expect(verifier.dispatch).not.toHaveBeenCalled();
  1072. expect(capture).not.toHaveBeenCalled();
  1073. expect(decision).toMatchObject({ stage: 10, action: "continued" });
  1074. expect(persisted).toMatchObject({
  1075. status: "active",
  1076. lastVerification: undefined,
  1077. });
  1078. },
  1079. );
  1080. });
  1081. /**
  1082. * The claim is what opens the verification, never what decides it: the worker
  1083. * cannot complete its own Goal by asserting it has.
  1084. */
  1085. it("treats a completion proposal as the trigger without granting it completion authority", async () => {
  1086. const verifier = fixedVerifier({
  1087. verdict: "not_met",
  1088. reason: "The completion claim is not supported.",
  1089. missing: ["independent approval"],
  1090. });
  1091. const capture = vi.fn(async () => ({ messages: [], truncated: false }));
  1092. await withHarness(
  1093. { verifier, transcriptReader: { capture } },
  1094. async (harness) => {
  1095. await proposeCompletion(harness);
  1096. await harness.settle();
  1097. const [attempt] = (verifier.dispatch as ReturnType<typeof vi.fn>).mock
  1098. .calls[0] as [VerificationAttempt];
  1099. const persisted = await harness.integration.store.getById(
  1100. harness.initialGoal.goalId,
  1101. );
  1102. expect(verifier.dispatch).toHaveBeenCalledOnce();
  1103. expect(capture).toHaveBeenCalledOnce();
  1104. expect(attempt.transcriptWindow).toEqual({
  1105. messages: [],
  1106. truncated: false,
  1107. });
  1108. expect(persisted).toMatchObject({
  1109. status: "active",
  1110. lastVerification: { verdict: "not_met" },
  1111. });
  1112. },
  1113. );
  1114. });
  1115. /**
  1116. * `blocked` is the worker's own report of a dead end, not a claim of success,
  1117. * so no verifier adjudicates it. Under managed routing this used to fall
  1118. * through to a dispatch whose `not_met` verdict produced no transition at
  1119. * all, silently discarding the report and leaving the Goal spinning on work
  1120. * the worker had already declared stuck.
  1121. */
  1122. it("settles a subagent-routed block proposal without dispatching a verifier", async () => {
  1123. const verifier = fixedVerifier(
  1124. {
  1125. verdict: "not_met",
  1126. reason: "No completion evidence.",
  1127. missing: ["evidence"],
  1128. },
  1129. KNOWN_USAGE,
  1130. "subagent",
  1131. );
  1132. await withHarness(
  1133. { verifier, configuredVerification: "subagent" },
  1134. async (harness) => {
  1135. await proposeBlock(harness);
  1136. const decision = await harness.settle();
  1137. const persisted = await harness.integration.store.getById(
  1138. harness.initialGoal.goalId,
  1139. );
  1140. expect(verifier.dispatch).not.toHaveBeenCalled();
  1141. expect(decision).toMatchObject({
  1142. stage: 9,
  1143. action: "settled",
  1144. reason: "blocked(worker_reported)",
  1145. });
  1146. expect(persisted).toMatchObject({
  1147. status: "blocked",
  1148. statusReason: "blocked(worker_reported)",
  1149. lastVerification: undefined,
  1150. });
  1151. expect(harness.enqueuePostTurnContinuation).not.toHaveBeenCalled();
  1152. },
  1153. );
  1154. });
  1155. it("fails closed when a replaceable verifier returns an invalid met payload", async () => {
  1156. const invalidMet = { verdict: "met", reason: "" } as VerificationVerdict;
  1157. const verifier = fixedVerifier(invalidMet);
  1158. await withHarness({ verifier }, async (harness) => {
  1159. await proposeCompletion(harness);
  1160. await harness.settle();
  1161. const persisted = await harness.integration.store.getById(
  1162. harness.initialGoal.goalId,
  1163. );
  1164. expect(persisted).toMatchObject({
  1165. status: "paused",
  1166. // A malformed verdict is a verifier-contract problem, so it must not
  1167. // read back as a transient provider outage.
  1168. statusReason: "paused(verifier_protocol)",
  1169. lastVerification: {
  1170. verdict: "inconclusive",
  1171. reason: expect.stringContaining("invalid"),
  1172. },
  1173. });
  1174. });
  1175. });
  1176. it("retries a failed continuation enqueue without redispatching the verifier", async () => {
  1177. const verifier = fixedVerifier({
  1178. verdict: "not_met",
  1179. reason: "More evidence is required.",
  1180. missing: ["release approval"],
  1181. });
  1182. const enqueuePostTurnContinuation = vi
  1183. .fn()
  1184. .mockRejectedValueOnce(new Error("queue unavailable"))
  1185. .mockResolvedValueOnce(undefined);
  1186. await withHarness(
  1187. { verifier, enqueuePostTurnContinuation },
  1188. async (harness) => {
  1189. await proposeCompletion(harness);
  1190. await expect(harness.settle()).rejects.toThrow("queue unavailable");
  1191. await expect(harness.settle()).resolves.toMatchObject({
  1192. stage: 10,
  1193. action: "continued",
  1194. });
  1195. const persisted = await harness.integration.store.getById(
  1196. harness.initialGoal.goalId,
  1197. );
  1198. expect(verifier.dispatch).toHaveBeenCalledOnce();
  1199. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  1200. expect(persisted).toMatchObject({
  1201. status: "active",
  1202. tokensUsed: 1,
  1203. lastVerification: {
  1204. verdict: "not_met",
  1205. notMetStreak: 1,
  1206. turnId: TURN_ID,
  1207. },
  1208. });
  1209. },
  1210. );
  1211. });
  1212. });
  1213. /**
  1214. * A verifier dispatch is the one window in which an `active` Goal is running no
  1215. * Turn and is not idle either. Without a projection both clients render it as a
  1216. * plain running Goal that has simply stopped producing output, which is what a
  1217. * two-minute verification actually looked like in the field.
  1218. */
  1219. describe("Thread Goal verification execution wait", () => {
  1220. it("publishes the wait for the dispatch window without advancing the decision epoch", async () => {
  1221. let observed: ThreadGoalState | undefined;
  1222. let epochAtDispatch: number | undefined;
  1223. const verifier: VerifierPort = {
  1224. dispatch: vi.fn(async (attempt: VerificationAttempt) => {
  1225. observed = await integrationRef?.store.getById(attempt.goalId);
  1226. epochAtDispatch = attempt.goalUpdatedAt;
  1227. return verifierResult({
  1228. verdict: "met",
  1229. reason: "The evidence is sufficient.",
  1230. });
  1231. }),
  1232. };
  1233. let integrationRef: LocalThreadGoalIntegration | undefined;
  1234. await withHarness({ verifier }, async (harness) => {
  1235. integrationRef = harness.integration;
  1236. await proposeCompletion(harness);
  1237. await harness.settle();
  1238. // Visible for the whole await, and stamped against the epoch the dispatch
  1239. // was decided on. Comparing to `attempt.goalUpdatedAt` rather than to the
  1240. // pre-settlement epoch is the point: settlement legitimately advances the
  1241. // epoch for usage accounting *before* dispatch, so only this equality
  1242. // isolates the wait write itself as a non-advancing one.
  1243. expect(observed).toMatchObject({
  1244. status: "active",
  1245. executionWait: { reason: "verification", sinceMs: expect.any(Number) },
  1246. });
  1247. expect(observed?.updatedAt).toBe(epochAtDispatch);
  1248. // The verdict is what moves the epoch on, which is also what retires the
  1249. // wait for readers.
  1250. const persisted = await harness.integration.store.getById(
  1251. harness.initialGoal.goalId,
  1252. );
  1253. expect(persisted?.updatedAt).toBeGreaterThan(epochAtDispatch ?? 0);
  1254. expect(persisted?.executionWait).toBeNull();
  1255. });
  1256. });
  1257. /**
  1258. * Every way a dispatch can end must retire the wait. A `Verifying` label that
  1259. * outlives its verifier is worse than no label: it reports work nobody is
  1260. * doing, and only a restart would ever clear it.
  1261. */
  1262. it.each([
  1263. {
  1264. label: "met",
  1265. verdict: {
  1266. verdict: "met",
  1267. reason: "All requirements are covered.",
  1268. } as VerificationVerdict,
  1269. },
  1270. {
  1271. label: "not_met",
  1272. verdict: {
  1273. verdict: "not_met",
  1274. reason: "Evidence is missing.",
  1275. missing: ["smoke test"],
  1276. } as VerificationVerdict,
  1277. },
  1278. {
  1279. label: "impossible",
  1280. verdict: {
  1281. verdict: "impossible",
  1282. reason: "The signing key is gone.",
  1283. blocker: "Key revoked.",
  1284. } as VerificationVerdict,
  1285. },
  1286. {
  1287. label: "inconclusive",
  1288. verdict: {
  1289. verdict: "inconclusive",
  1290. reason: "The evidence cannot be evaluated.",
  1291. code: "evidence_ambiguous",
  1292. } as VerificationVerdict,
  1293. },
  1294. ])(
  1295. "retires the wait once the verdict settles: $label",
  1296. async ({ verdict }) => {
  1297. await withHarness(
  1298. { verifier: fixedVerifier(verdict) },
  1299. async (harness) => {
  1300. await proposeCompletion(harness);
  1301. await harness.settle();
  1302. const persisted = await harness.integration.store.getById(
  1303. harness.initialGoal.goalId,
  1304. );
  1305. expect(persisted?.executionWait).toBeNull();
  1306. },
  1307. );
  1308. },
  1309. );
  1310. it.each(["api_error", "timeout", "schema_error"] as const)(
  1311. "retires the wait when dispatch fails: %s",
  1312. async (code: VerificationDispatchFailureCode) => {
  1313. const verifier: VerifierPort = {
  1314. dispatch: vi.fn(async () => {
  1315. throw new VerificationDispatchError(code, `verifier ${code}`, {
  1316. tokens: null,
  1317. activeSeconds: 0,
  1318. incomplete: true,
  1319. });
  1320. }),
  1321. };
  1322. await withHarness({ verifier }, async (harness) => {
  1323. await proposeCompletion(harness);
  1324. await harness.settle();
  1325. const persisted = await harness.integration.store.getById(
  1326. harness.initialGoal.goalId,
  1327. );
  1328. expect(persisted?.executionWait).toBeNull();
  1329. });
  1330. },
  1331. );
  1332. it("retires the wait when an unclassified verifier child crashes", async () => {
  1333. const verifier: VerifierPort = {
  1334. dispatch: vi.fn(async () => {
  1335. throw new Error("verifier child terminated");
  1336. }),
  1337. };
  1338. await withHarness({ verifier }, async (harness) => {
  1339. await proposeCompletion(harness);
  1340. await harness.settle();
  1341. const persisted = await harness.integration.store.getById(
  1342. harness.initialGoal.goalId,
  1343. );
  1344. expect(persisted?.executionWait).toBeNull();
  1345. });
  1346. });
  1347. /**
  1348. * The user winning the epoch race is the case the epoch stamp exists for: the
  1349. * pause writes a new `updatedAt`, which makes the wait unreadable *before*
  1350. * the dispatch unwinds. The later clear then finds nothing current to clear
  1351. * and must leave the paused Goal untouched rather than resurrect a row.
  1352. */
  1353. it("drops the wait when a user pause supersedes the verification epoch", async () => {
  1354. let announceDispatch = (): void => undefined;
  1355. const reachedVerifier = new Promise<void>((resolve) => {
  1356. announceDispatch = resolve;
  1357. });
  1358. const verifier: VerifierPort = {
  1359. dispatch: vi.fn(
  1360. async (_attempt: VerificationAttempt, signal: AbortSignal) => {
  1361. announceDispatch();
  1362. await new Promise<void>((resolve) =>
  1363. signal.addEventListener("abort", () => resolve()),
  1364. );
  1365. throw new Error("verifier child terminated");
  1366. },
  1367. ),
  1368. };
  1369. await withHarness({ verifier }, async (harness) => {
  1370. await proposeCompletion(harness);
  1371. const settling = harness.settle();
  1372. await reachedVerifier;
  1373. await expect(
  1374. harness.integration.store.getById(harness.initialGoal.goalId),
  1375. ).resolves.toMatchObject({ executionWait: { reason: "verification" } });
  1376. await harness.integration.pauseActiveGoalForAbort(SESSION_ID);
  1377. await expect(settling).resolves.toMatchObject({ action: "stale" });
  1378. await expect(
  1379. harness.integration.store.getById(harness.initialGoal.goalId),
  1380. ).resolves.toMatchObject({
  1381. status: "paused",
  1382. statusReason: "paused(user_requested)",
  1383. executionWait: null,
  1384. });
  1385. });
  1386. });
  1387. /**
  1388. * Verification lives only in the dispatching process, so a wait found at
  1389. * startup is stale by construction. The cleanup must not sit behind
  1390. * continuation recovery, which legitimately skips Goals for reasons that have
  1391. * nothing to do with the wait.
  1392. */
  1393. it("clears a wait left behind by a crashed process without advancing the epoch", async () => {
  1394. const verifier = fixedVerifier({ verdict: "met", reason: "Sufficient." });
  1395. await withHarness({ verifier }, async (harness) => {
  1396. const goalId = harness.initialGoal.goalId;
  1397. const before = await harness.integration.store.getById(goalId);
  1398. if (!before) throw new Error("Expected a persisted Goal");
  1399. await harness.integration.store.setExecutionWaitAtEpoch({
  1400. goalId,
  1401. expectedUpdatedAt: before.updatedAt,
  1402. reason: "verification",
  1403. });
  1404. await expect(
  1405. harness.integration.store.listGoalsWaitingOnVerification(),
  1406. ).resolves.toMatchObject([{ goalId }]);
  1407. await expect(
  1408. harness.integration.clearStaleVerificationWaits(),
  1409. ).resolves.toBe(1);
  1410. await expect(
  1411. harness.integration.store.getById(goalId),
  1412. ).resolves.toMatchObject({
  1413. status: "active",
  1414. updatedAt: before.updatedAt,
  1415. executionWait: null,
  1416. });
  1417. // Idempotent: a second startup finds nothing left to correct.
  1418. await expect(
  1419. harness.integration.clearStaleVerificationWaits(),
  1420. ).resolves.toBe(0);
  1421. });
  1422. });
  1423. });