contract-hygiene.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 { Session } from "../src/session.js"
  12. import { SessionMessage } from "../src/session-message.js"
  13. import { SessionInbox } from "../src/session-inbox.js"
  14. import { FileDiff } from "../src/file-diff.js"
  15. import { Money } from "../src/money.js"
  16. import { Skill } from "../src/skill.js"
  17. import { Shell } from "../src/shell.js"
  18. import { Vcs } from "../src/vcs.js"
  19. import { Worktree } from "../src/worktree.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(SessionInbox.SyntheticPayload)({
  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("session inbox items omit the internal enqueue sequence", () => {
  65. expect(
  66. Schema.encodeSync(SessionInbox.Info)(
  67. Schema.decodeUnknownSync(SessionInbox.Info)({
  68. admittedSeq: 3,
  69. id: "msg_pending",
  70. sessionID: "ses_pending",
  71. timeCreated: 1,
  72. type: "user",
  73. payload: { text: "hello" },
  74. delivery: "steer",
  75. }),
  76. ),
  77. ).toEqual({
  78. id: "msg_pending",
  79. sessionID: "ses_pending",
  80. timeCreated: 1,
  81. type: "user",
  82. payload: { 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(Provider.Info.empty(Provider.ID.make("provider")).activation).toBe("auto")
  116. expect(
  117. Schema.decodeUnknownSync(Provider.Info)({
  118. id: "provider",
  119. name: "Provider",
  120. activation: "auto",
  121. package: "native",
  122. settings: { arbitrary: 1n },
  123. }).settings,
  124. ).toEqual({ arbitrary: 1n })
  125. })
  126. test("current ID constructors expose create", () => {
  127. expect(Form.ID.create()).toStartWith("frm_")
  128. expect(Pty.ID.create()).toStartWith("pty_")
  129. })
  130. test("VCS info omits unavailable branch names", () => {
  131. expect(Schema.encodeSync(Vcs.Info)({ branch: { current: undefined, default: undefined } })).toEqual({ branch: {} })
  132. })
  133. test("reusable public identifiers are stable and unique", () => {
  134. const identifiers = [
  135. Agent.Color,
  136. FileSystem.Submatch,
  137. Form.Field,
  138. Form.Fields,
  139. Form.Info,
  140. Form.ExternalField,
  141. Mcp.Resource,
  142. Mcp.ResourceTemplate,
  143. Mcp.ResourceCatalog,
  144. Mcp.ResourceContentPart,
  145. Mcp.ResourceContent,
  146. Model.Ref,
  147. Model.Capabilities,
  148. Model.Cost,
  149. Model.Variant,
  150. Project.Current,
  151. Worktree.Directory,
  152. Worktree.ListInput,
  153. Worktree.List,
  154. Project.Icon,
  155. Project.Commands,
  156. Project.Time,
  157. Project.Info,
  158. Pty.Info,
  159. Session.ListAnchor,
  160. Session.Revert,
  161. SessionInbox.Delivery,
  162. SessionInbox.UserPayload,
  163. SessionInbox.SyntheticPayload,
  164. SessionInbox.CompactionPayload,
  165. SessionInbox.MovePayload,
  166. SessionInbox.Item,
  167. SessionInbox.User,
  168. SessionInbox.Synthetic,
  169. SessionInbox.Compaction,
  170. SessionInbox.Move,
  171. SessionInbox.Info,
  172. Vcs.Branch,
  173. Vcs.Info,
  174. ].map((schema) => schema.ast.annotations?.identifier)
  175. expect(identifiers.every((identifier) => typeof identifier === "string")).toBe(true)
  176. expect(new Set(identifiers).size).toBe(identifiers.length)
  177. })
  178. test("all session inbox item types accept both delivery modes", () => {
  179. const decode = Schema.decodeUnknownSync(SessionInbox.Info)
  180. const base = { id: "msg_inbox", sessionID: "ses_inbox", timeCreated: 1 }
  181. const move = {
  182. location: { directory: "/project" },
  183. projectID: "global",
  184. }
  185. for (const delivery of ["steer", "queue"] as const) {
  186. expect(decode({ ...base, type: "user", payload: { text: "hello" }, delivery }).delivery).toBe(delivery)
  187. expect(decode({ ...base, type: "synthetic", payload: { text: "context" }, delivery }).delivery).toBe(delivery)
  188. expect(decode({ ...base, type: "compaction", payload: {}, delivery }).delivery).toBe(delivery)
  189. expect(decode({ ...base, type: "move", payload: move, delivery }).delivery).toBe(delivery)
  190. }
  191. })
  192. test("current source limits Any to provider options and avoids mutable contract wrappers", async () => {
  193. const files = [...new Bun.Glob("*.ts").scanSync(new URL("../src", import.meta.url).pathname)].filter(
  194. (file) => !file.endsWith("-v1.ts"),
  195. )
  196. const sources = await Promise.all(
  197. files.map(async (file) => ({ file, source: await Bun.file(new URL(`../src/${file}`, import.meta.url)).text() })),
  198. )
  199. const source = sources.map((item) => item.source).join("\n")
  200. expect(
  201. sources
  202. .filter((item) => item.file !== "provider.ts")
  203. .map((item) => item.source)
  204. .join("\n"),
  205. ).not.toContain("Schema.Any")
  206. expect(sources.find((item) => item.file === "provider.ts")?.source.match(/Schema\.Any/g)).toHaveLength(4)
  207. expect(source).not.toContain("Schema.mutable")
  208. })
  209. test("assistant content keeps only domain identities", () => {
  210. expect(SessionMessage.AssistantText.make({ type: "text", text: "hello" })).toEqual({
  211. type: "text",
  212. text: "hello",
  213. })
  214. expect(
  215. SessionMessage.AssistantReasoning.make({ type: "reasoning", text: "thinking", state: { id: "opaque" } }),
  216. ).toEqual({ type: "reasoning", text: "thinking", state: { id: "opaque" } })
  217. expect(
  218. SessionMessage.AssistantTool.make({
  219. type: "tool",
  220. id: "call_1",
  221. name: "search",
  222. executed: true,
  223. providerState: { itemId: "item_1" },
  224. state: { status: "streaming", input: "" },
  225. time: { created: DateTime.makeUnsafe(0) },
  226. }),
  227. ).not.toHaveProperty("provider")
  228. })
  229. test("reviewed session contracts use their canonical current shapes", () => {
  230. expect(SessionMessage.Info.ast.annotations?.identifier).toBe("Session.Message.Info")
  231. expect(SessionInbox.Info.ast.annotations?.identifier).toBe("Session.Inbox.Info")
  232. expect(Money.USD).not.toBe(Money.USDPerMillionTokens)
  233. expect(
  234. FileDiff.Info.make({ file: "src/index.ts", patch: "@@", additions: 1, deletions: 0, status: "modified" }),
  235. ).toEqual({ file: "src/index.ts", patch: "@@", additions: 1, deletions: 0, status: "modified" })
  236. expect(
  237. SessionMessage.Shell.make({
  238. id: SessionMessage.ID.make("msg_shell"),
  239. type: "shell",
  240. shellID: Shell.ID.make("sh_test"),
  241. command: "pwd",
  242. status: "exited",
  243. exit: 0,
  244. time: { created: DateTime.makeUnsafe(0) },
  245. }),
  246. ).not.toHaveProperty("shell")
  247. expect(
  248. SessionMessage.Skill.make({
  249. id: SessionMessage.ID.make("msg_skill"),
  250. type: "skill",
  251. skill: Skill.ID.make("effect"),
  252. name: Skill.Name.make("Effect"),
  253. text: "Use Effect",
  254. time: { created: DateTime.makeUnsafe(0) },
  255. }),
  256. ).toMatchObject({ skill: "effect", name: "Effect" })
  257. expect(
  258. SessionMessage.CompactionFailed.make({
  259. id: SessionMessage.ID.make("msg_compaction"),
  260. type: "compaction",
  261. status: "failed",
  262. reason: "manual",
  263. error: { type: "compaction.failed", message: "failed" },
  264. time: { created: DateTime.makeUnsafe(0) },
  265. }),
  266. ).not.toHaveProperty("summary")
  267. })
  268. test("keeps shared persisted revert compatibility", () => {
  269. expect(
  270. Schema.decodeUnknownSync(Session.Revert)({
  271. messageID: "msg_legacy",
  272. snapshot: "tree",
  273. diff: "legacy patch",
  274. }),
  275. ).not.toHaveProperty("diff")
  276. const revert = Schema.decodeUnknownSync(PersistedRevert)({
  277. messageID: "msg_legacy",
  278. snapshot: "tree",
  279. diff: "legacy patch",
  280. files: [{ path: "src/index.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" }],
  281. })
  282. expect(String(revert.messageID)).toBe("msg_legacy")
  283. expect(String(revert.snapshot)).toBe("tree")
  284. expect(revert.files).toEqual([
  285. { file: "src/index.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" },
  286. ])
  287. expect(Schema.encodeSync(PersistedRevert)(revert)).toEqual({
  288. messageID: "msg_legacy",
  289. snapshot: "tree",
  290. files: [{ file: "src/index.ts", status: "modified", additions: 1, deletions: 0, patch: "@@" }],
  291. })
  292. })
  293. })