host-integration-testkit.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /**
  2. * `LocalThreadGoalIntegration` — host-side wiring for steering injection.
  3. *
  4. * Targets the MR-2/3/4 surfaces in isolation: the integration class
  5. * doesn't depend on `LocalApiHost`, so we can drive it with vi.fn() deps
  6. * and pin the codex-parity behaviour without a SQLite round trip.
  7. *
  8. * Pins:
  9. * - PATCH with `objectiveChanged: true` steers the codex
  10. * `objective_updated` prompt into a busy Turn immediately
  11. * - The edited objective invalidates model-authored completion from the
  12. * pre-edit Turn, while a successor Turn can finalize normally
  13. * - PATCH with `objectiveChanged: true` and an idle session does NOT
  14. * abort; instead the next `continue_if_idle` kick swaps in the
  15. * objective_updated prompt (consumed once)
  16. * - settlement that observes `budget_limited` queues one hidden summary
  17. * using a restart-stable idempotency key
  18. * - a later ordinary Turn is never attributed to a Goal that had already
  19. * stopped before that Turn began, while a mid-Turn completion still keeps
  20. * the usage accrued before its status boundary
  21. * - Budget summary delivery is reconstructed from durable status and keyed
  22. * by Goal id + epoch; repeated settlement does not enqueue twice
  23. */
  24. import { describe, expect, it, vi } from "vitest";
  25. import type {
  26. InternalTurnPromptReadRegistry,
  27. PromptSnapshotSource,
  28. } from "@mavis/agent-core";
  29. import {
  30. digestThreadGoalObjective,
  31. type GoalTurnBinding,
  32. type ThreadGoalBoundStoreOperations,
  33. type ThreadGoalBoundUsageDelta,
  34. type ThreadGoalBoundUsageResult,
  35. type ThreadGoalDecisionResult,
  36. type ThreadGoalPatchInput,
  37. type ThreadGoalState,
  38. type ThreadGoalStore,
  39. } from "@mavis/goal";
  40. import { LocalThreadGoalIntegration } from "../../../src/thread-goal/host-integration.js";
  41. import type { LocalQueuedMessage } from "../../../src/messages/queue.js";
  42. import { LocalActiveTurnTimingRegistry } from "../../../src/turns/active-turn-timing.js";
  43. function goal(overrides: Partial<ThreadGoalState> = {}): ThreadGoalState {
  44. return {
  45. goalId: "tg_int_1",
  46. sessionId: "sess_int",
  47. objective: "Audit the build pipeline",
  48. status: "active",
  49. createdAt: 0,
  50. updatedAt: 1_700_000_000_000,
  51. tokensUsed: 0,
  52. turnsUsed: 0,
  53. timeUsedSeconds: 0,
  54. tokenBudget: null,
  55. replyFingerprint: null,
  56. noProgressStreak: 0,
  57. noToolStreak: 0,
  58. lastVerification: undefined,
  59. statusReason: null,
  60. kickoffAttachments: [],
  61. kickoffState: "consumed",
  62. executionWait: null,
  63. ...overrides,
  64. };
  65. }
  66. type HostGoalStore = ThreadGoalStore &
  67. ThreadGoalBoundStoreOperations & {
  68. patchByUser(
  69. goalId: string,
  70. input: ThreadGoalPatchInput,
  71. ): Promise<ThreadGoalState>;
  72. resetBreakerAtEpoch(
  73. goalId: string,
  74. expectedEpoch: number,
  75. ): Promise<ThreadGoalState | undefined>;
  76. transitionActiveAtEpoch(
  77. goalId: string,
  78. expectedEpoch: number,
  79. input: {
  80. readonly status: "paused" | "budget_limited";
  81. readonly statusReason: NonNullable<ThreadGoalState["statusReason"]>;
  82. },
  83. ): Promise<ThreadGoalState | undefined>;
  84. setExecutionWaitAtEpoch(input: {
  85. readonly goalId: string;
  86. readonly expectedUpdatedAt: number;
  87. readonly reason: NonNullable<ThreadGoalState["executionWait"]>["reason"];
  88. }): Promise<ThreadGoalState | undefined>;
  89. clearExecutionWaitAtEpoch(input: {
  90. readonly goalId: string;
  91. readonly expectedUpdatedAt: number;
  92. }): Promise<ThreadGoalState | undefined>;
  93. pauseActiveBySession(): Promise<ThreadGoalState | undefined>;
  94. listRecoverableKickoffs(): Promise<ThreadGoalState[]>;
  95. listRecoverableActiveGoals(): Promise<ThreadGoalState[]>;
  96. listRecoverableBudgetLimitSummaries(): Promise<ThreadGoalState[]>;
  97. transitionKickoffState(): Promise<ThreadGoalState | undefined>;
  98. };
  99. type StoreOverrides = Partial<HostGoalStore>;
  100. function makeStore(overrides: StoreOverrides = {}): HostGoalStore {
  101. const getBySession = overrides.getBySession ?? (async () => undefined);
  102. const getById =
  103. overrides.getById ??
  104. (async (goalId: string) => {
  105. const current = await getBySession("sess_int");
  106. return current?.goalId === goalId ? current : undefined;
  107. });
  108. const patch = overrides.patch ?? (async () => goal());
  109. return {
  110. getBySession,
  111. getById,
  112. create: async () => goal(),
  113. patch,
  114. patchByUser: overrides.patchByUser ?? patch,
  115. bumpBoundUsage: async () => ({ staleReason: "missing_goal" }),
  116. settleBoundTurn: async () => ({
  117. status: "stale",
  118. staleReason: "missing_goal",
  119. }),
  120. updateBreaker: async () => ({
  121. action: "stale",
  122. staleReason: "missing_goal",
  123. }),
  124. resetBreakerAtEpoch: async () => undefined,
  125. transitionActiveAtEpoch: async () => undefined,
  126. setExecutionWaitAtEpoch: async () => undefined,
  127. clearExecutionWaitAtEpoch: async () => undefined,
  128. pauseActiveBySession: async () => undefined,
  129. delete: async () => undefined,
  130. listRecoverableKickoffs: async () => [],
  131. listRecoverableActiveGoals: async () => [],
  132. listRecoverableBudgetLimitSummaries: async () => [],
  133. transitionKickoffState: async () => undefined,
  134. ...overrides,
  135. } as HostGoalStore;
  136. }
  137. function makeIntegration(
  138. opts: {
  139. store?: HostGoalStore;
  140. dataDir?: string;
  141. isSessionBusy?: () => boolean;
  142. useTurnTimingBusyFallback?: boolean;
  143. startContinuationTurn?: ReturnType<typeof vi.fn>;
  144. steerContinuationTurn?: ReturnType<typeof vi.fn>;
  145. emitBusEvent?: ReturnType<typeof vi.fn>;
  146. emitRuntimeEvent?: ReturnType<typeof vi.fn>;
  147. reportFailure?: ReturnType<typeof vi.fn>;
  148. enqueueInitialContinuationTurn?: ReturnType<typeof vi.fn>;
  149. enqueuePostTurnContinuation?: ReturnType<typeof vi.fn>;
  150. abortThreadGoalTurn?: ReturnType<typeof vi.fn>;
  151. requestQueueDispatch?: ReturnType<typeof vi.fn>;
  152. cancelInitialContinuation?: ReturnType<typeof vi.fn>;
  153. hasPendingInitialContinuation?: (
  154. sessionId: string,
  155. clientRequestId: string,
  156. ) => Promise<boolean> | boolean;
  157. hasPendingQuestionnaire?: (
  158. sessionId: string,
  159. expectedGoalId: string,
  160. ) => Promise<boolean> | boolean;
  161. retireGoalQuestionnaire?: (
  162. sessionId: string,
  163. goalId: string,
  164. ) => Promise<boolean> | boolean;
  165. hasPendingPermission?: () => Promise<boolean> | boolean;
  166. hasAutomationOwnerConflict?: () => Promise<boolean> | boolean;
  167. hasRequiredBackgroundWork?: () => Promise<boolean> | boolean;
  168. now?: () => number;
  169. turnTimings?: LocalActiveTurnTimingRegistry;
  170. isEnabled?: () => boolean;
  171. promptSnapshots?: () => PromptSnapshotSource | undefined;
  172. internalTurnPromptReads?: () => InternalTurnPromptReadRegistry | undefined;
  173. } = {},
  174. ): {
  175. integration: LocalThreadGoalIntegration;
  176. startContinuationTurn: ReturnType<typeof vi.fn>;
  177. steerContinuationTurn?: ReturnType<typeof vi.fn>;
  178. emitBusEvent: ReturnType<typeof vi.fn>;
  179. emitRuntimeEvent: ReturnType<typeof vi.fn>;
  180. reportFailure: ReturnType<typeof vi.fn>;
  181. enqueueInitialContinuationTurn: ReturnType<typeof vi.fn>;
  182. enqueuePostTurnContinuation: ReturnType<typeof vi.fn>;
  183. cancelInitialContinuation: ReturnType<typeof vi.fn>;
  184. requestQueueDispatch: ReturnType<typeof vi.fn>;
  185. turnTimings: LocalActiveTurnTimingRegistry;
  186. } {
  187. const startContinuationTurn =
  188. opts.startContinuationTurn ?? vi.fn(async () => undefined);
  189. const emitBusEvent = opts.emitBusEvent ?? vi.fn();
  190. const emitRuntimeEvent = opts.emitRuntimeEvent ?? vi.fn();
  191. const reportFailure = opts.reportFailure ?? vi.fn();
  192. const enqueueInitialContinuationTurn =
  193. opts.enqueueInitialContinuationTurn ?? vi.fn(async () => undefined);
  194. const enqueuePostTurnContinuation =
  195. opts.enqueuePostTurnContinuation ?? vi.fn(async () => undefined);
  196. const requestQueueDispatch = opts.requestQueueDispatch ?? vi.fn();
  197. const cancelInitialContinuation =
  198. opts.cancelInitialContinuation ?? vi.fn(async () => undefined);
  199. const store = opts.store ?? makeStore();
  200. const now = opts.now ?? (() => 1_700_000_000_000);
  201. const turnTimings =
  202. opts.turnTimings ?? new LocalActiveTurnTimingRegistry(now);
  203. if (!opts.turnTimings) turnTimings.begin("sess_int", "turn_int");
  204. const integration = new LocalThreadGoalIntegration({
  205. dataDir: opts.dataDir ?? "unused",
  206. nowMs: now,
  207. turnTimingReader: turnTimings,
  208. publishGlobalEvent: emitBusEvent,
  209. ...(opts.promptSnapshots ? { promptSnapshots: opts.promptSnapshots } : {}),
  210. ...(opts.internalTurnPromptReads
  211. ? { internalTurnPromptReads: opts.internalTurnPromptReads }
  212. : {}),
  213. emitRuntimeEvent,
  214. isSessionBusy: opts.useTurnTimingBusyFallback
  215. ? (sessionId) => turnTimings.getBySession(sessionId) !== undefined
  216. : (opts.isSessionBusy ?? (() => false)),
  217. hasPendingQuestionnaire:
  218. opts.hasPendingQuestionnaire ?? (async () => false),
  219. retireGoalQuestionnaire:
  220. opts.retireGoalQuestionnaire ?? (async () => false),
  221. hasPendingPermission: opts.hasPendingPermission ?? (async () => false),
  222. hasAutomationOwnerConflict:
  223. opts.hasAutomationOwnerConflict ?? (async () => false),
  224. hasRequiredBackgroundWork:
  225. opts.hasRequiredBackgroundWork ?? (async () => false),
  226. startContinuationTurn,
  227. enqueueInitialContinuationTurn,
  228. enqueuePostTurnContinuation,
  229. ...(opts.abortThreadGoalTurn
  230. ? { abortThreadGoalTurn: opts.abortThreadGoalTurn }
  231. : {}),
  232. ...(opts.steerContinuationTurn
  233. ? { steerContinuationTurn: opts.steerContinuationTurn }
  234. : {}),
  235. cancelInitialContinuation,
  236. requestQueueDispatch,
  237. hasPendingInitialContinuation:
  238. opts.hasPendingInitialContinuation ?? (async () => false),
  239. reportFailure,
  240. formatError: (err) => (err instanceof Error ? err.message : String(err)),
  241. isEnabled: opts.isEnabled ?? (() => true),
  242. });
  243. // Test seam — replace the constructor-built SQLite store with the fake
  244. // so the deterministic behaviour under test doesn't touch disk.
  245. (integration as unknown as { store: HostGoalStore }).store = store;
  246. return {
  247. integration,
  248. startContinuationTurn,
  249. steerContinuationTurn: opts.steerContinuationTurn,
  250. emitBusEvent,
  251. emitRuntimeEvent,
  252. reportFailure,
  253. enqueueInitialContinuationTurn,
  254. enqueuePostTurnContinuation,
  255. cancelInitialContinuation,
  256. requestQueueDispatch,
  257. turnTimings,
  258. };
  259. }
  260. function kickoffQueueItem(
  261. overrides: Partial<LocalQueuedMessage> = {},
  262. ): LocalQueuedMessage {
  263. return {
  264. itemId: "queue_goal_1",
  265. sessionId: "sess_int",
  266. agentName: "mavis",
  267. source: "api",
  268. status: "queued",
  269. message: {
  270. content: "hidden continuation prompt",
  271. attachments: [],
  272. source: "thread-goal",
  273. origin: {
  274. type: "thread-goal-kickoff",
  275. goalId: "tg_int_1",
  276. goalUpdatedAt: 1_700_000_000_000,
  277. objectiveDigest: digestThreadGoalObjective("Audit the build pipeline"),
  278. displayContent: "Audit the build pipeline",
  279. },
  280. },
  281. clientRequestId: "thread-goal-kickoff:tg_int_1",
  282. createdAt: 1_700_000_000_000,
  283. ...overrides,
  284. };
  285. }
  286. function continuationQueueItem(
  287. overrides: Partial<LocalQueuedMessage> = {},
  288. ): LocalQueuedMessage {
  289. return {
  290. itemId: "queue_goal_followup_1",
  291. sessionId: "sess_int",
  292. agentName: "mavis",
  293. source: "thread-goal",
  294. status: "queued",
  295. message: {
  296. content: "hidden continuation prompt",
  297. attachments: [],
  298. source: "thread-goal",
  299. origin: {
  300. type: "thread-goal-continuation",
  301. goalId: "tg_int_1",
  302. goalUpdatedAt: 1_700_000_000_000,
  303. objectiveDigest: digestThreadGoalObjective("Audit the build pipeline"),
  304. kind: "active",
  305. },
  306. },
  307. clientRequestId: "thread-goal-followup:turn_int",
  308. createdAt: 1_700_000_000_000,
  309. ...overrides,
  310. };
  311. }
  312. async function flushContinuationKick(): Promise<void> {
  313. // handleChanged/injectObjectiveUpdatedSteering fire-and-forget the async
  314. // maybeKickContinuation path; keep this helper resilient as guards are added.
  315. for (let i = 0; i < 8; i += 1) await Promise.resolve();
  316. }
  317. async function admitGoalTurn(
  318. integration: LocalThreadGoalIntegration,
  319. current: ThreadGoalState,
  320. turnId: string,
  321. kind: "active" | "budget-limit" = "active",
  322. ): Promise<void> {
  323. const prepared = await integration.prepareTurnAdmission({
  324. sessionId: current.sessionId,
  325. turnId,
  326. provenance: {
  327. source: "thread-goal",
  328. sourceContext: {
  329. origin: {
  330. type: "thread-goal-continuation",
  331. goalId: current.goalId,
  332. goalUpdatedAt: current.updatedAt,
  333. objectiveDigest: digestThreadGoalObjective(current.objective),
  334. kind,
  335. },
  336. },
  337. },
  338. hasPendingPlan: async () => false,
  339. hasPriorityMailboxWork: async () => false,
  340. });
  341. if (prepared?.status !== "ready") {
  342. throw new Error(`expected ready Goal admission for ${turnId}`);
  343. }
  344. await prepared.commit();
  345. }
  346. async function submitGoalProposal(
  347. integration: LocalThreadGoalIntegration,
  348. status: "complete" | "blocked",
  349. turnId = "turn_int",
  350. summary?: string,
  351. ) {
  352. const updateGoal = (
  353. await integration.runtimeToolsFor(false, "sess_int")
  354. ).find((tool) => tool.def.name === "update_goal");
  355. if (!updateGoal) throw new Error("expected update_goal tool");
  356. return updateGoal.impl.execute(
  357. { sessionId: "sess_int", turnId },
  358. { status, ...(summary ? { summary } : {}) },
  359. );
  360. }
  361. function boundUsageResult(
  362. state: ThreadGoalState,
  363. overrides: Partial<ThreadGoalBoundUsageResult> = {},
  364. ): ThreadGoalBoundUsageResult {
  365. return {
  366. goal: state,
  367. decisionEpoch: state.updatedAt,
  368. transitioned: null,
  369. ...overrides,
  370. };
  371. }
  372. function settledDecision(state: ThreadGoalState): ThreadGoalDecisionResult {
  373. return { status: "settled", goal: state, decisionEpoch: state.updatedAt };
  374. }
  375. export {
  376. LocalActiveTurnTimingRegistry,
  377. LocalThreadGoalIntegration,
  378. admitGoalTurn,
  379. boundUsageResult,
  380. continuationQueueItem,
  381. describe,
  382. digestThreadGoalObjective,
  383. expect,
  384. flushContinuationKick,
  385. goal,
  386. it,
  387. kickoffQueueItem,
  388. makeIntegration,
  389. makeStore,
  390. settledDecision,
  391. submitGoalProposal,
  392. vi,
  393. };
  394. export type {
  395. GoalTurnBinding,
  396. HostGoalStore,
  397. LocalQueuedMessage,
  398. StoreOverrides,
  399. ThreadGoalBoundStoreOperations,
  400. ThreadGoalBoundUsageDelta,
  401. ThreadGoalBoundUsageResult,
  402. ThreadGoalDecisionResult,
  403. ThreadGoalPatchInput,
  404. ThreadGoalState,
  405. ThreadGoalStore,
  406. };