config.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import path from "path"
  2. import fs from "fs/promises"
  3. import { describe, expect } from "bun:test"
  4. import { Effect, Layer, Schema } from "effect"
  5. import { FastCheck } from "effect/testing"
  6. import { Config } from "@opencode-ai/core/config"
  7. import { ConfigProvider } from "@opencode-ai/core/config/provider"
  8. import { ConfigMigrateV1 } from "@opencode-ai/core/v1/config/migrate"
  9. import { ConfigV1 } from "@opencode-ai/core/v1/config/config"
  10. import { FSUtil } from "@opencode-ai/core/fs-util"
  11. import { Global } from "@opencode-ai/core/global"
  12. import { Location } from "@opencode-ai/core/location"
  13. import { Policy } from "@opencode-ai/core/policy"
  14. import { Project } from "@opencode-ai/core/project"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { location } from "../fixture/location"
  17. import { tmpdir } from "../fixture/tmpdir"
  18. import { testEffect } from "../lib/effect"
  19. const it = testEffect(Layer.empty)
  20. function testLayer(
  21. directory: string,
  22. globalDirectory = path.join(directory, "global"),
  23. projectDirectory = directory,
  24. vcs?: Project.Vcs,
  25. ) {
  26. return Config.locationLayer.pipe(
  27. Layer.provide(FSUtil.defaultLayer),
  28. Layer.provide(Global.layerWith({ config: globalDirectory })),
  29. Layer.provide(
  30. Layer.succeed(
  31. Location.Service,
  32. Location.Service.of(
  33. location(
  34. { directory: AbsolutePath.make(directory) },
  35. { projectDirectory: AbsolutePath.make(projectDirectory), vcs },
  36. ),
  37. ),
  38. ),
  39. ),
  40. )
  41. }
  42. const provider = {
  43. api: { type: "native", settings: {} },
  44. request: {
  45. headers: {},
  46. body: {},
  47. },
  48. models: {},
  49. }
  50. describe("Config", () => {
  51. it.effect("detects v1 configuration from any v1-only top-level key", () =>
  52. Effect.sync(() => {
  53. expect(ConfigMigrateV1.isV1({ snapshot: false })).toBe(true)
  54. expect(ConfigMigrateV1.isV1({ snapshot: false, agents: {} })).toBe(true)
  55. expect(ConfigMigrateV1.isV1({ shell: "/bin/zsh", model: "anthropic/claude" })).toBe(false)
  56. }),
  57. )
  58. it.effect("migrates arbitrary v1 configuration into valid v2 configuration", () =>
  59. Effect.sync(() => {
  60. FastCheck.assert(
  61. FastCheck.property(Schema.toArbitrary(ConfigV1.Info), (info) => {
  62. Schema.decodeUnknownSync(Config.Info)(ConfigMigrateV1.migrate(info), { errors: "all" })
  63. }),
  64. { numRuns: 100 },
  65. )
  66. }),
  67. )
  68. it.effect("migrates v1 provider setup options into AISDK settings", () =>
  69. Effect.sync(() => {
  70. const migrated = ConfigMigrateV1.migrate({
  71. provider: {
  72. bedrock: {
  73. npm: "@ai-sdk/amazon-bedrock",
  74. options: {
  75. headers: { "x-test": "1" },
  76. body: { trace: true },
  77. region: "us-east-1",
  78. profile: "dev",
  79. },
  80. },
  81. },
  82. })
  83. expect(migrated.providers?.bedrock?.api).toEqual({
  84. type: "aisdk",
  85. package: "@ai-sdk/amazon-bedrock",
  86. url: undefined,
  87. settings: { region: "us-east-1", profile: "dev" },
  88. })
  89. expect(migrated.providers?.bedrock?.request).toEqual({
  90. headers: { "x-test": "1" },
  91. body: { trace: true },
  92. })
  93. }),
  94. )
  95. it.effect("migrates v1 command configuration", () =>
  96. Effect.sync(() => {
  97. expect(
  98. ConfigMigrateV1.migrate({
  99. command: {
  100. review: {
  101. template: "Review changes",
  102. description: "Review code",
  103. agent: "reviewer",
  104. model: "anthropic/claude",
  105. variant: "high",
  106. subtask: true,
  107. },
  108. },
  109. }).commands,
  110. ).toEqual({
  111. review: {
  112. template: "Review changes",
  113. description: "Review code",
  114. agent: "reviewer",
  115. model: "anthropic/claude",
  116. variant: "high",
  117. subtask: true,
  118. },
  119. })
  120. }),
  121. )
  122. it.live("returns an empty configuration when directory files do not exist", () =>
  123. Effect.acquireRelease(
  124. Effect.promise(() => tmpdir()),
  125. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  126. ).pipe(
  127. Effect.flatMap((tmp) =>
  128. Effect.gen(function* () {
  129. const config = yield* Config.Service
  130. const entries = yield* config.entries()
  131. expect(entries).toEqual([
  132. new Config.Directory({ type: "directory", path: AbsolutePath.make(path.join(tmp.path, "global")) }),
  133. ])
  134. }).pipe(Effect.provide(testLayer(tmp.path))),
  135. ),
  136. ),
  137. )
  138. it.live("loads JSON and JSONC files from lowest to highest priority", () =>
  139. Effect.acquireRelease(
  140. Effect.promise(() => tmpdir()),
  141. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  142. ).pipe(
  143. Effect.flatMap((tmp) =>
  144. Effect.gen(function* () {
  145. yield* Effect.promise(() =>
  146. Promise.all([
  147. fs.writeFile(
  148. path.join(tmp.path, "config.json"),
  149. JSON.stringify({ $schema: "base", providers: { base: provider } }),
  150. ),
  151. fs.writeFile(
  152. path.join(tmp.path, "opencode.json"),
  153. JSON.stringify({ $schema: "middle", providers: { middle: provider } }),
  154. ),
  155. fs.writeFile(
  156. path.join(tmp.path, "opencode.jsonc"),
  157. `{
  158. // Later global files override scalar fields while retaining providers.
  159. "$schema": "last",
  160. "providers": { "last": ${JSON.stringify(provider)} },
  161. }`,
  162. ),
  163. ]),
  164. )
  165. return yield* Effect.gen(function* () {
  166. const config = yield* Config.Service
  167. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  168. expect(documents).toHaveLength(3)
  169. expect(documents.map((document) => document.type)).toEqual(["document", "document", "document"])
  170. expect(documents.map((document) => document.info.$schema)).toEqual(["base", "middle", "last"])
  171. expect(documents[0]).toBeInstanceOf(Config.Document)
  172. expect(documents[0]?.path).toBe(path.join(tmp.path, "config.json"))
  173. expect(documents[2]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info)
  174. yield* Effect.promise(() =>
  175. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ $schema: "changed" })),
  176. )
  177. expect(
  178. (yield* config.entries())
  179. .filter((entry) => entry.type === "document")
  180. .map((document) => document.info.$schema),
  181. ).toEqual(["base", "middle", "last"])
  182. }).pipe(Effect.provide(testLayer(tmp.path)))
  183. }),
  184. ),
  185. ),
  186. )
  187. it.live("accepts $schema metadata without writing it into config files", () =>
  188. Effect.acquireRelease(
  189. Effect.promise(() => tmpdir()),
  190. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  191. ).pipe(
  192. Effect.flatMap((tmp) =>
  193. Effect.gen(function* () {
  194. const file = path.join(tmp.path, "opencode.json")
  195. const contents = JSON.stringify({
  196. shell: "/bin/zsh",
  197. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  198. providers: { local: provider },
  199. })
  200. yield* Effect.promise(() => fs.writeFile(file, contents))
  201. return yield* Effect.gen(function* () {
  202. const config = yield* Config.Service
  203. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  204. expect(documents[0]?.info.$schema).toBeUndefined()
  205. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  206. expect(documents[0]?.info.experimental?.policies?.[0]).toEqual({
  207. effect: "deny",
  208. action: "provider.use",
  209. resource: "openai",
  210. })
  211. expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents)
  212. }).pipe(Effect.provide(testLayer(tmp.path)))
  213. }),
  214. ),
  215. ),
  216. )
  217. it.live("loads supported scalar and resource configuration", () =>
  218. Effect.acquireRelease(
  219. Effect.promise(() => tmpdir()),
  220. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  221. ).pipe(
  222. Effect.flatMap((tmp) =>
  223. Effect.gen(function* () {
  224. yield* Effect.promise(() =>
  225. fs.writeFile(
  226. path.join(tmp.path, "opencode.json"),
  227. JSON.stringify({
  228. shell: "/bin/bash",
  229. model: "anthropic/claude",
  230. default_agent: "reviewer",
  231. autoupdate: "notify",
  232. share: "disabled",
  233. enterprise: { url: "https://share.example.com" },
  234. username: "test-user",
  235. permissions: [
  236. { action: "bash", resource: "*", effect: "ask" },
  237. { action: "bash", resource: "git status", effect: "allow" },
  238. ],
  239. agents: {
  240. reviewer: {
  241. model: "openrouter/openai/gpt-5",
  242. variant: "high",
  243. request: {
  244. headers: { "x-agent": "reviewer" },
  245. body: { reasoningEffort: "high" },
  246. },
  247. description: "Review changes for correctness",
  248. system: "Find regressions.",
  249. mode: "subagent",
  250. hidden: false,
  251. color: "warning",
  252. steps: 12,
  253. disabled: false,
  254. permissions: [{ action: "edit", resource: "*", effect: "deny" }],
  255. },
  256. },
  257. snapshots: false,
  258. watcher: { ignore: ["node_modules/**", "dist/**", ".git"] },
  259. formatter: {
  260. prettier: { disabled: true },
  261. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  262. },
  263. lsp: { typescript: { disabled: true }, custom: { command: ["custom-lsp"], extensions: [".foo"] } },
  264. attachments: {
  265. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  266. },
  267. tool_output: { max_lines: 1000, max_bytes: 32768 },
  268. mcp: {
  269. timeout: 5000,
  270. servers: {
  271. local: {
  272. type: "local",
  273. command: ["node", "./mcp/server.js"],
  274. environment: { API_KEY: "secret" },
  275. disabled: false,
  276. timeout: 10000,
  277. },
  278. remote: {
  279. type: "remote",
  280. url: "https://mcp.example.com/mcp",
  281. headers: { Authorization: "Bearer token" },
  282. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  283. disabled: true,
  284. },
  285. },
  286. },
  287. compaction: {
  288. auto: true,
  289. prune: false,
  290. keep: { turns: 3, tokens: 2000 },
  291. buffer: 10000,
  292. },
  293. skills: ["./skills", "~/shared-skills", "https://example.com/.well-known/skills/"],
  294. instructions: ["CONTRIBUTING.md", ".cursor/rules/*.md", "https://example.com/shared-rules.md"],
  295. references: {
  296. local: { path: "../library" },
  297. sdk: { repository: "github.com/example/sdk", branch: "main" },
  298. shorthand: "github.com/example/docs",
  299. },
  300. plugins: [
  301. "opencode-helicone-session",
  302. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  303. ],
  304. }),
  305. ),
  306. )
  307. return yield* Effect.gen(function* () {
  308. const config = yield* Config.Service
  309. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  310. expect(documents).toHaveLength(1)
  311. expect(documents[0]?.info.shell).toBe("/bin/bash")
  312. expect(documents[0]?.info.model).toBe("anthropic/claude")
  313. expect(documents[0]?.info.default_agent).toBe("reviewer")
  314. expect(documents[0]?.info.autoupdate).toBe("notify")
  315. expect(documents[0]?.info.share).toBe("disabled")
  316. expect(documents[0]?.info.enterprise).toEqual({ url: "https://share.example.com" })
  317. expect(documents[0]?.info.username).toBe("test-user")
  318. expect(documents[0]?.info.permissions).toEqual([
  319. { action: "bash", resource: "*", effect: "ask" },
  320. { action: "bash", resource: "git status", effect: "allow" },
  321. ])
  322. const reviewer = documents[0]?.info.agents?.reviewer
  323. expect(reviewer?.model).toBe("openrouter/openai/gpt-5")
  324. expect(reviewer?.variant).toBe("high")
  325. expect(reviewer?.request).toEqual({
  326. headers: { "x-agent": "reviewer" },
  327. body: { reasoningEffort: "high" },
  328. })
  329. expect(reviewer?.description).toBe("Review changes for correctness")
  330. expect(reviewer?.system).toBe("Find regressions.")
  331. expect(reviewer?.mode).toBe("subagent")
  332. expect(reviewer?.hidden).toBe(false)
  333. expect(reviewer?.color).toBe("warning")
  334. expect(reviewer?.steps).toBe(12)
  335. expect(reviewer?.disabled).toBe(false)
  336. expect(reviewer?.permissions).toEqual([{ action: "edit", resource: "*", effect: "deny" }])
  337. expect(documents[0]?.info.snapshots).toBe(false)
  338. expect(documents[0]?.info.watcher).toEqual({ ignore: ["node_modules/**", "dist/**", ".git"] })
  339. expect(documents[0]?.info.formatter).toEqual({
  340. prettier: { disabled: true },
  341. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  342. })
  343. expect(documents[0]?.info.lsp).toEqual({
  344. typescript: { disabled: true },
  345. custom: { command: ["custom-lsp"], extensions: [".foo"] },
  346. })
  347. expect(documents[0]?.info.attachments).toEqual({
  348. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  349. })
  350. expect(documents[0]?.info.tool_output).toEqual({ max_lines: 1000, max_bytes: 32768 })
  351. expect(documents[0]?.info.mcp).toEqual({
  352. timeout: 5000,
  353. servers: {
  354. local: {
  355. type: "local",
  356. command: ["node", "./mcp/server.js"],
  357. environment: { API_KEY: "secret" },
  358. disabled: false,
  359. timeout: 10000,
  360. },
  361. remote: {
  362. type: "remote",
  363. url: "https://mcp.example.com/mcp",
  364. headers: { Authorization: "Bearer token" },
  365. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  366. disabled: true,
  367. },
  368. },
  369. })
  370. expect(documents[0]?.info.compaction).toEqual({
  371. auto: true,
  372. prune: false,
  373. keep: { turns: 3, tokens: 2000 },
  374. buffer: 10000,
  375. })
  376. expect(documents[0]?.info.skills).toEqual([
  377. "./skills",
  378. "~/shared-skills",
  379. "https://example.com/.well-known/skills/",
  380. ])
  381. expect(documents[0]?.info.instructions).toEqual([
  382. "CONTRIBUTING.md",
  383. ".cursor/rules/*.md",
  384. "https://example.com/shared-rules.md",
  385. ])
  386. expect(documents[0]?.info.references).toEqual({
  387. local: { path: "../library" },
  388. sdk: { repository: "github.com/example/sdk", branch: "main" },
  389. shorthand: "github.com/example/docs",
  390. })
  391. expect(documents[0]?.info.plugins).toEqual([
  392. "opencode-helicone-session",
  393. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  394. ])
  395. }).pipe(Effect.provide(testLayer(tmp.path)))
  396. }),
  397. ),
  398. ),
  399. )
  400. it.live("migrates v1 configuration when a v1-only key is present", () =>
  401. Effect.acquireRelease(
  402. Effect.promise(() => tmpdir()),
  403. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  404. ).pipe(
  405. Effect.flatMap((tmp) =>
  406. Effect.gen(function* () {
  407. yield* Effect.promise(() =>
  408. fs.writeFile(
  409. path.join(tmp.path, "opencode.json"),
  410. JSON.stringify({
  411. shell: "/bin/zsh",
  412. default_agent: "reviewer",
  413. snapshot: false,
  414. autoshare: true,
  415. permission: {
  416. bash: "ask",
  417. edit: { "*.md": "allow", "*": "deny" },
  418. },
  419. agent: {
  420. reviewer: {
  421. prompt: "Review changes.",
  422. disable: true,
  423. temperature: 0.2,
  424. permission: { read: "allow" },
  425. },
  426. },
  427. plugin: [
  428. "opencode-helicone-session",
  429. ["@my-org/audit-plugin", { endpoint: "https://audit.example.com" }],
  430. ],
  431. skills: { paths: ["./skills"], urls: ["https://example.com/.well-known/skills/"] },
  432. reference: { docs: { path: "../docs" } },
  433. attachment: { image: { auto_resize: false, max_width: 1200 } },
  434. provider: {
  435. custom: {
  436. options: { apiKey: "secret" },
  437. models: {
  438. model: {
  439. options: { reasoningEffort: "high" },
  440. variants: { fast: { temperature: 0.2 } },
  441. },
  442. },
  443. },
  444. openai: {
  445. npm: "@ai-sdk/openai",
  446. options: { apiKey: "secret", organization: "org" },
  447. models: {
  448. model: { options: { reasoningEffort: "high", serviceTier: "priority" } },
  449. },
  450. },
  451. },
  452. compaction: { auto: true, tail_turns: 3, preserve_recent_tokens: 2000, reserved: 10000 },
  453. experimental: { mcp_timeout: 5000 },
  454. mcp: {
  455. local: { type: "local", command: ["node", "server.js"], enabled: false },
  456. remote: {
  457. type: "remote",
  458. url: "https://mcp.example.com",
  459. oauth: { clientId: "client", callbackPort: 19876 },
  460. },
  461. },
  462. }),
  463. ),
  464. )
  465. return yield* Effect.gen(function* () {
  466. const config = yield* Config.Service
  467. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  468. expect(documents).toHaveLength(1)
  469. expect(documents[0]?.info).toBeInstanceOf(Config.Info)
  470. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  471. expect(documents[0]?.info.default_agent).toBe("reviewer")
  472. expect(documents[0]?.info.snapshots).toBe(false)
  473. expect(documents[0]?.info.share).toBe("auto")
  474. expect(documents[0]?.info.permissions).toEqual([
  475. { action: "bash", resource: "*", effect: "ask" },
  476. { action: "edit", resource: "*.md", effect: "allow" },
  477. { action: "edit", resource: "*", effect: "deny" },
  478. ])
  479. expect(documents[0]?.info.agents?.reviewer).toMatchObject({
  480. system: "Review changes.",
  481. disabled: true,
  482. request: { body: { temperature: 0.2 } },
  483. permissions: [{ action: "read", resource: "*", effect: "allow" }],
  484. })
  485. expect(documents[0]?.info.plugins).toEqual([
  486. "opencode-helicone-session",
  487. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  488. ])
  489. expect(documents[0]?.info.skills).toEqual(["./skills", "https://example.com/.well-known/skills/"])
  490. expect(documents[0]?.info.references).toEqual({ docs: { path: "../docs" } })
  491. expect(documents[0]?.info.attachments).toEqual({ image: { auto_resize: false, max_width: 1200 } })
  492. expect(documents[0]?.info.providers?.custom).toMatchObject({
  493. request: { body: { apiKey: "secret" } },
  494. models: {
  495. model: {
  496. request: { body: { reasoningEffort: "high" } },
  497. variants: [{ id: "fast", body: { temperature: 0.2 } }],
  498. },
  499. },
  500. })
  501. expect(documents[0]?.info.providers?.openai).toMatchObject({
  502. api: { settings: {} },
  503. request: { headers: { Authorization: "Bearer secret", "OpenAI-Organization": "org" } },
  504. models: { model: { request: { body: { reasoning_effort: "high", service_tier: "priority" } } } },
  505. })
  506. expect(documents[0]?.info.compaction).toEqual({
  507. auto: true,
  508. prune: undefined,
  509. keep: { turns: 3, tokens: 2000 },
  510. buffer: 10000,
  511. })
  512. expect(documents[0]?.info.mcp).toMatchObject({
  513. timeout: 5000,
  514. servers: {
  515. local: { type: "local", command: ["node", "server.js"], disabled: true },
  516. remote: {
  517. type: "remote",
  518. url: "https://mcp.example.com",
  519. oauth: { client_id: "client", callback_port: 19876 },
  520. },
  521. },
  522. })
  523. }).pipe(Effect.provide(testLayer(tmp.path)))
  524. }),
  525. ),
  526. ),
  527. )
  528. it.live("ignores invalid files while loading valid config values", () =>
  529. Effect.acquireRelease(
  530. Effect.promise(() => tmpdir()),
  531. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  532. ).pipe(
  533. Effect.flatMap((tmp) =>
  534. Effect.gen(function* () {
  535. yield* Effect.promise(() =>
  536. Promise.all([
  537. fs.writeFile(path.join(tmp.path, "config.json"), JSON.stringify({ $schema: "base" })),
  538. fs.writeFile(path.join(tmp.path, "opencode.json"), "{ invalid"),
  539. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ providers: { invalid: true } })),
  540. ]),
  541. )
  542. return yield* Effect.gen(function* () {
  543. const config = yield* Config.Service
  544. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  545. expect(documents.map((document) => document.info.$schema)).toEqual(["base"])
  546. }).pipe(Effect.provide(testLayer(tmp.path)))
  547. }),
  548. ),
  549. ),
  550. )
  551. it.live("loads policy statements in reverse config order", () =>
  552. Effect.acquireRelease(
  553. Effect.promise(() => tmpdir()),
  554. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  555. ).pipe(
  556. Effect.flatMap((tmp) => {
  557. const global = path.join(tmp.path, "global")
  558. return Effect.gen(function* () {
  559. yield* Effect.promise(async () => {
  560. await fs.mkdir(global, { recursive: true })
  561. await fs.writeFile(
  562. path.join(global, "opencode.json"),
  563. JSON.stringify({
  564. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  565. }),
  566. )
  567. await fs.writeFile(
  568. path.join(tmp.path, "opencode.json"),
  569. JSON.stringify({
  570. experimental: { policies: [{ effect: "allow", action: "provider.use", resource: "openai" }] },
  571. }),
  572. )
  573. })
  574. return yield* Effect.gen(function* () {
  575. const policy = yield* Policy.Service
  576. expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny")
  577. }).pipe(Effect.provide(testLayer(tmp.path, global)))
  578. })
  579. }),
  580. ),
  581. )
  582. it.live("loads global, ancestor, and .opencode configuration up to the project boundary", () =>
  583. Effect.acquireRelease(
  584. Effect.promise(() => tmpdir()),
  585. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  586. ).pipe(
  587. Effect.flatMap((tmp) => {
  588. const global = path.join(tmp.path, "global")
  589. const root = path.join(tmp.path, "repo")
  590. const parent = path.join(root, "packages")
  591. const directory = path.join(parent, "app")
  592. return Effect.gen(function* () {
  593. yield* Effect.promise(async () => {
  594. await fs.mkdir(global, { recursive: true })
  595. await fs.mkdir(directory, { recursive: true })
  596. await fs.mkdir(path.join(root, ".opencode"), { recursive: true })
  597. await fs.mkdir(path.join(directory, ".opencode"), { recursive: true })
  598. await Promise.all([
  599. fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "outside" })),
  600. fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ $schema: "global" })),
  601. fs.writeFile(path.join(root, "opencode.json"), JSON.stringify({ $schema: "root" })),
  602. fs.writeFile(path.join(parent, "opencode.jsonc"), JSON.stringify({ $schema: "parent" })),
  603. fs.writeFile(path.join(directory, "config.json"), JSON.stringify({ $schema: "directory" })),
  604. fs.writeFile(path.join(root, ".opencode", "opencode.json"), JSON.stringify({ $schema: "root-dot" })),
  605. fs.writeFile(
  606. path.join(directory, ".opencode", "opencode.jsonc"),
  607. JSON.stringify({ $schema: "directory-dot" }),
  608. ),
  609. ])
  610. })
  611. return yield* Effect.gen(function* () {
  612. const config = yield* Config.Service
  613. const entries = yield* config.entries()
  614. const documents = entries.filter((entry) => entry.type === "document")
  615. expect(entries.filter((entry) => entry.type === "directory").map((entry) => entry.path)).toEqual([
  616. AbsolutePath.make(global),
  617. AbsolutePath.make(path.join(root, ".opencode")),
  618. AbsolutePath.make(path.join(directory, ".opencode")),
  619. ])
  620. expect(documents.map((document) => document.info.$schema)).toEqual([
  621. "global",
  622. "root",
  623. "parent",
  624. "directory",
  625. "root-dot",
  626. "directory-dot",
  627. ])
  628. expect(entries.map((entry) => (entry.type === "document" ? entry.info.$schema : entry.path))).toEqual([
  629. "global",
  630. AbsolutePath.make(global),
  631. "root",
  632. "parent",
  633. "directory",
  634. "root-dot",
  635. AbsolutePath.make(path.join(root, ".opencode")),
  636. "directory-dot",
  637. AbsolutePath.make(path.join(directory, ".opencode")),
  638. ])
  639. }).pipe(
  640. Effect.provide(
  641. testLayer(directory, global, root, {
  642. type: "git",
  643. store: AbsolutePath.make(path.join(root, ".git")),
  644. }),
  645. ),
  646. )
  647. })
  648. }),
  649. ),
  650. )
  651. })