contract-hygiene.test.ts 9.8 KB

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