contract-hygiene.test.ts 10 KB

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