contract-hygiene.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import { describe, expect, test } from "bun:test"
  2. import { DateTime, Schema } from "effect"
  3. import { Agent } from "../src/agent.js"
  4. import { FileSystem } from "../src/filesystem.js"
  5. import { Form } from "../src/form.js"
  6. import { Mcp } from "../src/mcp.js"
  7. import { Model } from "../src/model.js"
  8. import { Project } from "../src/project.js"
  9. import { Provider } from "../src/provider.js"
  10. import { Pty } from "../src/pty.js"
  11. import { Question } from "../src/question.js"
  12. import { Session } from "../src/session.js"
  13. import { SessionMessage } from "../src/session-message.js"
  14. import { SessionPending } from "../src/session-pending.js"
  15. import { FileDiff } from "../src/file-diff.js"
  16. import { Money } from "../src/money.js"
  17. import { Skill } from "../src/skill.js"
  18. import { Shell } from "../src/shell.js"
  19. import { PersistedRevert } from "../src/session-revert.js"
  20. import { optional } from "../src/schema.js"
  21. describe("contract hygiene", () => {
  22. test("keeps absolute costs distinct from model rates", () => {
  23. const usd = Money.USD.make(1)
  24. const rate = Money.USDPerMillionTokens.make(1)
  25. // @ts-expect-error Model rates are not absolute costs.
  26. const invalidUSD: Money.USD = rate
  27. // @ts-expect-error Absolute costs are not model rates.
  28. const invalidRate: Money.USDPerMillionTokens = usd
  29. expect(invalidUSD).toBe(Money.USD.make(1))
  30. expect(invalidRate).toBe(Money.USDPerMillionTokens.make(1))
  31. expect(Money.USD.zero).toBe(Money.USD.make(0))
  32. expect(Money.USDPerMillionTokens.zero).toBe(Money.USDPerMillionTokens.make(0))
  33. })
  34. test("optional properties preserve transformations and omit undefined while encoding", () => {
  35. const Value = Schema.Struct({ value: optional(Schema.FiniteFromString) })
  36. expect(Schema.decodeUnknownSync(Value)({ value: "1" })).toEqual({ value: 1 })
  37. expect(Schema.encodeSync(Value)({ value: 1 })).toEqual({ value: "1" })
  38. expect(Schema.encodeSync(Value)({ value: undefined })).toEqual({})
  39. expect(
  40. Schema.encodeSync(SessionPending.SyntheticData)({
  41. text: "completed",
  42. description: undefined,
  43. metadata: undefined,
  44. }),
  45. ).toEqual({ text: "completed" })
  46. })
  47. test("forms require at least one field", () => {
  48. expect(() =>
  49. Schema.decodeUnknownSync(Form.Info)({
  50. id: Form.ID.create(),
  51. sessionID: "global",
  52. title: "Empty form",
  53. fields: [],
  54. }),
  55. ).toThrow()
  56. expect(
  57. Schema.decodeUnknownSync(Form.Info)({
  58. id: Form.ID.create(),
  59. sessionID: "global",
  60. title: "External form",
  61. fields: [{ key: "authorization", type: "external", url: "https://example.com" }],
  62. }).fields,
  63. ).toHaveLength(1)
  64. expect(() =>
  65. Schema.decodeUnknownSync(Form.Info)({
  66. id: Form.ID.create(),
  67. sessionID: "global",
  68. title: "External form",
  69. fields: [{ type: "external", url: "https://example.com" }],
  70. }),
  71. ).toThrow()
  72. })
  73. test("model defaults and provider overlays preserve public invariants", () => {
  74. const id = Model.ID.make("model")
  75. expect(Model.Info.empty(Provider.ID.make("provider"), id)).toMatchObject({ modelID: id, variants: [] })
  76. expect(() =>
  77. Schema.decodeUnknownSync(Provider.Info)({
  78. id: "provider",
  79. name: "Provider",
  80. package: "native",
  81. settings: { invalid: 1n },
  82. }),
  83. ).toThrow()
  84. })
  85. test("current ID constructors expose create", () => {
  86. expect(Question.ID.create()).toStartWith("que_")
  87. expect(Pty.ID.create()).toStartWith("pty_")
  88. })
  89. test("reusable public identifiers are stable and unique", () => {
  90. const identifiers = [
  91. Agent.Color,
  92. FileSystem.Submatch,
  93. Form.Field,
  94. Form.Fields,
  95. Form.Info,
  96. Form.ExternalField,
  97. Mcp.Resource,
  98. Mcp.ResourceTemplate,
  99. Mcp.ResourceCatalog,
  100. Mcp.ResourceContentPart,
  101. Mcp.ResourceContent,
  102. Model.Ref,
  103. Model.Capabilities,
  104. Model.Cost,
  105. Model.Variant,
  106. Project.Current,
  107. Project.Directory,
  108. Project.DirectoriesInput,
  109. Project.Directories,
  110. Project.Icon,
  111. Project.Commands,
  112. Project.Time,
  113. Project.Info,
  114. Pty.Info,
  115. Session.ListAnchor,
  116. Session.Revert,
  117. SessionPending.UserData,
  118. SessionPending.SyntheticData,
  119. SessionPending.User,
  120. SessionPending.Synthetic,
  121. ].map((schema) => schema.ast.annotations?.identifier)
  122. expect(identifiers.every((identifier) => typeof identifier === "string")).toBe(true)
  123. expect(new Set(identifiers).size).toBe(identifiers.length)
  124. })
  125. test("current source avoids Any and mutable contract wrappers", async () => {
  126. const files = [...new Bun.Glob("*.ts").scanSync(new URL("../src", import.meta.url).pathname)].filter(
  127. (file) => !file.endsWith("-v1.ts"),
  128. )
  129. const source = await Promise.all(
  130. files.map((file) => Bun.file(new URL(`../src/${file}`, import.meta.url)).text()),
  131. ).then((values) => values.join("\n"))
  132. expect(source).not.toContain("Schema.Any")
  133. expect(source).not.toContain("Schema.mutable")
  134. })
  135. test("assistant content keeps only domain identities", () => {
  136. expect(SessionMessage.AssistantText.make({ type: "text", text: "hello" })).toEqual({
  137. type: "text",
  138. text: "hello",
  139. })
  140. expect(
  141. SessionMessage.AssistantReasoning.make({ type: "reasoning", text: "thinking", state: { id: "opaque" } }),
  142. ).toEqual({ type: "reasoning", text: "thinking", state: { id: "opaque" } })
  143. expect(
  144. SessionMessage.AssistantTool.make({
  145. type: "tool",
  146. id: "call_1",
  147. name: "search",
  148. executed: true,
  149. providerState: { itemId: "item_1" },
  150. state: { status: "streaming", input: "" },
  151. time: { created: DateTime.makeUnsafe(0) },
  152. }),
  153. ).not.toHaveProperty("provider")
  154. })
  155. test("reviewed session contracts use their canonical current shapes", () => {
  156. expect(SessionMessage.Info.ast.annotations?.identifier).toBe("Session.Message.Info")
  157. expect(SessionPending.Info.ast.annotations?.identifier).toBe("SessionPending.Info")
  158. expect(Money.USD).not.toBe(Money.USDPerMillionTokens)
  159. expect(
  160. FileDiff.Info.make({ file: "src/index.ts", patch: "@@", additions: 1, deletions: 0, status: "modified" }),
  161. ).toEqual({ file: "src/index.ts", patch: "@@", additions: 1, deletions: 0, status: "modified" })
  162. expect(
  163. SessionMessage.Shell.make({
  164. id: SessionMessage.ID.make("msg_shell"),
  165. type: "shell",
  166. shellID: Shell.ID.make("sh_test"),
  167. command: "pwd",
  168. status: "exited",
  169. exit: 0,
  170. time: { created: DateTime.makeUnsafe(0) },
  171. }),
  172. ).not.toHaveProperty("shell")
  173. expect(
  174. SessionMessage.Skill.make({
  175. id: SessionMessage.ID.make("msg_skill"),
  176. type: "skill",
  177. skill: Skill.ID.make("effect"),
  178. name: Skill.Name.make("Effect"),
  179. text: "Use Effect",
  180. time: { created: DateTime.makeUnsafe(0) },
  181. }),
  182. ).toMatchObject({ skill: "effect", name: "Effect" })
  183. expect(
  184. SessionMessage.CompactionFailed.make({
  185. id: SessionMessage.ID.make("msg_compaction"),
  186. type: "compaction",
  187. status: "failed",
  188. reason: "manual",
  189. error: { type: "compaction.failed", message: "failed" },
  190. time: { created: DateTime.makeUnsafe(0) },
  191. }),
  192. ).not.toHaveProperty("summary")
  193. })
  194. test("keeps shared persisted revert compatibility", () => {
  195. expect(
  196. Schema.decodeUnknownSync(Session.Revert)({
  197. messageID: "msg_legacy",
  198. snapshot: "tree",
  199. diff: "legacy patch",
  200. }),
  201. ).not.toHaveProperty("diff")
  202. const revert = Schema.decodeUnknownSync(PersistedRevert)({
  203. messageID: "msg_legacy",
  204. snapshot: "tree",
  205. diff: "legacy patch",
  206. files: [{ path: "src/index.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" }],
  207. })
  208. expect(String(revert.messageID)).toBe("msg_legacy")
  209. expect(String(revert.snapshot)).toBe("tree")
  210. expect(revert.files).toEqual([
  211. { file: "src/index.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" },
  212. ])
  213. expect(Schema.encodeSync(PersistedRevert)(revert)).toEqual({
  214. messageID: "msg_legacy",
  215. snapshot: "tree",
  216. files: [{ file: "src/index.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" }],
  217. })
  218. })
  219. })