tool-impls.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /**
  2. * Thread Goal tool-impl tests against an in-memory ThreadGoalStore.
  3. *
  4. * Pins the codex-aligned semantics:
  5. * (a) create_goal rejects active / paused goals in the tool before writing,
  6. * while the store remains the race-safe rejection backstop for other
  7. * unfinished states; a complete goal is replaced,
  8. * (b) create_goal validates that the objective is non-empty without inventing
  9. * an implicit length cap,
  10. * (c) update_goal preserves a user pause instead of overwriting it with
  11. * a model-authored complete / blocked status,
  12. * (d) mutation tools fire the onChanged listener (host SSE projection,
  13. * mirrors codex tool.rs emitting ThreadGoalUpdated on tool calls),
  14. * (e) get_goal returns null when missing, the serialized record when set.
  15. */
  16. import { describe, expect, it, beforeEach, vi } from "vitest";
  17. import {
  18. CreateGoalTool,
  19. UpdateGoalTool,
  20. GetGoalTool,
  21. type ThreadGoalTokenBudgetMutationPort,
  22. type ThreadGoalSignalCollector,
  23. } from "../../../src/tool-impls.js";
  24. import {
  25. ThreadGoalAlreadyExistsError,
  26. ThreadGoalObjectiveConflictError,
  27. ThreadGoalStatusConflictError,
  28. type ThreadGoalBreakerResult,
  29. type ThreadGoalCreateInput,
  30. type ThreadGoalPatchInput,
  31. type ThreadGoalStore,
  32. } from "../../../src/store-port.js";
  33. import type { ThreadGoalState } from "../../../src/types.js";
  34. class InMemoryThreadGoalStore implements ThreadGoalStore {
  35. private bySession = new Map<string, ThreadGoalState>();
  36. private byId = new Map<string, ThreadGoalState>();
  37. private seq = 0;
  38. // Deterministic clock so tests don't depend on real time.
  39. public now = 1_700_000_000_000;
  40. async getBySession(sessionId: string): Promise<ThreadGoalState | undefined> {
  41. return this.bySession.get(sessionId);
  42. }
  43. async getById(goalId: string): Promise<ThreadGoalState | undefined> {
  44. return this.byId.get(goalId);
  45. }
  46. async create(input: ThreadGoalCreateInput): Promise<ThreadGoalState> {
  47. const existing = this.bySession.get(input.sessionId);
  48. // codex insert_thread_goal: replace only a complete goal; anything
  49. // else (active / paused / blocked) counts as unfinished.
  50. if (existing && existing.status !== "complete") {
  51. throw new ThreadGoalAlreadyExistsError(existing.goalId);
  52. }
  53. if (existing) {
  54. this.byId.delete(existing.goalId);
  55. }
  56. this.seq += 1;
  57. const goal: ThreadGoalState = {
  58. goalId: `tg_${this.seq}`,
  59. sessionId: input.sessionId,
  60. objective: input.objective,
  61. status: "active",
  62. createdAt: this.now,
  63. updatedAt: this.now,
  64. tokensUsed: 0,
  65. turnsUsed: 0,
  66. timeUsedSeconds: 0,
  67. tokenBudget: input.tokenBudget ?? null,
  68. replyFingerprint: null,
  69. noProgressStreak: 0,
  70. lastVerification: undefined,
  71. statusReason: null,
  72. kickoffAttachments: (input.kickoffAttachments ?? []).map(
  73. (attachment) => ({
  74. ...attachment,
  75. }),
  76. ),
  77. kickoffState: "pending",
  78. };
  79. this.bySession.set(input.sessionId, goal);
  80. this.byId.set(goal.goalId, goal);
  81. return goal;
  82. }
  83. async patch(
  84. goalId: string,
  85. input: ThreadGoalPatchInput,
  86. ): Promise<ThreadGoalState> {
  87. const existing = this.byId.get(goalId);
  88. if (!existing) throw new Error(`goal ${goalId} not found`);
  89. if (existing.status === input.rejectIfCurrentStatus) {
  90. throw new ThreadGoalStatusConflictError(goalId, existing.status);
  91. }
  92. if (
  93. input.rejectIfObjectiveChangedFrom !== undefined &&
  94. existing.objective !== input.rejectIfObjectiveChangedFrom
  95. ) {
  96. throw new ThreadGoalObjectiveConflictError(
  97. goalId,
  98. input.rejectIfObjectiveChangedFrom,
  99. existing.objective,
  100. );
  101. }
  102. this.now += 1;
  103. const next: ThreadGoalState = {
  104. ...existing,
  105. status: input.status ?? existing.status,
  106. objective: input.objective ?? existing.objective,
  107. statusReason:
  108. input.statusReason === undefined
  109. ? existing.statusReason
  110. : input.statusReason,
  111. updatedAt: this.now,
  112. };
  113. this.byId.set(goalId, next);
  114. this.bySession.set(existing.sessionId, next);
  115. return next;
  116. }
  117. async updateBreaker(): Promise<ThreadGoalBreakerResult> {
  118. return { action: "stale", staleReason: "missing_goal" };
  119. }
  120. async delete(goalId: string): Promise<void> {
  121. const existing = this.byId.get(goalId);
  122. if (!existing) return;
  123. this.byId.delete(goalId);
  124. this.bySession.delete(existing.sessionId);
  125. }
  126. }
  127. const ctx = { sessionId: "sess_a", turnId: "turn_a" } as const;
  128. function signalCollector(
  129. result: ReturnType<ThreadGoalSignalCollector["collect"]> = "accepted",
  130. ) {
  131. return { collect: vi.fn(() => result) } satisfies ThreadGoalSignalCollector;
  132. }
  133. function budgetMutation(
  134. result: Awaited<
  135. ReturnType<ThreadGoalTokenBudgetMutationPort["updateTokenBudget"]>
  136. >,
  137. ) {
  138. return {
  139. updateTokenBudget: vi.fn(async () => result),
  140. } satisfies ThreadGoalTokenBudgetMutationPort;
  141. }
  142. describe("thread-goal tool impls", () => {
  143. let store: InMemoryThreadGoalStore;
  144. beforeEach(() => {
  145. store = new InMemoryThreadGoalStore();
  146. });
  147. describe("CreateGoalTool", () => {
  148. it("creates a new active goal when none exists", async () => {
  149. const tool = new CreateGoalTool(store);
  150. const result = await tool.execute(ctx, { objective: "Ship the feature" });
  151. expect(result.tool_name).toBe("create_goal");
  152. const payload = JSON.parse(result.text) as { goal: ThreadGoalState };
  153. expect(payload.goal.objective).toBe("Ship the feature");
  154. expect(payload.goal.status).toBe("active");
  155. expect(payload.goal.sessionId).toBe("sess_a");
  156. });
  157. it("rejects empty objective with the codex-verbatim message", async () => {
  158. const tool = new CreateGoalTool(store);
  159. const result = await tool.execute(ctx, { objective: " " });
  160. const payload = JSON.parse(result.text) as { error: string };
  161. expect(payload.error).toBe("goal objective must not be empty");
  162. });
  163. it("does not impose an objective length limit by default", async () => {
  164. const tool = new CreateGoalTool(store);
  165. const objective = "x".repeat(4_001);
  166. const result = await tool.execute(ctx, {
  167. objective,
  168. });
  169. const payload = JSON.parse(result.text) as { goal: ThreadGoalState };
  170. expect(payload.goal.objective).toBe(objective);
  171. expect(await store.getBySession(ctx.sessionId)).toMatchObject({
  172. objective,
  173. });
  174. });
  175. it("refuses before create when an active goal already exists", async () => {
  176. const tool = new CreateGoalTool(store);
  177. await store.create({ sessionId: ctx.sessionId, objective: "First" });
  178. const createSpy = vi.spyOn(store, "create");
  179. const second = await tool.execute(ctx, { objective: "Second" });
  180. const payload = JSON.parse(second.text) as {
  181. error: string;
  182. existingGoalId: string;
  183. existingStatus: string;
  184. };
  185. expect(payload.error).toBe(
  186. "this thread already has a goal with status active; do not create another goal",
  187. );
  188. expect(payload.existingGoalId).toBe("tg_1");
  189. expect(payload.existingStatus).toBe("active");
  190. expect(createSpy).not.toHaveBeenCalled();
  191. });
  192. it("refuses before create when a paused goal already exists", async () => {
  193. await store.create({ sessionId: ctx.sessionId, objective: "First" });
  194. const first = await store.getBySession(ctx.sessionId);
  195. await store.patch(first!.goalId, { status: "paused" });
  196. const createSpy = vi.spyOn(store, "create");
  197. const second = await new CreateGoalTool(store).execute(ctx, {
  198. objective: "Second",
  199. });
  200. const payload = JSON.parse(second.text) as {
  201. error: string;
  202. existingGoalId: string;
  203. existingStatus: string;
  204. };
  205. expect(payload.error).toBe(
  206. "this thread already has a goal with status paused; do not create another goal",
  207. );
  208. expect(payload.existingGoalId).toBe("tg_1");
  209. expect(payload.existingStatus).toBe("paused");
  210. expect(createSpy).not.toHaveBeenCalled();
  211. });
  212. it("refuses over a blocked goal — blocked counts as unfinished (codex parity)", async () => {
  213. await new CreateGoalTool(store).execute(ctx, { objective: "First" });
  214. const first = await store.getBySession(ctx.sessionId);
  215. await store.patch(first!.goalId, { status: "blocked" });
  216. const second = await new CreateGoalTool(store).execute(ctx, {
  217. objective: "Second",
  218. });
  219. const payload = JSON.parse(second.text) as { error: string };
  220. expect(payload.error).toContain("unfinished goal");
  221. });
  222. it("replaces a complete goal with a fresh active one (codex ON CONFLICT semantics)", async () => {
  223. await new CreateGoalTool(store).execute(ctx, { objective: "First" });
  224. const first = await store.getBySession(ctx.sessionId);
  225. await store.patch(first!.goalId, { status: "complete" });
  226. const second = await new CreateGoalTool(store).execute(ctx, {
  227. objective: "Second",
  228. });
  229. const payload = JSON.parse(second.text) as { goal: ThreadGoalState };
  230. expect(payload.goal.objective).toBe("Second");
  231. expect(payload.goal.status).toBe("active");
  232. expect(payload.goal.goalId).not.toBe("tg_1");
  233. });
  234. it("fires onChanged with the created goal", async () => {
  235. const seen: ThreadGoalState[] = [];
  236. const tool = new CreateGoalTool(store, (goal) => seen.push(goal));
  237. await tool.execute(ctx, { objective: "Notify me" });
  238. expect(seen).toHaveLength(1);
  239. expect(seen[0]?.objective).toBe("Notify me");
  240. expect(seen[0]?.status).toBe("active");
  241. });
  242. it("does NOT fire onChanged when creation is rejected", async () => {
  243. const seen: ThreadGoalState[] = [];
  244. await new CreateGoalTool(store).execute(ctx, { objective: "First" });
  245. const tool = new CreateGoalTool(store, (goal) => seen.push(goal));
  246. await tool.execute(ctx, { objective: "Second" });
  247. expect(seen).toHaveLength(0);
  248. });
  249. });
  250. describe("UpdateGoalTool", () => {
  251. it("updates the token budget through the host mutation port without ending the turn", async () => {
  252. const goal = await store.create({
  253. sessionId: ctx.sessionId,
  254. objective: "x",
  255. tokenBudget: 80_000,
  256. });
  257. const updated = {
  258. ...goal,
  259. tokenBudget: 160_000,
  260. updatedAt: goal.updatedAt + 1,
  261. };
  262. const mutation = budgetMutation({
  263. updated: true,
  264. goal: updated,
  265. previousTokenBudget: 80_000,
  266. resumed: false,
  267. });
  268. const collector = signalCollector();
  269. const result = await new UpdateGoalTool(
  270. store,
  271. collector,
  272. mutation,
  273. ).execute(ctx, {
  274. token_budget: 160_000,
  275. expected_goal_id: goal.goalId,
  276. expected_updated_at: goal.updatedAt,
  277. });
  278. expect(result.terminate).not.toBe(true);
  279. expect(JSON.parse(result.text)).toEqual({
  280. updated: true,
  281. previousTokenBudget: 80_000,
  282. goal: expect.objectContaining({
  283. goalId: goal.goalId,
  284. status: "active",
  285. tokenBudget: 160_000,
  286. }),
  287. resumed: false,
  288. });
  289. expect(mutation.updateTokenBudget).toHaveBeenCalledWith(ctx, {
  290. tokenBudget: 160_000,
  291. expectedGoalId: goal.goalId,
  292. expectedUpdatedAt: goal.updatedAt,
  293. });
  294. expect(collector.collect).not.toHaveBeenCalled();
  295. });
  296. it("clears the token budget and reports a token-limited Goal resume", async () => {
  297. const goal = await store.create({
  298. sessionId: ctx.sessionId,
  299. objective: "x",
  300. tokenBudget: 80_000,
  301. });
  302. const mutation = budgetMutation({
  303. updated: true,
  304. goal: {
  305. ...goal,
  306. status: "active",
  307. statusReason: null,
  308. tokenBudget: null,
  309. updatedAt: goal.updatedAt + 1,
  310. },
  311. previousTokenBudget: 80_000,
  312. resumed: true,
  313. });
  314. const result = await new UpdateGoalTool(
  315. store,
  316. signalCollector(),
  317. mutation,
  318. ).execute(ctx, {
  319. token_budget: null,
  320. expected_goal_id: goal.goalId,
  321. expected_updated_at: goal.updatedAt,
  322. });
  323. expect(JSON.parse(result.text)).toMatchObject({
  324. updated: true,
  325. previousTokenBudget: 80_000,
  326. goal: { status: "active", tokenBudget: null },
  327. resumed: true,
  328. });
  329. });
  330. it("returns the host rejection and allows a retry until one budget update succeeds", async () => {
  331. const goal = await store.create({
  332. sessionId: ctx.sessionId,
  333. objective: "x",
  334. });
  335. const mutation = {
  336. updateTokenBudget: vi
  337. .fn<ThreadGoalTokenBudgetMutationPort["updateTokenBudget"]>()
  338. .mockResolvedValueOnce({
  339. updated: false,
  340. error:
  341. "goal changed; call get_goal again before updating the token budget",
  342. currentGoal: goal,
  343. })
  344. .mockResolvedValueOnce({
  345. updated: true,
  346. goal: {
  347. ...goal,
  348. tokenBudget: 160_000,
  349. updatedAt: goal.updatedAt + 1,
  350. },
  351. previousTokenBudget: null,
  352. resumed: false,
  353. }),
  354. } satisfies ThreadGoalTokenBudgetMutationPort;
  355. const tool = new UpdateGoalTool(store, signalCollector(), mutation);
  356. const input = {
  357. token_budget: 160_000,
  358. expected_goal_id: goal.goalId,
  359. expected_updated_at: goal.updatedAt,
  360. } as const;
  361. expect(JSON.parse((await tool.execute(ctx, input)).text).error).toContain(
  362. "call get_goal again",
  363. );
  364. expect(JSON.parse((await tool.execute(ctx, input)).text).updated).toBe(
  365. true,
  366. );
  367. expect(JSON.parse((await tool.execute(ctx, input)).text).error).toContain(
  368. "already updated the token budget during this turn",
  369. );
  370. expect(mutation.updateTokenBudget).toHaveBeenCalledTimes(2);
  371. });
  372. it.each([
  373. [
  374. { status: "complete", token_budget: 160_000 },
  375. "cannot combine status and token_budget",
  376. ],
  377. [
  378. { token_budget: 160_000 },
  379. "expected_goal_id and expected_updated_at are required",
  380. ],
  381. [
  382. {
  383. token_budget: "80K",
  384. expected_goal_id: "tg_1",
  385. expected_updated_at: 1,
  386. },
  387. "token_budget must be a positive integer or null",
  388. ],
  389. [{}, "provide either status or token_budget"],
  390. ] as const)("rejects an invalid update mode %#", async (input, error) => {
  391. const mutation = budgetMutation({
  392. updated: false,
  393. error: "must not be called",
  394. });
  395. const result = await new UpdateGoalTool(
  396. store,
  397. signalCollector(),
  398. mutation,
  399. ).execute(ctx, input as never);
  400. expect(JSON.parse(result.text).error).toContain(error);
  401. expect(mutation.updateTokenBudget).not.toHaveBeenCalled();
  402. });
  403. it("points a mode-less mixed call at the mode field", async () => {
  404. const result = await new UpdateGoalTool(store, signalCollector()).execute(
  405. ctx,
  406. {
  407. status: "complete",
  408. token_budget: 160_000,
  409. } as never,
  410. );
  411. expect(JSON.parse(result.text).error).toContain(
  412. 'set mode to "status" or "token_budget" to disambiguate',
  413. );
  414. });
  415. it("updates the budget when mode is token_budget despite terminal filler fields", async () => {
  416. // Verbatim production payload from hy-5.6-luna (a model that materializes
  417. // every schema property), plus the explicit mode it is now steered to set.
  418. const goal = await store.create({
  419. sessionId: ctx.sessionId,
  420. objective: "x",
  421. tokenBudget: 50_000,
  422. });
  423. const mutation = budgetMutation({
  424. updated: true,
  425. goal: { ...goal, tokenBudget: 100_000, updatedAt: goal.updatedAt + 1 },
  426. previousTokenBudget: 50_000,
  427. resumed: true,
  428. });
  429. const collector = signalCollector();
  430. const result = await new UpdateGoalTool(
  431. store,
  432. collector,
  433. mutation,
  434. ).execute(ctx, {
  435. mode: "token_budget",
  436. status: "complete",
  437. summary: "预算更新请求",
  438. token_budget: 100_000,
  439. expected_goal_id: goal.goalId,
  440. expected_updated_at: goal.updatedAt,
  441. });
  442. expect(JSON.parse(result.text)).toMatchObject({
  443. updated: true,
  444. previousTokenBudget: 50_000,
  445. goal: { tokenBudget: 100_000 },
  446. resumed: true,
  447. });
  448. expect(result.terminate).not.toBe(true);
  449. expect(collector.collect).not.toHaveBeenCalled();
  450. expect(mutation.updateTokenBudget).toHaveBeenCalledWith(ctx, {
  451. tokenBudget: 100_000,
  452. expectedGoalId: goal.goalId,
  453. expectedUpdatedAt: goal.updatedAt,
  454. });
  455. });
  456. it("proposes a terminal status when mode is status despite a numeric budget filler", async () => {
  457. const goal = await store.create({
  458. sessionId: ctx.sessionId,
  459. objective: "x",
  460. });
  461. const collector = signalCollector();
  462. const mutation = budgetMutation({
  463. updated: false,
  464. error: "must not be called",
  465. });
  466. const result = await new UpdateGoalTool(
  467. store,
  468. collector,
  469. mutation,
  470. ).execute(ctx, {
  471. mode: "status",
  472. status: "complete",
  473. summary: "Done.",
  474. token_budget: 100_000,
  475. expected_goal_id: goal.goalId,
  476. expected_updated_at: goal.updatedAt,
  477. });
  478. expect(JSON.parse(result.text).proposal).toMatchObject({
  479. status: "complete",
  480. summary: "Done.",
  481. accepted: true,
  482. });
  483. expect(result.terminate).toBe(true);
  484. expect(mutation.updateTokenBudget).not.toHaveBeenCalled();
  485. });
  486. it("rejects mode status without a valid terminal status value", async () => {
  487. await store.create({ sessionId: ctx.sessionId, objective: "x" });
  488. const collector = signalCollector();
  489. for (const status of [undefined, null, "paused"]) {
  490. const result = await new UpdateGoalTool(store, collector).execute(ctx, {
  491. mode: "status",
  492. status,
  493. } as never);
  494. expect(JSON.parse(result.text).error).toContain(
  495. 'status must be "complete" or "blocked"',
  496. );
  497. }
  498. expect(collector.collect).not.toHaveBeenCalled();
  499. });
  500. it("requires the get_goal CAS pair even when mode is token_budget", async () => {
  501. const result = await new UpdateGoalTool(
  502. store,
  503. signalCollector(),
  504. budgetMutation({ updated: false, error: "must not be called" }),
  505. ).execute(ctx, { mode: "token_budget", token_budget: 100_000 });
  506. expect(JSON.parse(result.text).error).toContain(
  507. "expected_goal_id and expected_updated_at are required",
  508. );
  509. });
  510. it('returns the codex-verbatim "no goal" message when the session has none', async () => {
  511. const collector = signalCollector();
  512. const tool = new UpdateGoalTool(store, collector);
  513. const result = await tool.execute(ctx, { status: "complete" });
  514. const payload = JSON.parse(result.text) as { error: string };
  515. expect(payload.error).toBe(
  516. "cannot update goal because this thread has no goal",
  517. );
  518. // A refused proposal has to reach the model as a failed tool call, not as
  519. // ordinary output that reads like a normal result.
  520. expect(result.isError).toBe(true);
  521. expect(collector.collect).not.toHaveBeenCalled();
  522. });
  523. it("marks every rejection path as a tool error and leaves the Goal untouched", async () => {
  524. await new CreateGoalTool(store).execute(ctx, { objective: "Keep me" });
  525. const before = await store.getBySession(ctx.sessionId);
  526. const patch = vi.spyOn(store, "patch");
  527. // An unbound proposal: the Turn carries no Goal binding, so the host
  528. // rejects it. Both the stale and the unbound refusals share `err()`.
  529. const stale = await new UpdateGoalTool(
  530. store,
  531. signalCollector("stale"),
  532. ).execute(ctx, {
  533. status: "complete",
  534. });
  535. const missingMode = await new UpdateGoalTool(
  536. store,
  537. signalCollector(),
  538. ).execute(ctx, {
  539. mode: "status",
  540. status: "not_a_status" as never,
  541. });
  542. expect(stale.isError).toBe(true);
  543. expect(missingMode.isError).toBe(true);
  544. expect(patch).not.toHaveBeenCalled();
  545. expect(await store.getBySession(ctx.sessionId)).toEqual(before);
  546. });
  547. it("does not mark an accepted proposal as a tool error", async () => {
  548. await new CreateGoalTool(store).execute(ctx, { objective: "x" });
  549. const result = await new UpdateGoalTool(store, signalCollector()).execute(
  550. ctx,
  551. {
  552. status: "complete",
  553. },
  554. );
  555. expect(result.isError).toBeUndefined();
  556. });
  557. it('returns the "no goal" message after the current goal was deleted', async () => {
  558. const created = await store.create({
  559. sessionId: ctx.sessionId,
  560. objective: "Gone",
  561. });
  562. await store.delete(created.goalId);
  563. const result = await new UpdateGoalTool(store, signalCollector()).execute(
  564. ctx,
  565. {
  566. status: "complete",
  567. },
  568. );
  569. const payload = JSON.parse(result.text) as { error: string };
  570. expect(payload.error).toBe(
  571. "cannot update goal because this thread has no goal",
  572. );
  573. });
  574. it.each([
  575. ["complete", "completion_proposed"],
  576. ["blocked", "block_proposed"],
  577. ] as const)(
  578. "collects an active %s proposal without mutating durable state",
  579. async (status, type) => {
  580. await new CreateGoalTool(store).execute(ctx, { objective: "x" });
  581. const collector = signalCollector();
  582. const patch = vi.spyOn(store, "patch");
  583. const result = await new UpdateGoalTool(store, collector).execute(ctx, {
  584. status,
  585. });
  586. const payload = JSON.parse(result.text) as {
  587. proposal: { status: string; accepted: boolean; settlement: string };
  588. goal: ThreadGoalState;
  589. goalSnapshotPhase: string;
  590. };
  591. expect(payload.proposal).toEqual({
  592. status,
  593. accepted: true,
  594. settlement: "pending_host_validation",
  595. });
  596. expect(payload.goal.status).toBe("active");
  597. expect(payload.goalSnapshotPhase).toBe("before_host_settlement");
  598. expect(result.terminate).toBe(true);
  599. expect(collector.collect).toHaveBeenCalledWith(ctx, {
  600. type,
  601. goalId: "tg_1",
  602. objectiveDigest: expect.stringMatching(/^[a-f0-9]{64}$/u),
  603. });
  604. expect(patch).not.toHaveBeenCalled();
  605. expect((await store.getBySession(ctx.sessionId))?.status).toBe(
  606. "active",
  607. );
  608. },
  609. );
  610. it.each([
  611. ["complete", "completion_proposed"],
  612. ["blocked", "block_proposed"],
  613. ] as const)(
  614. "treats provider-materialized token_budget null as an active %s proposal",
  615. async (status, type) => {
  616. const goal = await store.create({
  617. sessionId: ctx.sessionId,
  618. objective: "x",
  619. });
  620. const collector = signalCollector();
  621. const mutation = budgetMutation({
  622. updated: false,
  623. error: "must not be called",
  624. });
  625. const result = await new UpdateGoalTool(
  626. store,
  627. collector,
  628. mutation,
  629. ).execute(ctx, {
  630. status,
  631. summary: "The Goal is terminal.",
  632. token_budget: null,
  633. expected_goal_id: goal.goalId,
  634. expected_updated_at: goal.updatedAt,
  635. });
  636. expect(JSON.parse(result.text).proposal).toMatchObject({
  637. status,
  638. summary: "The Goal is terminal.",
  639. accepted: true,
  640. settlement: "pending_host_validation",
  641. });
  642. expect(result.terminate).toBe(true);
  643. expect(collector.collect).toHaveBeenCalledWith(ctx, {
  644. type,
  645. goalId: goal.goalId,
  646. objectiveDigest: expect.stringMatching(/^[a-f0-9]{64}$/u),
  647. summary: "The Goal is terminal.",
  648. });
  649. expect(mutation.updateTokenBudget).not.toHaveBeenCalled();
  650. },
  651. );
  652. it("terminates a proposal rejected by the host as an invalidated Turn", async () => {
  653. await new CreateGoalTool(store).execute(ctx, {
  654. objective: "Updated objective",
  655. });
  656. const collector = signalCollector("stale");
  657. const patch = vi.spyOn(store, "patch");
  658. const result = await new UpdateGoalTool(store, collector).execute(ctx, {
  659. status: "complete",
  660. });
  661. const payload = JSON.parse(result.text) as {
  662. error: string;
  663. currentGoal: ThreadGoalState;
  664. };
  665. expect(payload.error).toContain("objective changed during this turn");
  666. expect(payload.currentGoal).toMatchObject({
  667. objective: "Updated objective",
  668. status: "active",
  669. });
  670. expect(result.terminate).toBe(true);
  671. expect(collector.collect).toHaveBeenCalledWith(
  672. ctx,
  673. expect.objectContaining({
  674. type: "completion_proposed",
  675. goalId: "tg_1",
  676. }),
  677. );
  678. expect(patch).not.toHaveBeenCalled();
  679. });
  680. it("passes a trimmed completion summary through the turn-local proposal only", async () => {
  681. await new CreateGoalTool(store).execute(ctx, { objective: "x" });
  682. const collector = signalCollector();
  683. const result = await new UpdateGoalTool(store, collector).execute(ctx, {
  684. status: "complete",
  685. summary: " Changed verifier.ts and ran its focused test. ",
  686. });
  687. expect(JSON.parse(result.text).proposal).toEqual({
  688. status: "complete",
  689. summary: "Changed verifier.ts and ran its focused test.",
  690. accepted: true,
  691. settlement: "pending_host_validation",
  692. });
  693. expect(collector.collect).toHaveBeenCalledWith(ctx, {
  694. type: "completion_proposed",
  695. goalId: "tg_1",
  696. objectiveDigest: expect.stringMatching(/^[a-f0-9]{64}$/u),
  697. summary: "Changed verifier.ts and ran its focused test.",
  698. });
  699. });
  700. it.each(["complete", "blocked"] as const)(
  701. "rejects changing a PAUSED goal to %s and preserves the user pause",
  702. async (status) => {
  703. const collector = signalCollector();
  704. await new CreateGoalTool(store).execute(ctx, { objective: "x" });
  705. const goal = await store.getBySession(ctx.sessionId);
  706. await store.patch(goal!.goalId, { status: "paused" });
  707. const result = await new UpdateGoalTool(store, collector).execute(ctx, {
  708. status,
  709. });
  710. const payload = JSON.parse(result.text) as {
  711. error: string;
  712. currentStatus: string;
  713. };
  714. expect(payload.error).toBe(
  715. "cannot update goal because it is paused; resume the goal before completing or blocking it",
  716. );
  717. expect(payload.currentStatus).toBe("paused");
  718. expect((await store.getBySession(ctx.sessionId))?.status).toBe(
  719. "paused",
  720. );
  721. expect(collector.collect).not.toHaveBeenCalled();
  722. },
  723. );
  724. it.each([
  725. [
  726. "no_goal",
  727. "cannot update goal because this thread has no goal",
  728. undefined,
  729. ],
  730. [
  731. "paused",
  732. "cannot update goal because it is paused; resume the goal before completing or blocking it",
  733. "paused",
  734. ],
  735. ] as const)(
  736. "maps a collector %s race to the existing rejection",
  737. async (result, error, currentStatus) => {
  738. await new CreateGoalTool(store).execute(ctx, { objective: "x" });
  739. const response = await new UpdateGoalTool(
  740. store,
  741. signalCollector(result),
  742. ).execute(ctx, {
  743. status: "complete",
  744. });
  745. const payload = JSON.parse(response.text) as {
  746. error: string;
  747. currentStatus?: string;
  748. };
  749. expect(payload.error).toBe(error);
  750. expect(payload.currentStatus).toBe(currentStatus);
  751. expect((await store.getBySession(ctx.sessionId))?.status).toBe(
  752. "active",
  753. );
  754. },
  755. );
  756. });
  757. describe("GetGoalTool", () => {
  758. it("returns goal:null when none exists", async () => {
  759. const result = await new GetGoalTool(store).execute(ctx, {});
  760. const payload = JSON.parse(result.text) as { goal: unknown };
  761. expect(payload.goal).toBeNull();
  762. });
  763. it("returns the serialized goal record when set", async () => {
  764. await new CreateGoalTool(store).execute(ctx, { objective: "See me" });
  765. const result = await new GetGoalTool(store).execute(ctx, {});
  766. const payload = JSON.parse(result.text) as { goal: ThreadGoalState };
  767. expect(payload.goal.objective).toBe("See me");
  768. expect(payload.goal.status).toBe("active");
  769. });
  770. it.each([
  771. "active",
  772. "paused",
  773. "blocked",
  774. "complete",
  775. "budget_limited",
  776. ] as const)(
  777. "returns status information when the current goal is %s",
  778. async (status) => {
  779. const created = await store.create({
  780. sessionId: ctx.sessionId,
  781. objective: "Status check",
  782. });
  783. if (status !== "active") {
  784. await store.patch(created.goalId, { status });
  785. }
  786. const result = await new GetGoalTool(store).execute(ctx, {});
  787. const payload = JSON.parse(result.text) as { goal: ThreadGoalState };
  788. expect(payload.goal.status).toBe(status);
  789. },
  790. );
  791. });
  792. });