gate.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import { describe, expect, it } from "vitest";
  2. import { digestThreadGoalObjective, type ThreadGoalState } from "@mavis/goal";
  3. import {
  4. finalRecheck,
  5. threadGoalSubagentMaxTokens,
  6. type ThreadGoalFinalRecheckDeps,
  7. } from "../../../src/thread-goal/gate.js";
  8. describe("Thread Goal subagent limits", () => {
  9. it("leaves the verifier token cap absent until it is configured", () => {
  10. expect(threadGoalSubagentMaxTokens()).toBeUndefined();
  11. expect(threadGoalSubagentMaxTokens(() => ({ goal: {} }))).toBeUndefined();
  12. expect(
  13. threadGoalSubagentMaxTokens(() => ({
  14. goal: { subagent: { maxTokens: 123_456 } },
  15. })),
  16. ).toBe(123_456);
  17. });
  18. });
  19. describe("Thread Goal final recheck", () => {
  20. it("captures an exact binding only after every pre-LLM guard is clear", async () => {
  21. const current = goal();
  22. await expect(finalRecheck(deps(current), input(current))).resolves.toEqual({
  23. decision: "ready",
  24. binding: {
  25. goalId: current.goalId,
  26. admittedGoalUpdatedAt: current.updatedAt,
  27. objectiveDigest: digestThreadGoalObjective(current.objective),
  28. turnId: "turn-final",
  29. },
  30. });
  31. });
  32. it.each([
  33. [
  34. "pause",
  35. goal({ status: "paused" }),
  36. {},
  37. "defer",
  38. "deferred(goal_not_active)",
  39. ],
  40. [
  41. "edit",
  42. goal({ updatedAt: 101, objective: "edited" }),
  43. {},
  44. "cancel",
  45. "stale(goal_epoch)",
  46. ],
  47. [
  48. "replace",
  49. goal({ goalId: "goal-replaced" }),
  50. {},
  51. "cancel",
  52. "stale(turn_binding)",
  53. ],
  54. [
  55. "user message",
  56. goal(),
  57. { hasPriorityMailboxWork: true },
  58. "cancel",
  59. "deferred(user_work)",
  60. ],
  61. ] as const)(
  62. "does not admit after a classify/start race: %s",
  63. async (_case, current, guards, decision, reason) => {
  64. await expect(
  65. finalRecheck(deps(current, guards), input(goal())),
  66. ).resolves.toMatchObject({
  67. decision,
  68. reason,
  69. });
  70. },
  71. );
  72. it.each([
  73. ["hasPendingQuestionnaire", "deferred(questionnaire)", "questionnaire"],
  74. ["hasPendingPermission", "deferred(permission)", "permission"],
  75. ["hasPendingPlan", "deferred(plan)", "plan"],
  76. [
  77. "hasRequiredBackgroundWork",
  78. "deferred(required_background)",
  79. "required_background",
  80. ],
  81. [
  82. "hasAutomationOwnerConflict",
  83. "deferred(automation_owner_conflict)",
  84. "automation_owner_conflict",
  85. ],
  86. ] as const)(
  87. "defers while %s is unresolved",
  88. async (guard, reason, waitReason) => {
  89. await expect(
  90. finalRecheck(deps(goal(), { [guard]: true }), input(goal())),
  91. ).resolves.toMatchObject({ decision: "defer", reason, waitReason });
  92. },
  93. );
  94. it("pauses a token-budget state before admission", async () => {
  95. const exhausted = goal({ tokensUsed: 10, tokenBudget: 10 });
  96. await expect(
  97. finalRecheck(deps(exhausted), input(exhausted)),
  98. ).resolves.toMatchObject({
  99. decision: "pause",
  100. reason: "budget_limited(token)",
  101. });
  102. });
  103. it("does not stop admission when no default limits are configured", async () => {
  104. const current = goal({
  105. tokensUsed: 10_000_000,
  106. turnsUsed: 10_000,
  107. timeUsedSeconds: 10_000_000,
  108. tokenBudget: null,
  109. });
  110. await expect(
  111. finalRecheck(deps(current), input(current)),
  112. ).resolves.toMatchObject({
  113. decision: "ready",
  114. });
  115. });
  116. it.each([
  117. [
  118. "default token",
  119. goal({ tokensUsed: 10, tokenBudget: null }),
  120. { defaultTokens: 10, defaultMainTurns: 50, defaultActiveSeconds: 100 },
  121. "budget_limited(token)",
  122. ],
  123. [
  124. "main turn",
  125. goal({ turnsUsed: 2 }),
  126. { defaultTokens: 100, defaultMainTurns: 2, defaultActiveSeconds: 100 },
  127. "budget_limited(main_turn)",
  128. ],
  129. [
  130. "active time",
  131. goal({ timeUsedSeconds: 30 }),
  132. { defaultTokens: 100, defaultMainTurns: 5, defaultActiveSeconds: 30 },
  133. "budget_limited(active_time)",
  134. ],
  135. ] as const)(
  136. "stops admission when the %s budget is exhausted",
  137. async (_label, current, budget, reason) => {
  138. await expect(
  139. finalRecheck(deps(current), input(current), () => ({
  140. goal: { budget },
  141. })),
  142. ).resolves.toMatchObject({ decision: "pause", reason });
  143. },
  144. );
  145. it("rejects an objective digest mismatch even when the epoch was not advanced", async () => {
  146. const current = goal({ objective: "silently changed" });
  147. await expect(
  148. finalRecheck(deps(current), input(goal())),
  149. ).resolves.toMatchObject({
  150. decision: "cancel",
  151. reason: "stale(objective_digest)",
  152. });
  153. });
  154. });
  155. function goal(overrides: Partial<ThreadGoalState> = {}): ThreadGoalState {
  156. return {
  157. goalId: "goal-1",
  158. sessionId: "session-1",
  159. objective: "Ship the release",
  160. status: "active",
  161. createdAt: 1,
  162. updatedAt: 100,
  163. tokensUsed: 0,
  164. turnsUsed: 0,
  165. timeUsedSeconds: 0,
  166. tokenBudget: null,
  167. replyFingerprint: null,
  168. noProgressStreak: 0,
  169. noToolStreak: 0,
  170. lastVerification: undefined,
  171. statusReason: null,
  172. kickoffAttachments: [],
  173. kickoffState: "consumed",
  174. executionWait: null,
  175. ...overrides,
  176. };
  177. }
  178. function input(expected: ThreadGoalState) {
  179. return {
  180. sessionId: expected.sessionId,
  181. goalId: expected.goalId,
  182. expectedUpdatedAt: expected.updatedAt,
  183. expectedObjectiveDigest: digestThreadGoalObjective(expected.objective),
  184. turnId: "turn-final",
  185. };
  186. }
  187. type GuardName = Exclude<keyof ThreadGoalFinalRecheckDeps, "getGoalBySession">;
  188. function deps(
  189. current: ThreadGoalState,
  190. guards: Partial<Record<GuardName, boolean>> = {},
  191. ): ThreadGoalFinalRecheckDeps {
  192. return {
  193. getGoalBySession: async () => current,
  194. hasPendingQuestionnaire: async () =>
  195. guards.hasPendingQuestionnaire ?? false,
  196. hasPendingPermission: async () => guards.hasPendingPermission ?? false,
  197. hasPendingPlan: async () => guards.hasPendingPlan ?? false,
  198. hasRequiredBackgroundWork: async () =>
  199. guards.hasRequiredBackgroundWork ?? false,
  200. hasAutomationOwnerConflict: async () =>
  201. guards.hasAutomationOwnerConflict ?? false,
  202. hasPriorityMailboxWork: async () => guards.hasPriorityMailboxWork ?? false,
  203. };
  204. }