1
0

contract-hygiene.test.ts 9.3 KB

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