contract.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import { describe, it, expect } from "vitest";
  2. import {
  3. ThreadGoalAlreadyExistsError,
  4. ThreadGoalBudgetLimitedError,
  5. type ThreadGoalState,
  6. } from "@mavis/goal";
  7. import {
  8. ThreadGoalContractError,
  9. createGoalReqToCreateInput,
  10. goalStateToGoalState,
  11. patchGoalReqToPatchInput,
  12. toThreadGoalContractError,
  13. } from "../../../src/thread-goal/contract.js";
  14. /**
  15. * Pure mapping coverage for the IDL goal contract glue — no HTTP, no store.
  16. * Mirrors `cron/contract` testing: validates the snake↔camel / tri-state /
  17. * error-derivation logic in isolation so the DesktopService methods and the
  18. * request-level test can both rely on it.
  19. */
  20. const STATE: ThreadGoalState = {
  21. goalId: "tg_1",
  22. sessionId: "sess_1",
  23. objective: "ship the migration",
  24. status: "active",
  25. createdAt: 1_700_000_000_000,
  26. updatedAt: 1_700_000_000_001,
  27. tokensUsed: 1234,
  28. turnsUsed: 3,
  29. timeUsedSeconds: 42,
  30. tokenBudget: 50_000,
  31. replyFingerprint: "abc123",
  32. noProgressStreak: 1,
  33. noToolStreak: 0,
  34. lastVerification: {
  35. v: 1,
  36. backend: "evaluator",
  37. verdict: "not_met",
  38. reason: "Tests are still missing",
  39. missing: ["focused test"],
  40. notMetStreak: 1,
  41. turnId: "turn_1",
  42. objectiveDigest: "digest",
  43. at: 1_700_000_000_000,
  44. },
  45. lastWorkerProposal: {
  46. v: 1,
  47. source: "worker",
  48. type: "blocked",
  49. turnId: "turn_1",
  50. summary: "private blocker detail",
  51. at: 1_700_000_000_001,
  52. },
  53. statusReason: null,
  54. kickoffAttachments: [],
  55. kickoffState: "consumed",
  56. executionWait: null,
  57. };
  58. describe("goalStateToGoalState", () => {
  59. it("maps the full record identity-style", () => {
  60. const projected = goalStateToGoalState(STATE);
  61. expect(projected).toEqual({
  62. goalId: "tg_1",
  63. sessionId: "sess_1",
  64. objective: "ship the migration",
  65. objectiveResources: [],
  66. status: "active",
  67. createdAt: 1_700_000_000_000,
  68. updatedAt: 1_700_000_000_001,
  69. tokensUsed: 1234,
  70. turnsUsed: 3,
  71. timeUsedSeconds: 42,
  72. tokenBudget: 50_000,
  73. lastVerification: {
  74. backend: "evaluator",
  75. verdict: "not_met",
  76. reason: "Tests are still missing",
  77. missing: ["focused test"],
  78. notMetStreak: 1,
  79. at: 1_700_000_000_000,
  80. },
  81. hasKickoffAttachments: false,
  82. });
  83. expect(JSON.stringify(projected)).not.toContain("private blocker detail");
  84. });
  85. it("projects Goal-owned kickoff attachment presence without exposing local paths", () => {
  86. expect(
  87. goalStateToGoalState({
  88. ...STATE,
  89. kickoffAttachments: [
  90. {
  91. type: "file",
  92. filePath: "/tmp/private/brief.pdf",
  93. fileName: "brief.pdf",
  94. mimeType: "application/pdf",
  95. },
  96. ],
  97. }),
  98. ).toMatchObject({ hasKickoffAttachments: true });
  99. });
  100. it("omits tokenBudget when the cap is null (uncapped → absent on wire)", () => {
  101. const out = goalStateToGoalState({ ...STATE, tokenBudget: null });
  102. expect("tokenBudget" in out).toBe(false);
  103. });
  104. it("projects the execution wait without changing the Goal decision epoch", () => {
  105. expect(
  106. goalStateToGoalState({
  107. ...STATE,
  108. executionWait: {
  109. reason: "required_background",
  110. sinceMs: 1_700_000_000_500,
  111. },
  112. }),
  113. ).toMatchObject({
  114. updatedAt: STATE.updatedAt,
  115. execution: {
  116. waitReason: "required_background",
  117. waitSince: 1_700_000_000_500,
  118. },
  119. });
  120. });
  121. });
  122. describe("createGoalReqToCreateInput", () => {
  123. it("trims objective and passes a positive token budget through", () => {
  124. expect(
  125. createGoalReqToCreateInput({
  126. sessionId: "sess_1",
  127. objective: " do the thing ",
  128. tokenBudget: 1000,
  129. }),
  130. ).toEqual({
  131. sessionId: "sess_1",
  132. objective: "do the thing",
  133. tokenBudget: 1000,
  134. });
  135. });
  136. it("maps usable wire attachments into the Goal-owned kickoff snapshot", () => {
  137. expect(
  138. createGoalReqToCreateInput({
  139. sessionId: "sess_1",
  140. objective: "Read the brief",
  141. attachments: [
  142. {
  143. meta: {
  144. attachmentType: "file",
  145. fileName: "brief.pdf",
  146. mimeType: "application/pdf",
  147. },
  148. local: {
  149. filePath: "/tmp/brief.pdf",
  150. assetId: "asset-1",
  151. },
  152. },
  153. ],
  154. }),
  155. ).toMatchObject({
  156. kickoffAttachments: [
  157. {
  158. type: "file",
  159. filePath: "/tmp/brief.pdf",
  160. fileName: "brief.pdf",
  161. mimeType: "application/pdf",
  162. assetId: "asset-1",
  163. },
  164. ],
  165. });
  166. });
  167. it("keeps a local data URL without copying the shared cloud payload", () => {
  168. expect(
  169. createGoalReqToCreateInput({
  170. sessionId: "sess_1",
  171. objective: "Inspect the image",
  172. attachments: [
  173. {
  174. meta: {
  175. attachmentType: "image",
  176. fileName: "inline.png",
  177. mimeType: "image/png",
  178. },
  179. local: { dataUrl: "data:image/png;base64,AA==" },
  180. cloud: { dataUrl: "data:image/png;base64,CLOUD" },
  181. },
  182. ],
  183. }),
  184. ).toMatchObject({
  185. kickoffAttachments: [
  186. {
  187. type: "image",
  188. filePath: "",
  189. fileName: "inline.png",
  190. mimeType: "image/png",
  191. dataUrl: "data:image/png;base64,AA==",
  192. },
  193. ],
  194. });
  195. });
  196. it("clears a display-only attachment path so its inline preview is persisted", () => {
  197. expect(
  198. createGoalReqToCreateInput({
  199. sessionId: "sess_1",
  200. objective: "Inspect the annotation",
  201. attachments: [
  202. {
  203. meta: {
  204. attachmentType: "image",
  205. fileName: "inline-comment-preview.png",
  206. mimeType: "image/png",
  207. },
  208. local: {
  209. filePath: "inline-comment-preview.png",
  210. dataUrl: "data:image/png;base64,AA==",
  211. },
  212. },
  213. ],
  214. }),
  215. ).toMatchObject({
  216. kickoffAttachments: [
  217. {
  218. type: "image",
  219. filePath: "",
  220. fileName: "inline-comment-preview.png",
  221. mimeType: "image/png",
  222. dataUrl: "data:image/png;base64,AA==",
  223. },
  224. ],
  225. });
  226. });
  227. it("prefers a real desktop path over an inline display path", () => {
  228. expect(
  229. createGoalReqToCreateInput({
  230. sessionId: "sess_1",
  231. objective: "Inspect the local image",
  232. attachments: [
  233. {
  234. meta: {
  235. attachmentType: "image",
  236. fileName: "photo.png",
  237. mimeType: "image/png",
  238. },
  239. local: {
  240. filePath: "photo.png",
  241. desktopPath: "C:\\Users\\Mira\\Pictures\\photo.png",
  242. dataUrl: "data:image/png;base64,AA==",
  243. },
  244. },
  245. ],
  246. }),
  247. ).toMatchObject({
  248. kickoffAttachments: [
  249. {
  250. filePath: "C:\\Users\\Mira\\Pictures\\photo.png",
  251. dataUrl: "data:image/png;base64,AA==",
  252. },
  253. ],
  254. });
  255. });
  256. it("keeps a registered asset path ahead of a desktop fallback", () => {
  257. expect(
  258. createGoalReqToCreateInput({
  259. sessionId: "sess_1",
  260. objective: "Inspect the durable asset",
  261. attachments: [
  262. {
  263. meta: {
  264. attachmentType: "file",
  265. fileName: "brief.pdf",
  266. mimeType: "application/pdf",
  267. },
  268. local: {
  269. assetId: "asset-1",
  270. filePath: "/assets/asset-1/brief.pdf",
  271. desktopPath: "/tmp/brief.pdf",
  272. dataUrl: "data:application/pdf;base64,AA==",
  273. },
  274. },
  275. ],
  276. }),
  277. ).toMatchObject({
  278. kickoffAttachments: [
  279. {
  280. assetId: "asset-1",
  281. filePath: "/assets/asset-1/brief.pdf",
  282. },
  283. ],
  284. });
  285. });
  286. it("ignores a cloud-only attachment in the local runtime Goal contract", () => {
  287. expect(
  288. createGoalReqToCreateInput({
  289. sessionId: "sess_1",
  290. objective: "Inspect the image",
  291. attachments: [
  292. {
  293. meta: {
  294. attachmentType: "image",
  295. fileName: "cloud-only.png",
  296. mimeType: "image/png",
  297. },
  298. cloud: { dataUrl: "data:image/png;base64,CLOUD" },
  299. },
  300. ],
  301. }),
  302. ).toEqual({
  303. sessionId: "sess_1",
  304. objective: "Inspect the image",
  305. });
  306. });
  307. it('treats tokenBudget 0 / omitted as "no cap" (field absent)', () => {
  308. expect(
  309. createGoalReqToCreateInput({
  310. sessionId: "sess_1",
  311. objective: "x",
  312. tokenBudget: 0,
  313. }),
  314. ).toEqual({ sessionId: "sess_1", objective: "x" });
  315. expect(
  316. createGoalReqToCreateInput({ sessionId: "sess_1", objective: "x" }),
  317. ).toEqual({
  318. sessionId: "sess_1",
  319. objective: "x",
  320. });
  321. });
  322. it("does not impose an objective length limit by default", () => {
  323. const objective = "x".repeat(4_001);
  324. expect(
  325. createGoalReqToCreateInput({ sessionId: "sess_1", objective }),
  326. ).toMatchObject({
  327. objective,
  328. });
  329. });
  330. it("rejects objectives longer than an explicitly configured bound without truncating", () => {
  331. const objective = "x".repeat(4_001);
  332. expect(() =>
  333. createGoalReqToCreateInput(
  334. { sessionId: "sess_1", objective },
  335. { objectiveMaxChars: 4_000 },
  336. ),
  337. ).toThrow(expect.objectContaining({ code: "GOAL_OBJECTIVE_TOO_LONG" }));
  338. });
  339. it("rejects an empty objective with a 400 contract error", () => {
  340. expect(() =>
  341. createGoalReqToCreateInput({ sessionId: "sess_1", objective: " " }),
  342. ).toThrow(ThreadGoalContractError);
  343. try {
  344. createGoalReqToCreateInput({ sessionId: "sess_1", objective: "" });
  345. } catch (e) {
  346. expect((e as ThreadGoalContractError).status).toBe(400);
  347. }
  348. });
  349. it("rejects a blank session_id with a 400", () => {
  350. expect(() =>
  351. createGoalReqToCreateInput({ sessionId: " ", objective: "x" }),
  352. ).toThrow(/session_id is required/);
  353. });
  354. });
  355. describe("patchGoalReqToPatchInput tri-state token_budget", () => {
  356. it("omitted → field absent (leave the cap alone)", () => {
  357. const { patch, hasChange } = patchGoalReqToPatchInput({
  358. sessionId: "s",
  359. status: "paused",
  360. });
  361. expect("tokenBudget" in patch).toBe(false);
  362. expect(patch.status).toBe("paused");
  363. expect(hasChange).toBe(true);
  364. });
  365. it("never invents a statusReason the wire request does not carry", () => {
  366. // `PatchGoalReq` has no status_reason field. A translator that derives one
  367. // is writing domain state it does not own, and that invented field is what
  368. // previously diverted every wire pause away from the atomic pause path.
  369. for (const status of ["paused", "complete", "active"] as const) {
  370. const { patch } = patchGoalReqToPatchInput({ sessionId: "s", status });
  371. expect("statusReason" in patch).toBe(false);
  372. }
  373. });
  374. it("reports a bare pause as the user-pause intent", () => {
  375. expect(
  376. patchGoalReqToPatchInput({ sessionId: "s", status: "paused" })
  377. .isUserPause,
  378. ).toBe(true);
  379. });
  380. it("does not treat a pause bundled with an edit as a bare user pause", () => {
  381. expect(
  382. patchGoalReqToPatchInput({
  383. sessionId: "s",
  384. status: "paused",
  385. objective: "new objective",
  386. }).isUserPause,
  387. ).toBe(false);
  388. expect(
  389. patchGoalReqToPatchInput({
  390. sessionId: "s",
  391. status: "paused",
  392. tokenBudget: 42,
  393. }).isUserPause,
  394. ).toBe(false);
  395. expect(
  396. patchGoalReqToPatchInput({ sessionId: "s", status: "complete" })
  397. .isUserPause,
  398. ).toBe(false);
  399. });
  400. it("0 → null (clear the cap)", () => {
  401. const { patch } = patchGoalReqToPatchInput({
  402. sessionId: "s",
  403. tokenBudget: 0,
  404. });
  405. expect(patch.tokenBudget).toBeNull();
  406. });
  407. it("positive → set the cap", () => {
  408. const { patch } = patchGoalReqToPatchInput({
  409. sessionId: "s",
  410. tokenBudget: 99_000,
  411. });
  412. expect(patch.tokenBudget).toBe(99_000);
  413. });
  414. it("reports hasChange=false for an empty patch", () => {
  415. const { hasChange } = patchGoalReqToPatchInput({ sessionId: "s" });
  416. expect(hasChange).toBe(false);
  417. });
  418. it("rejects an invalid status enum with a 400", () => {
  419. expect(() =>
  420. patchGoalReqToPatchInput({ sessionId: "s", status: "bogus" }),
  421. ).toThrow(ThreadGoalContractError);
  422. });
  423. it("accepts every closed status value before store-level transition checks", () => {
  424. for (const status of [
  425. "active",
  426. "paused",
  427. "blocked",
  428. "complete",
  429. "budget_limited",
  430. "usage_limited",
  431. ]) {
  432. const { patch } = patchGoalReqToPatchInput({ sessionId: "s", status });
  433. expect(patch.status).toBe(status);
  434. }
  435. });
  436. });
  437. describe("toThreadGoalContractError", () => {
  438. it("maps ThreadGoalAlreadyExistsError → 409 GOAL_EXISTS", () => {
  439. const mapped = toThreadGoalContractError(
  440. new ThreadGoalAlreadyExistsError("tg_old"),
  441. );
  442. expect(mapped.status).toBe(409);
  443. expect(mapped.code).toBe("GOAL_EXISTS");
  444. });
  445. it("maps a budget state conflict to a typed 409 response", () => {
  446. expect(
  447. toThreadGoalContractError(new ThreadGoalBudgetLimitedError("tg_1")),
  448. ).toMatchObject({
  449. status: 409,
  450. code: "GOAL_BUDGET_LIMITED",
  451. });
  452. });
  453. it('maps a "not found" message → 404', () => {
  454. expect(toThreadGoalContractError(new Error("goal not found")).status).toBe(
  455. 404,
  456. );
  457. });
  458. it("passes a ThreadGoalContractError through unchanged", () => {
  459. const err = new ThreadGoalContractError(400, "bad", "VALIDATION_ERROR");
  460. expect(toThreadGoalContractError(err)).toBe(err);
  461. });
  462. it("maps an admitted attachment size failure without exposing the original error", () => {
  463. const mapped = toThreadGoalContractError(
  464. Object.assign(new Error("asset_too_large"), {
  465. status: 413,
  466. key: "local_attachment_too_large",
  467. }),
  468. );
  469. expect(mapped).toMatchObject({
  470. status: 413,
  471. code: "local_attachment_too_large",
  472. message: "Local attachment is too large to persist",
  473. });
  474. });
  475. it("maps filesystem read failures to a sanitized attachment error", () => {
  476. const mapped = toThreadGoalContractError(
  477. Object.assign(new Error("ENOENT: stat 'C:\\Users\\Mira\\private.png'"), {
  478. code: "ENOENT",
  479. }),
  480. );
  481. expect(mapped).toMatchObject({
  482. status: 415,
  483. code: "local_attachment_unreadable",
  484. message: "Local attachment source is unreadable or invalid",
  485. });
  486. expect(mapped.message).not.toContain("Mira");
  487. });
  488. it("maps the materializer attachment error contract to a stable Goal response", () => {
  489. const mapped = toThreadGoalContractError(
  490. Object.assign(
  491. new Error("Local attachment source is unreadable or invalid"),
  492. {
  493. name: "AttachmentRegistrationError",
  494. reason: "unreadable",
  495. },
  496. ),
  497. );
  498. expect(mapped).toMatchObject({
  499. status: 415,
  500. code: "local_attachment_unreadable",
  501. message: "Local attachment source is unreadable or invalid",
  502. });
  503. });
  504. it("falls back to 500 for an unknown error", () => {
  505. expect(toThreadGoalContractError(new Error("boom")).status).toBe(500);
  506. });
  507. });