host-integration-settlement.test.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. import {
  2. LocalActiveTurnTimingRegistry,
  3. LocalThreadGoalIntegration,
  4. admitGoalTurn,
  5. boundUsageResult,
  6. continuationQueueItem,
  7. describe,
  8. digestThreadGoalObjective,
  9. expect,
  10. flushContinuationKick,
  11. goal,
  12. it,
  13. kickoffQueueItem,
  14. makeIntegration,
  15. makeStore,
  16. settledDecision,
  17. submitGoalProposal,
  18. vi,
  19. type GoalTurnBinding,
  20. type HostGoalStore,
  21. type LocalQueuedMessage,
  22. type ThreadGoalBoundUsageDelta,
  23. type ThreadGoalBoundUsageResult,
  24. type ThreadGoalDecisionResult,
  25. type ThreadGoalState,
  26. } from "./host-integration-testkit.js";
  27. describe("LocalThreadGoalIntegration injected v2 Turn settlement", () => {
  28. it("accounts a bound main Turn and durably queues its continuation", async () => {
  29. const active = goal();
  30. const bumpBoundUsage = vi.fn(async () => boundUsageResult(active));
  31. const updateBreaker = vi.fn();
  32. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  33. const { integration, emitRuntimeEvent } = makeIntegration({
  34. store: makeStore({
  35. getBySession: async () => active,
  36. bumpBoundUsage,
  37. updateBreaker,
  38. }),
  39. enqueuePostTurnContinuation,
  40. });
  41. await admitGoalTurn(integration, active, "turn_int");
  42. const decision = await integration.settleInjectedTurn({
  43. sessionId: active.sessionId,
  44. turnId: "turn_int",
  45. status: "completed",
  46. tokens: 10,
  47. retracted: false,
  48. usageIncomplete: true,
  49. });
  50. expect(decision).toEqual({
  51. stage: 10,
  52. action: "continued",
  53. reason: "goal_active",
  54. goalId: active.goalId,
  55. decisionEpoch: active.updatedAt,
  56. });
  57. expect(bumpBoundUsage).toHaveBeenCalledWith(
  58. expect.objectContaining({ goalId: active.goalId, turnId: "turn_int" }),
  59. { tokens: 10, activeSeconds: 0, mainTurns: 1 },
  60. { tokens: null, mainTurns: null, activeSeconds: null },
  61. );
  62. expect(updateBreaker).not.toHaveBeenCalled();
  63. expect(emitRuntimeEvent).toHaveBeenCalledWith({
  64. type: "goal.turn_settled",
  65. at: 1_700_000_000_000,
  66. payload: expect.objectContaining({
  67. goalId: active.goalId,
  68. sessionId: active.sessionId,
  69. turnId: "turn_int",
  70. status: "completed",
  71. tokens: 10,
  72. usageIncomplete: true,
  73. }),
  74. });
  75. expect(enqueuePostTurnContinuation).toHaveBeenCalledWith({
  76. sessionId: active.sessionId,
  77. turnId: "turn_int",
  78. message: expect.objectContaining({
  79. content: expect.stringContaining(
  80. "follow the goal contract from the kickoff context",
  81. ),
  82. origin: expect.objectContaining({
  83. goalId: active.goalId,
  84. kind: "active",
  85. }),
  86. }),
  87. });
  88. });
  89. it("pauses a bound Goal with a distinct reason when accounting fails", async () => {
  90. const active = goal();
  91. const paused = goal({
  92. status: "paused",
  93. statusReason: "paused(accounting_unavailable)",
  94. updatedAt: active.updatedAt + 1,
  95. });
  96. const settleBoundTurn = vi.fn(async () => settledDecision(paused));
  97. const reportFailure = vi.fn();
  98. const { integration, emitBusEvent } = makeIntegration({
  99. store: makeStore({
  100. getBySession: async () => active,
  101. bumpBoundUsage: async () => {
  102. throw new Error("sqlite busy");
  103. },
  104. settleBoundTurn,
  105. }),
  106. reportFailure,
  107. });
  108. await admitGoalTurn(integration, active, "turn_int");
  109. await expect(
  110. integration.settleInjectedTurn({
  111. sessionId: active.sessionId,
  112. turnId: "turn_int",
  113. status: "completed",
  114. tokens: 10,
  115. retracted: false,
  116. }),
  117. ).resolves.toEqual({
  118. stage: 1,
  119. action: "settled",
  120. reason: "paused(accounting_unavailable)",
  121. goalId: paused.goalId,
  122. decisionEpoch: paused.updatedAt,
  123. });
  124. expect(settleBoundTurn).toHaveBeenCalledWith({
  125. goalId: active.goalId,
  126. expectedEpoch: active.updatedAt,
  127. objectiveDigest: digestThreadGoalObjective(active.objective),
  128. next: {
  129. status: "paused",
  130. statusReason: "paused(accounting_unavailable)",
  131. },
  132. });
  133. expect(reportFailure).toHaveBeenCalledWith(
  134. active.sessionId,
  135. "thread_goal_accounting_failed:sqlite busy",
  136. );
  137. expect(emitBusEvent).toHaveBeenCalledWith({
  138. type: "thread_goal.updated",
  139. payload: {
  140. goal: expect.objectContaining({
  141. goalId: paused.goalId,
  142. status: "paused",
  143. statusReason: "paused(accounting_unavailable)",
  144. }),
  145. },
  146. });
  147. });
  148. it("settles an accepted completion proposal only after accounting and breaker CAS", async () => {
  149. const active = goal();
  150. let current = active;
  151. const accounted = goal({ turnsUsed: 1, updatedAt: active.updatedAt + 1 });
  152. const breakerChecked = goal({
  153. turnsUsed: 1,
  154. replyFingerprint: "checked",
  155. updatedAt: accounted.updatedAt + 1,
  156. });
  157. const completed = goal({
  158. status: "complete",
  159. statusReason: "complete(worker_proposal)",
  160. turnsUsed: 1,
  161. replyFingerprint: "checked",
  162. updatedAt: breakerChecked.updatedAt + 1,
  163. });
  164. const updateBreaker = vi.fn(async () => {
  165. current = breakerChecked;
  166. return {
  167. action: "none" as const,
  168. goal: breakerChecked,
  169. epoch: breakerChecked.updatedAt,
  170. };
  171. });
  172. const settleBoundTurn = vi.fn(async () => {
  173. current = completed;
  174. return settledDecision(completed);
  175. });
  176. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  177. const { integration } = makeIntegration({
  178. store: makeStore({
  179. getBySession: async () => current,
  180. bumpBoundUsage: async () => {
  181. current = accounted;
  182. return boundUsageResult(accounted);
  183. },
  184. updateBreaker,
  185. settleBoundTurn,
  186. }),
  187. enqueuePostTurnContinuation,
  188. });
  189. await admitGoalTurn(integration, active, "turn_int");
  190. const proposal = await submitGoalProposal(integration, "complete");
  191. expect(JSON.parse(proposal.text)).toMatchObject({
  192. proposal: { status: "complete" },
  193. goal: { status: "active" },
  194. });
  195. expect(proposal.terminate).toBe(true);
  196. expect(current.status).toBe("active");
  197. const decision = await integration.settleInjectedTurn({
  198. sessionId: active.sessionId,
  199. turnId: "turn_int",
  200. status: "completed",
  201. tokens: 0,
  202. retracted: false,
  203. finalAssistantText: "all work is complete",
  204. });
  205. expect(decision).toEqual({
  206. stage: 9,
  207. action: "settled",
  208. reason: "complete(worker_proposal)",
  209. goalId: completed.goalId,
  210. decisionEpoch: completed.updatedAt,
  211. });
  212. expect(updateBreaker).toHaveBeenCalledWith(active.goalId, {
  213. expectedEpoch: accounted.updatedAt,
  214. fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/u),
  215. toolActivity: "unknown",
  216. limit: 3,
  217. pauseReason: "paused(no_progress_after_completion_claim)",
  218. });
  219. expect(settleBoundTurn).toHaveBeenCalledWith({
  220. goalId: active.goalId,
  221. expectedEpoch: breakerChecked.updatedAt,
  222. objectiveDigest: digestThreadGoalObjective(active.objective),
  223. next: { status: "complete", statusReason: "complete(worker_proposal)" },
  224. workerProposal: { type: "complete", turnId: "turn_int" },
  225. });
  226. expect(current.status).toBe("complete");
  227. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  228. });
  229. it("lets a block proposal win over completion in the same Turn and skips the breaker", async () => {
  230. const active = goal();
  231. const accounted = goal({ turnsUsed: 1, updatedAt: active.updatedAt + 1 });
  232. const blocked = goal({
  233. status: "blocked",
  234. statusReason: "blocked(worker_reported)",
  235. turnsUsed: 1,
  236. updatedAt: accounted.updatedAt + 1,
  237. });
  238. const updateBreaker = vi.fn();
  239. const settleBoundTurn = vi.fn(async () => settledDecision(blocked));
  240. const { integration, emitRuntimeEvent, enqueuePostTurnContinuation } =
  241. makeIntegration({
  242. store: makeStore({
  243. getBySession: async () => active,
  244. bumpBoundUsage: async () => boundUsageResult(accounted),
  245. updateBreaker,
  246. settleBoundTurn,
  247. }),
  248. });
  249. await admitGoalTurn(integration, active, "turn_int");
  250. await submitGoalProposal(integration, "complete");
  251. await submitGoalProposal(
  252. integration,
  253. "blocked",
  254. "turn_int",
  255. "The same inaccessible dependency persisted.",
  256. );
  257. await integration.settleInjectedTurn({
  258. sessionId: active.sessionId,
  259. turnId: "turn_int",
  260. status: "completed",
  261. tokens: 0,
  262. retracted: false,
  263. finalAssistantText: "cannot proceed",
  264. });
  265. expect(settleBoundTurn).toHaveBeenCalledWith({
  266. goalId: active.goalId,
  267. expectedEpoch: accounted.updatedAt,
  268. objectiveDigest: digestThreadGoalObjective(active.objective),
  269. next: { status: "blocked", statusReason: "blocked(worker_reported)" },
  270. workerProposal: {
  271. type: "blocked",
  272. turnId: "turn_int",
  273. summary: "The same inaccessible dependency persisted.",
  274. },
  275. });
  276. expect(emitRuntimeEvent).toHaveBeenCalledWith({
  277. type: "goal.worker_proposal_decided",
  278. at: 1_700_000_000_000,
  279. payload: {
  280. goalId: active.goalId,
  281. sessionId: active.sessionId,
  282. turnId: "turn_int",
  283. source: "worker",
  284. proposal: "blocked",
  285. disposition: "accepted",
  286. resultStatus: "blocked",
  287. statusReason: "blocked(worker_reported)",
  288. summaryPresent: true,
  289. summaryDigest: expect.stringMatching(/^[a-f0-9]{64}$/u),
  290. },
  291. });
  292. expect(updateBreaker).not.toHaveBeenCalled();
  293. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  294. });
  295. it("keeps a concurrent user pause authoritative after proposal collection", async () => {
  296. let current = goal();
  297. const admitted = current;
  298. const paused = goal({
  299. status: "paused",
  300. statusReason: "paused(user_requested)",
  301. updatedAt: current.updatedAt + 1,
  302. });
  303. const settleBoundTurn = vi.fn();
  304. const { integration, enqueuePostTurnContinuation } = makeIntegration({
  305. store: makeStore({
  306. getBySession: async () => current,
  307. bumpBoundUsage: async (_binding, delta) =>
  308. boundUsageResult(
  309. {
  310. ...paused,
  311. tokensUsed: paused.tokensUsed + delta.tokens,
  312. turnsUsed: paused.turnsUsed + delta.mainTurns,
  313. },
  314. { staleReason: "goal_epoch" },
  315. ),
  316. settleBoundTurn,
  317. }),
  318. });
  319. await admitGoalTurn(integration, admitted, "turn_int");
  320. await submitGoalProposal(integration, "complete");
  321. current = paused;
  322. await integration.settleInjectedTurn({
  323. sessionId: admitted.sessionId,
  324. turnId: "turn_int",
  325. status: "completed",
  326. tokens: 5,
  327. retracted: false,
  328. });
  329. expect(settleBoundTurn).not.toHaveBeenCalled();
  330. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  331. expect(current.status).toBe("paused");
  332. });
  333. it("queues a deferable continuation without breaker work when a dependency appears", async () => {
  334. const active = goal();
  335. let current = active;
  336. const accounted = goal({ turnsUsed: 1, updatedAt: active.updatedAt + 1 });
  337. let pendingPermission = false;
  338. const settleBoundTurn = vi.fn();
  339. const updateBreaker = vi.fn();
  340. const { integration, enqueuePostTurnContinuation } = makeIntegration({
  341. store: makeStore({
  342. getBySession: async () => current,
  343. bumpBoundUsage: async () => {
  344. current = accounted;
  345. return boundUsageResult(accounted);
  346. },
  347. updateBreaker,
  348. settleBoundTurn,
  349. }),
  350. hasPendingPermission: async () => pendingPermission,
  351. });
  352. await admitGoalTurn(integration, active, "turn_int");
  353. await submitGoalProposal(integration, "complete");
  354. pendingPermission = true;
  355. const decision = await integration.settleInjectedTurn({
  356. sessionId: active.sessionId,
  357. turnId: "turn_int",
  358. status: "completed",
  359. tokens: 0,
  360. retracted: false,
  361. });
  362. expect(decision).toEqual({
  363. stage: 5,
  364. action: "deferred",
  365. reason: "deferred(permission)",
  366. goalId: active.goalId,
  367. decisionEpoch: accounted.updatedAt,
  368. });
  369. expect(settleBoundTurn).not.toHaveBeenCalled();
  370. expect(updateBreaker).not.toHaveBeenCalled();
  371. expect(enqueuePostTurnContinuation).toHaveBeenCalledWith(
  372. expect.objectContaining({
  373. sessionId: active.sessionId,
  374. turnId: "turn_int",
  375. message: expect.objectContaining({
  376. origin: expect.objectContaining({
  377. goalUpdatedAt: accounted.updatedAt,
  378. }),
  379. }),
  380. }),
  381. );
  382. expect(current.status).toBe("active");
  383. });
  384. it("applies the dependency gate even without a terminal proposal", async () => {
  385. const active = goal();
  386. let pendingQuestionnaire = false;
  387. const updateBreaker = vi.fn();
  388. const { integration, enqueuePostTurnContinuation } = makeIntegration({
  389. store: makeStore({
  390. getBySession: async () => active,
  391. bumpBoundUsage: async () => boundUsageResult(active),
  392. updateBreaker,
  393. }),
  394. hasPendingQuestionnaire: async () => pendingQuestionnaire,
  395. });
  396. await admitGoalTurn(integration, active, "turn_int");
  397. pendingQuestionnaire = true;
  398. const decision = await integration.settleInjectedTurn({
  399. sessionId: active.sessionId,
  400. turnId: "turn_int",
  401. status: "completed",
  402. tokens: 0,
  403. retracted: false,
  404. });
  405. expect(decision).toMatchObject({
  406. stage: 5,
  407. action: "deferred",
  408. reason: "deferred(questionnaire)",
  409. });
  410. expect(updateBreaker).not.toHaveBeenCalled();
  411. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  412. });
  413. it.each(["evaluator", "subagent"] as const)(
  414. "pauses %s verification when no verifier provider is installed",
  415. async (verification) => {
  416. const active = goal();
  417. const paused = goal({
  418. status: "paused",
  419. statusReason: "paused(verifier_unavailable)",
  420. updatedAt: active.updatedAt + 1,
  421. });
  422. const updateBreaker = vi.fn();
  423. const settleBoundTurn = vi.fn(async () => settledDecision(paused));
  424. const { integration, enqueuePostTurnContinuation } = makeIntegration({
  425. store: makeStore({
  426. getBySession: async () => active,
  427. bumpBoundUsage: async () => boundUsageResult(active),
  428. updateBreaker,
  429. settleBoundTurn,
  430. }),
  431. });
  432. integration.bindConfigGetter(() => ({ goal: { verification } }));
  433. await admitGoalTurn(integration, active, "turn_int");
  434. // Only a completion claim opens a verification, so only a claiming turn
  435. // can discover that no verifier is installed.
  436. await submitGoalProposal(integration, "complete");
  437. const decision = await integration.settleInjectedTurn({
  438. sessionId: active.sessionId,
  439. turnId: "turn_int",
  440. status: "completed",
  441. tokens: 0,
  442. retracted: false,
  443. });
  444. expect(decision).toMatchObject({
  445. stage: 9,
  446. action: "settled",
  447. reason: "paused(verifier_unavailable)",
  448. });
  449. expect(settleBoundTurn).toHaveBeenCalledWith(
  450. expect.objectContaining({
  451. next: {
  452. status: "paused",
  453. statusReason: "paused(verifier_unavailable)",
  454. },
  455. }),
  456. );
  457. expect(updateBreaker).not.toHaveBeenCalled();
  458. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  459. },
  460. );
  461. it("discards a collected proposal when the process-local Turn lifecycle is lost", async () => {
  462. const active = goal();
  463. const bumpBoundUsage = vi.fn();
  464. const settleBoundTurn = vi.fn();
  465. const { integration, turnTimings, enqueuePostTurnContinuation } =
  466. makeIntegration({
  467. store: makeStore({
  468. getBySession: async () => active,
  469. bumpBoundUsage,
  470. settleBoundTurn,
  471. }),
  472. });
  473. await admitGoalTurn(integration, active, "turn_int");
  474. await submitGoalProposal(integration, "complete");
  475. turnTimings.finish(active.sessionId, "turn_int");
  476. await integration.settleInjectedTurn({
  477. sessionId: active.sessionId,
  478. turnId: "turn_int",
  479. status: "completed",
  480. tokens: 0,
  481. retracted: false,
  482. });
  483. expect(bumpBoundUsage).not.toHaveBeenCalled();
  484. expect(settleBoundTurn).not.toHaveBeenCalled();
  485. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  486. expect(active.status).toBe("active");
  487. });
  488. it("ignores an ordinary unbound Turn even when the session currently has an active Goal", async () => {
  489. const active = goal();
  490. const bumpBoundUsage = vi.fn();
  491. const settleBoundTurn = vi.fn();
  492. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  493. const { integration } = makeIntegration({
  494. store: makeStore({
  495. getBySession: async () => active,
  496. bumpBoundUsage,
  497. settleBoundTurn,
  498. }),
  499. enqueuePostTurnContinuation,
  500. });
  501. await integration.settleInjectedTurn({
  502. sessionId: active.sessionId,
  503. turnId: "turn_int",
  504. status: "completed",
  505. tokens: 99,
  506. retracted: false,
  507. });
  508. expect(bumpBoundUsage).not.toHaveBeenCalled();
  509. expect(settleBoundTurn).not.toHaveBeenCalled();
  510. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  511. });
  512. it("never attributes an old binding to a replacement Goal in the same session", async () => {
  513. let current = goal({ goalId: "tg_old" });
  514. const replacement = goal({
  515. goalId: "tg_replacement",
  516. objective: "Replacement objective",
  517. });
  518. const bumpBoundUsage = vi.fn(async (binding: GoalTurnBinding) => {
  519. expect(binding.goalId).toBe("tg_old");
  520. return { staleReason: "missing_goal" as const };
  521. });
  522. const settleBoundTurn = vi.fn();
  523. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  524. const { integration } = makeIntegration({
  525. store: makeStore({
  526. getBySession: async () => current,
  527. getById: async (goalId) =>
  528. current.goalId === goalId ? current : undefined,
  529. bumpBoundUsage,
  530. settleBoundTurn,
  531. }),
  532. enqueuePostTurnContinuation,
  533. });
  534. await admitGoalTurn(integration, current, "turn_int");
  535. current = replacement;
  536. await integration.settleInjectedTurn({
  537. sessionId: current.sessionId,
  538. turnId: "turn_int",
  539. status: "completed",
  540. tokens: 25,
  541. retracted: false,
  542. });
  543. expect(bumpBoundUsage).toHaveBeenCalledWith(
  544. expect.objectContaining({ goalId: "tg_old" }),
  545. { tokens: 25, activeSeconds: 0, mainTurns: 1 },
  546. expect.any(Object),
  547. );
  548. expect(settleBoundTurn).not.toHaveBeenCalled();
  549. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  550. expect(current).toBe(replacement);
  551. });
  552. it.each(["goal_epoch", "objective_digest"] as const)(
  553. "records usage but stops all business decisions for a stale %s binding",
  554. async (staleReason) => {
  555. let current = goal();
  556. const admitted = current;
  557. const bumpBoundUsage = vi.fn(
  558. async (_binding, delta: ThreadGoalBoundUsageDelta) => {
  559. current = {
  560. ...current,
  561. tokensUsed: current.tokensUsed + delta.tokens,
  562. turnsUsed: current.turnsUsed + delta.mainTurns,
  563. objective:
  564. staleReason === "objective_digest"
  565. ? "Edited objective"
  566. : current.objective,
  567. updatedAt:
  568. staleReason === "goal_epoch"
  569. ? current.updatedAt + 1
  570. : current.updatedAt,
  571. };
  572. return boundUsageResult(current, { staleReason });
  573. },
  574. );
  575. const updateBreaker = vi.fn();
  576. const settleBoundTurn = vi.fn();
  577. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  578. const { integration } = makeIntegration({
  579. store: makeStore({
  580. getBySession: async () => current,
  581. bumpBoundUsage,
  582. updateBreaker,
  583. settleBoundTurn,
  584. }),
  585. enqueuePostTurnContinuation,
  586. });
  587. await admitGoalTurn(integration, admitted, "turn_int");
  588. await integration.settleInjectedTurn({
  589. sessionId: admitted.sessionId,
  590. turnId: "turn_int",
  591. status: "completed",
  592. tokens: 25,
  593. retracted: false,
  594. finalAssistantText: "stale result",
  595. });
  596. expect(current).toMatchObject({ tokensUsed: 25, turnsUsed: 1 });
  597. expect(updateBreaker).not.toHaveBeenCalled();
  598. expect(settleBoundTurn).not.toHaveBeenCalled();
  599. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  600. },
  601. );
  602. it("persists a repeated reply and puts a no-progress nudge in the next Turn", async () => {
  603. let current = goal();
  604. const admitted = current;
  605. const repeated = goal({
  606. replyFingerprint: "persisted-fingerprint",
  607. noProgressStreak: 1,
  608. updatedAt: current.updatedAt + 1,
  609. });
  610. const updateBreaker = vi.fn(async () => {
  611. current = repeated;
  612. return {
  613. action: "nudge" as const,
  614. goal: repeated,
  615. epoch: repeated.updatedAt,
  616. };
  617. });
  618. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  619. const { integration, emitRuntimeEvent } = makeIntegration({
  620. store: makeStore({
  621. getBySession: async () => current,
  622. bumpBoundUsage: async () => boundUsageResult(current),
  623. updateBreaker,
  624. }),
  625. enqueuePostTurnContinuation,
  626. });
  627. integration.bindConfigGetter(() => ({
  628. goal: { breaker: { repeatedReplyLimit: 4 } },
  629. }));
  630. await admitGoalTurn(integration, admitted, "turn_int");
  631. await integration.settleInjectedTurn({
  632. sessionId: admitted.sessionId,
  633. turnId: "turn_int",
  634. status: "completed",
  635. tokens: 0,
  636. retracted: false,
  637. finalAssistantText: "same final reply",
  638. });
  639. expect(updateBreaker).toHaveBeenCalledWith(admitted.goalId, {
  640. expectedEpoch: admitted.updatedAt,
  641. fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/u),
  642. toolActivity: "unknown",
  643. limit: 4,
  644. });
  645. expect(JSON.stringify(emitRuntimeEvent.mock.calls)).not.toContain(
  646. "same final reply",
  647. );
  648. expect(enqueuePostTurnContinuation).toHaveBeenCalledWith(
  649. expect.objectContaining({
  650. message: expect.objectContaining({
  651. content: expect.stringContaining("No-progress guard:"),
  652. origin: expect.objectContaining({
  653. goalUpdatedAt: repeated.updatedAt,
  654. }),
  655. }),
  656. }),
  657. );
  658. });
  659. it("injects one terminal audit after the fifth settled main Goal Turn", async () => {
  660. const admitted = goal({ turnsUsed: 4 });
  661. let current = admitted;
  662. const accounted = goal({ turnsUsed: 5, updatedAt: admitted.updatedAt + 1 });
  663. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  664. const { integration, emitRuntimeEvent } = makeIntegration({
  665. store: makeStore({
  666. getBySession: async () => current,
  667. bumpBoundUsage: async () => {
  668. current = accounted;
  669. return boundUsageResult(accounted);
  670. },
  671. }),
  672. enqueuePostTurnContinuation,
  673. });
  674. await admitGoalTurn(integration, admitted, "turn_five");
  675. const decision = await integration.settleInjectedTurn({
  676. sessionId: admitted.sessionId,
  677. turnId: "turn_five",
  678. status: "completed",
  679. tokens: 0,
  680. retracted: false,
  681. });
  682. expect(decision).toMatchObject({ stage: 10, action: "continued" });
  683. expect(enqueuePostTurnContinuation).toHaveBeenCalledWith(
  684. expect.objectContaining({
  685. message: expect.objectContaining({
  686. content: expect.stringContaining("scheduled five-Turn checkpoint"),
  687. }),
  688. }),
  689. );
  690. expect(emitRuntimeEvent).toHaveBeenCalledWith({
  691. type: "goal.reminder_injected",
  692. at: expect.any(Number),
  693. payload: {
  694. goalId: admitted.goalId,
  695. sessionId: admitted.sessionId,
  696. turnsUsed: 5,
  697. reasons: ["terminal-audit"],
  698. },
  699. });
  700. });
  701. it("records when the repeated-reply threshold overrides a completion proposal", async () => {
  702. const active = goal({
  703. noProgressStreak: 1,
  704. replyFingerprint: "persisted-fingerprint",
  705. });
  706. const paused = goal({
  707. status: "paused",
  708. statusReason: "paused(no_progress_after_completion_claim)",
  709. noProgressStreak: 2,
  710. replyFingerprint: "persisted-fingerprint",
  711. updatedAt: active.updatedAt + 1,
  712. });
  713. const updateBreaker = vi.fn(async () => ({
  714. action: "pause" as const,
  715. goal: paused,
  716. epoch: paused.updatedAt,
  717. }));
  718. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  719. const { integration, emitBusEvent, emitRuntimeEvent } = makeIntegration({
  720. store: makeStore({
  721. getBySession: async () => active,
  722. bumpBoundUsage: async () => boundUsageResult(active),
  723. updateBreaker,
  724. }),
  725. enqueuePostTurnContinuation,
  726. });
  727. await admitGoalTurn(integration, active, "turn_int");
  728. await submitGoalProposal(integration, "complete");
  729. const decision = await integration.settleInjectedTurn({
  730. sessionId: active.sessionId,
  731. turnId: "turn_int",
  732. status: "completed",
  733. tokens: 0,
  734. retracted: false,
  735. finalAssistantText: "same final reply",
  736. });
  737. expect(decision).toMatchObject({
  738. stage: 8,
  739. action: "stopped",
  740. reason: "paused(no_progress_after_completion_claim)",
  741. });
  742. expect(updateBreaker).toHaveBeenCalledWith(active.goalId, {
  743. expectedEpoch: active.updatedAt,
  744. fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/u),
  745. toolActivity: "unknown",
  746. limit: 3,
  747. pauseReason: "paused(no_progress_after_completion_claim)",
  748. });
  749. expect(emitBusEvent).toHaveBeenCalledWith({
  750. type: "thread_goal.updated",
  751. payload: {
  752. goal: expect.objectContaining({
  753. status: "paused",
  754. statusReason: "paused(no_progress_after_completion_claim)",
  755. }),
  756. },
  757. });
  758. expect(emitRuntimeEvent).toHaveBeenCalledWith({
  759. type: "goal.breaker_decided",
  760. at: expect.any(Number),
  761. payload: {
  762. goalId: active.goalId,
  763. sessionId: active.sessionId,
  764. action: "pause",
  765. occurrences: 3,
  766. streak: 2,
  767. toolActivity: "unknown",
  768. noToolStreak: 0,
  769. },
  770. });
  771. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  772. });
  773. it("pauses after three consecutive tool-less main Turns even when every reply differs", async () => {
  774. // GOAL-11 second breaker condition: the replies are all distinct, so only
  775. // the no-tool streak can stop this Goal.
  776. let current = goal();
  777. const admitted = current;
  778. const observed: Array<{ toolActivity: string; limit: number }> = [];
  779. const updateBreaker = vi.fn(
  780. async (
  781. _goalId: string,
  782. input: { toolActivity: string; limit: number; expectedEpoch: number },
  783. ) => {
  784. observed.push({ toolActivity: input.toolActivity, limit: input.limit });
  785. const streak = current.noToolStreak + 1;
  786. const paused = streak >= input.limit;
  787. current = goal({
  788. ...(paused
  789. ? { status: "paused" as const, statusReason: "paused(no_progress)" }
  790. : {}),
  791. noToolStreak: streak,
  792. updatedAt: current.updatedAt + 1,
  793. });
  794. return {
  795. action: paused
  796. ? ("pause" as const)
  797. : streak >= 2
  798. ? ("nudge" as const)
  799. : ("none" as const),
  800. cause: "no_tool" as const,
  801. goal: current,
  802. epoch: current.updatedAt,
  803. };
  804. },
  805. );
  806. const { integration } = makeIntegration({
  807. store: makeStore({
  808. getBySession: async () => current,
  809. bumpBoundUsage: async () => boundUsageResult(current),
  810. updateBreaker,
  811. }),
  812. });
  813. const decisions = [];
  814. for (const [index, reply] of ["reply A", "reply B", "reply C"].entries()) {
  815. const turnId = `turn_no_tool_${index}`;
  816. await admitGoalTurn(integration, current, turnId);
  817. decisions.push(
  818. await integration.settleInjectedTurn({
  819. sessionId: admitted.sessionId,
  820. turnId,
  821. status: "completed",
  822. tokens: 0,
  823. retracted: false,
  824. finalAssistantText: reply,
  825. workSignals: { toolCalls: 0 },
  826. }),
  827. );
  828. }
  829. expect(observed).toEqual([
  830. { toolActivity: "absent", limit: 3 },
  831. { toolActivity: "absent", limit: 3 },
  832. { toolActivity: "absent", limit: 3 },
  833. ]);
  834. expect(decisions[0]).toMatchObject({ action: "continued" });
  835. expect(decisions[1]).toMatchObject({ action: "continued" });
  836. expect(decisions[2]).toMatchObject({
  837. stage: 8,
  838. action: "stopped",
  839. reason: "paused(no_progress)",
  840. });
  841. });
  842. it("reports a real tool call as `used` and a missing work signal as `unknown`", async () => {
  843. const active = goal();
  844. const updateBreaker = vi.fn(async () => ({
  845. action: "none" as const,
  846. goal: active,
  847. epoch: active.updatedAt,
  848. }));
  849. const { integration } = makeIntegration({
  850. store: makeStore({
  851. getBySession: async () => active,
  852. bumpBoundUsage: async () => boundUsageResult(active),
  853. updateBreaker,
  854. }),
  855. });
  856. await admitGoalTurn(integration, active, "turn_used");
  857. await integration.settleInjectedTurn({
  858. sessionId: active.sessionId,
  859. turnId: "turn_used",
  860. status: "completed",
  861. tokens: 0,
  862. retracted: false,
  863. finalAssistantText: "did work",
  864. workSignals: { toolCalls: 2 },
  865. });
  866. await admitGoalTurn(integration, active, "turn_unobserved");
  867. await integration.settleInjectedTurn({
  868. sessionId: active.sessionId,
  869. turnId: "turn_unobserved",
  870. status: "completed",
  871. tokens: 0,
  872. retracted: false,
  873. finalAssistantText: "no observation for this Turn",
  874. });
  875. expect(
  876. updateBreaker.mock.calls.map(
  877. (call) => (call[1] as { toolActivity: string }).toolActivity,
  878. ),
  879. ).toEqual(["used", "unknown"]);
  880. });
  881. it("retries a failed continuation enqueue without charging the same Turn twice", async () => {
  882. const active = goal();
  883. const bumpBoundUsage = vi.fn(async () => boundUsageResult(active));
  884. const enqueuePostTurnContinuation = vi
  885. .fn()
  886. .mockRejectedValueOnce(new Error("queue unavailable"))
  887. .mockResolvedValueOnce(undefined);
  888. const { integration, reportFailure } = makeIntegration({
  889. store: makeStore({ getBySession: async () => active, bumpBoundUsage }),
  890. enqueuePostTurnContinuation,
  891. });
  892. await admitGoalTurn(integration, active, "turn_int");
  893. const settlement = {
  894. sessionId: active.sessionId,
  895. turnId: "turn_int",
  896. status: "completed" as const,
  897. tokens: 10,
  898. retracted: false,
  899. };
  900. await expect(integration.settleInjectedTurn(settlement)).rejects.toThrow(
  901. "queue unavailable",
  902. );
  903. await expect(
  904. integration.settleInjectedTurn(settlement),
  905. ).resolves.toMatchObject({
  906. stage: 10,
  907. action: "continued",
  908. reason: "goal_active",
  909. });
  910. expect(bumpBoundUsage).toHaveBeenCalledOnce();
  911. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  912. expect(reportFailure).toHaveBeenCalledWith(
  913. active.sessionId,
  914. "thread_goal_continuation_enqueue_failed:queue unavailable",
  915. );
  916. });
  917. it("replays the first breaker decision when a tool-less Turn is settled again", async () => {
  918. // The breaker advances the Goal epoch when it writes, while the retry
  919. // reuses the accounting receipt captured before that write. Scoring the
  920. // Turn twice would either double-count the streak or fail its own CAS and
  921. // strand an active Goal without a continuation.
  922. const active = goal();
  923. const afterBreaker = goal({
  924. noToolStreak: 1,
  925. updatedAt: active.updatedAt + 1,
  926. });
  927. const updateBreaker = vi.fn(async () => ({
  928. action: "none" as const,
  929. goal: afterBreaker,
  930. epoch: afterBreaker.updatedAt,
  931. }));
  932. const enqueuePostTurnContinuation = vi
  933. .fn()
  934. .mockRejectedValueOnce(new Error("queue unavailable"))
  935. .mockResolvedValueOnce(undefined);
  936. const { integration } = makeIntegration({
  937. store: makeStore({
  938. getBySession: async () => active,
  939. bumpBoundUsage: async () => boundUsageResult(active),
  940. updateBreaker,
  941. }),
  942. enqueuePostTurnContinuation,
  943. });
  944. await admitGoalTurn(integration, active, "turn_int");
  945. const settlement = {
  946. sessionId: active.sessionId,
  947. turnId: "turn_int",
  948. status: "completed" as const,
  949. tokens: 0,
  950. retracted: false,
  951. workSignals: { toolCalls: 0 },
  952. };
  953. await expect(integration.settleInjectedTurn(settlement)).rejects.toThrow(
  954. "queue unavailable",
  955. );
  956. await expect(
  957. integration.settleInjectedTurn(settlement),
  958. ).resolves.toMatchObject({
  959. stage: 10,
  960. action: "continued",
  961. });
  962. expect(updateBreaker).toHaveBeenCalledOnce();
  963. });
  964. it("clears the no-tool streak on a dependency wait that really used tools", async () => {
  965. // A dependency wait returns at stage 5 and keeps the Goal active. Its real
  966. // tool calls must still interrupt the streak, otherwise the first tool-less
  967. // Turn after the dependency clears would be counted as the third
  968. // consecutive one.
  969. let current = goal({ noToolStreak: 2 });
  970. const admitted = current;
  971. const cleared = goal({ noToolStreak: 0, updatedAt: current.updatedAt + 1 });
  972. const updateBreaker = vi.fn(async () => {
  973. current = cleared;
  974. return {
  975. action: "none" as const,
  976. goal: cleared,
  977. epoch: cleared.updatedAt,
  978. };
  979. });
  980. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  981. let permissionPending = false;
  982. const { integration } = makeIntegration({
  983. store: makeStore({
  984. getBySession: async () => current,
  985. bumpBoundUsage: async () => boundUsageResult(current),
  986. updateBreaker,
  987. }),
  988. hasPendingPermission: async () => permissionPending,
  989. enqueuePostTurnContinuation,
  990. });
  991. await admitGoalTurn(integration, admitted, "turn_int");
  992. // The dependency appears during the Turn, after admission cleared.
  993. permissionPending = true;
  994. const decision = await integration.settleInjectedTurn({
  995. sessionId: admitted.sessionId,
  996. turnId: "turn_int",
  997. status: "completed",
  998. tokens: 0,
  999. retracted: false,
  1000. finalAssistantText: "waiting on a permission prompt",
  1001. workSignals: { toolCalls: 3 },
  1002. });
  1003. expect(decision).toMatchObject({ stage: 5, action: "deferred" });
  1004. expect(updateBreaker).toHaveBeenCalledWith(admitted.goalId, {
  1005. expectedEpoch: admitted.updatedAt,
  1006. // The fingerprint branch stays untouched: this Turn is not being scored
  1007. // for repetition, only cleared of its no-tool streak.
  1008. fingerprint: null,
  1009. toolActivity: "used",
  1010. limit: 3,
  1011. });
  1012. });
  1013. it("leaves a dependency wait alone when there is no live no-tool streak", async () => {
  1014. const active = goal();
  1015. const updateBreaker = vi.fn(async () => ({
  1016. action: "none" as const,
  1017. goal: active,
  1018. epoch: active.updatedAt,
  1019. }));
  1020. let permissionPending = false;
  1021. const { integration } = makeIntegration({
  1022. store: makeStore({
  1023. getBySession: async () => active,
  1024. bumpBoundUsage: async () => boundUsageResult(active),
  1025. updateBreaker,
  1026. }),
  1027. hasPendingPermission: async () => permissionPending,
  1028. });
  1029. await admitGoalTurn(integration, active, "turn_int");
  1030. permissionPending = true;
  1031. const decision = await integration.settleInjectedTurn({
  1032. sessionId: active.sessionId,
  1033. turnId: "turn_int",
  1034. status: "completed",
  1035. tokens: 0,
  1036. retracted: false,
  1037. workSignals: { toolCalls: 3 },
  1038. });
  1039. expect(decision).toMatchObject({ stage: 5, action: "deferred" });
  1040. expect(updateBreaker).not.toHaveBeenCalled();
  1041. });
  1042. it.each([
  1043. ["infra_retryable", "paused", "paused(infra_retryable)"],
  1044. ["unknown", "paused", "paused(infra_retryable)"],
  1045. ["provider_quota", "usage_limited", "usage_limited(provider_quota)"],
  1046. ["rate_limit", "usage_limited", "usage_limited(rate_limit)"],
  1047. ["safety", "blocked", "blocked(safety_policy)"],
  1048. ] as const)(
  1049. "maps %s failure through the bound settlement CAS to %s",
  1050. async (failureClass, status, statusReason) => {
  1051. const active = goal();
  1052. const settled = goal({
  1053. status,
  1054. statusReason,
  1055. updatedAt: active.updatedAt + 1,
  1056. });
  1057. const settleBoundTurn = vi.fn(async () => settledDecision(settled));
  1058. const enqueuePostTurnContinuation = vi.fn(async () => undefined);
  1059. const { integration, emitBusEvent, emitRuntimeEvent } = makeIntegration({
  1060. store: makeStore({
  1061. getBySession: async () => active,
  1062. bumpBoundUsage: async () => boundUsageResult(active),
  1063. settleBoundTurn,
  1064. }),
  1065. enqueuePostTurnContinuation,
  1066. });
  1067. await admitGoalTurn(integration, active, "turn_int");
  1068. await integration.settleInjectedTurn({
  1069. sessionId: active.sessionId,
  1070. turnId: "turn_int",
  1071. status: "failed",
  1072. failureClass,
  1073. tokens: 0,
  1074. retracted: false,
  1075. });
  1076. expect(settleBoundTurn).toHaveBeenCalledWith({
  1077. goalId: active.goalId,
  1078. expectedEpoch: active.updatedAt,
  1079. objectiveDigest: digestThreadGoalObjective(active.objective),
  1080. next: { status, statusReason },
  1081. });
  1082. expect(emitBusEvent).toHaveBeenCalledWith({
  1083. type: "thread_goal.updated",
  1084. payload: { goal: expect.objectContaining({ status, statusReason }) },
  1085. });
  1086. expect(emitRuntimeEvent).toHaveBeenCalledWith(
  1087. expect.objectContaining({
  1088. type: "goal.turn_settled",
  1089. payload: expect.objectContaining({ failureClass }),
  1090. }),
  1091. );
  1092. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  1093. },
  1094. );
  1095. it("pauses a retracted bound Turn through the same settlement CAS", async () => {
  1096. const active = goal();
  1097. const paused = goal({
  1098. status: "paused",
  1099. statusReason: "paused(retracted)",
  1100. updatedAt: active.updatedAt + 1,
  1101. });
  1102. const settleBoundTurn = vi.fn(async () => settledDecision(paused));
  1103. const { integration, enqueuePostTurnContinuation } = makeIntegration({
  1104. store: makeStore({
  1105. getBySession: async () => active,
  1106. bumpBoundUsage: async () => boundUsageResult(active),
  1107. settleBoundTurn,
  1108. }),
  1109. });
  1110. await admitGoalTurn(integration, active, "turn_int");
  1111. await integration.settleInjectedTurn({
  1112. sessionId: active.sessionId,
  1113. turnId: "turn_int",
  1114. status: "completed",
  1115. tokens: 0,
  1116. retracted: true,
  1117. });
  1118. expect(settleBoundTurn).toHaveBeenCalledWith(
  1119. expect.objectContaining({
  1120. goalId: active.goalId,
  1121. next: { status: "paused", statusReason: "paused(retracted)" },
  1122. }),
  1123. );
  1124. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  1125. });
  1126. it("accounts an aborted bound Turn but leaves Goal completion authority untouched", async () => {
  1127. const active = goal();
  1128. const bumpBoundUsage = vi.fn(async () => boundUsageResult(active));
  1129. const settleBoundTurn = vi.fn();
  1130. const { integration, enqueuePostTurnContinuation } = makeIntegration({
  1131. store: makeStore({
  1132. getBySession: async () => active,
  1133. bumpBoundUsage,
  1134. settleBoundTurn,
  1135. }),
  1136. });
  1137. await admitGoalTurn(integration, active, "turn_int");
  1138. await integration.settleInjectedTurn({
  1139. sessionId: active.sessionId,
  1140. turnId: "turn_int",
  1141. status: "aborted",
  1142. tokens: 7,
  1143. retracted: false,
  1144. });
  1145. expect(bumpBoundUsage).toHaveBeenCalledOnce();
  1146. expect(settleBoundTurn).not.toHaveBeenCalled();
  1147. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  1148. });
  1149. });