project-reference.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { describe, expect } from "bun:test"
  2. import fs from "fs/promises"
  3. import path from "path"
  4. import { Deferred, Effect, Layer, Schema } from "effect"
  5. import { Config } from "@opencode-ai/core/config"
  6. import { ConfigReference } from "@opencode-ai/core/config/reference"
  7. import { AppFileSystem } from "@opencode-ai/core/filesystem"
  8. import { Flag } from "@opencode-ai/core/flag/flag"
  9. import { Global } from "@opencode-ai/core/global"
  10. import { Location } from "@opencode-ai/core/location"
  11. import { ProjectReference } from "@opencode-ai/core/project-reference"
  12. import { Repository } from "@opencode-ai/core/repository"
  13. import { RepositoryCache } from "@opencode-ai/core/repository-cache"
  14. import { AbsolutePath } from "@opencode-ai/core/schema"
  15. import { location } from "./fixture/location"
  16. import { tmpdir } from "./fixture/tmpdir"
  17. import { it } from "./lib/effect"
  18. describe("ProjectReference", () => {
  19. it.live("uses the broad experimental flag unless references are explicitly configured", () =>
  20. withEnv({ OPENCODE_EXPERIMENTAL: "true", OPENCODE_EXPERIMENTAL_REFERENCES: undefined },
  21. Effect.sync(() => {
  22. expect(Flag.OPENCODE_EXPERIMENTAL_REFERENCES).toBe(true)
  23. }),
  24. ).pipe(
  25. Effect.flatMap(() =>
  26. withEnv({ OPENCODE_EXPERIMENTAL: "true", OPENCODE_EXPERIMENTAL_REFERENCES: "false" },
  27. Effect.sync(() => {
  28. expect(Flag.OPENCODE_EXPERIMENTAL_REFERENCES).toBe(false)
  29. }),
  30. ),
  31. ),
  32. ),
  33. )
  34. it.live("normalizes aliases and resolves relative local paths from the project root", () =>
  35. withTmp((tmp) =>
  36. Effect.gen(function* () {
  37. const project = path.join(tmp.path, "project")
  38. const nested = path.join(project, "packages", "app")
  39. yield* Effect.promise(() => fs.mkdir(nested, { recursive: true }))
  40. const references = ProjectReference.resolveAll({
  41. references: ConfigReference.normalize({
  42. docs: { path: "./docs" },
  43. home: "~/notes",
  44. sdk: { repository: "owner/repo", branch: "main" },
  45. shorthand: "owner/other",
  46. invalid: "not-a-repo",
  47. "bad/name": "owner/repo",
  48. }),
  49. directory: project,
  50. home: path.join(tmp.path, "home"),
  51. repos: path.join(tmp.path, "repos"),
  52. })
  53. expect(references).toMatchObject([
  54. { name: "docs", kind: "local", path: path.join(project, "docs") },
  55. { name: "home", kind: "local", path: path.join(tmp.path, "home", "notes") },
  56. { name: "sdk", kind: "git", branch: "main" },
  57. { name: "shorthand", kind: "git" },
  58. { name: "invalid", kind: "invalid", repository: "not-a-repo" },
  59. { name: "bad/name", kind: "invalid" },
  60. ])
  61. }),
  62. ),
  63. )
  64. it.live("marks same-cache references with different branches invalid", () =>
  65. Effect.sync(() => {
  66. const references = ProjectReference.resolveAll({
  67. references: ConfigReference.normalize({
  68. main: { repository: "owner/repo", branch: "main" },
  69. dev: { repository: "github.com/owner/repo", branch: "dev" },
  70. alsoMain: { repository: "https://github.com/owner/repo", branch: "main" },
  71. }),
  72. directory: "/project",
  73. home: "/home",
  74. repos: "/repos",
  75. })
  76. expect(references.map((reference) => reference.kind)).toEqual(["git", "invalid", "git"])
  77. expect(references[1]?.kind === "invalid" ? references[1].message : "").toContain("conflicts with @main")
  78. }),
  79. )
  80. it.live("merges config aliases and exposes mention and managed-path operations", () =>
  81. withoutReferences(withTmp((tmp) => {
  82. const calls: RepositoryCache.EnsureInput[] = []
  83. const project = path.join(tmp.path, "project")
  84. const nested = path.join(project, "packages", "app")
  85. const docs = path.join(project, "docs")
  86. const repos = path.join(tmp.path, "repos")
  87. return Effect.gen(function* () {
  88. yield* Effect.promise(async () => {
  89. await fs.mkdir(nested, { recursive: true })
  90. await fs.mkdir(docs)
  91. await fs.writeFile(path.join(docs, "README.md"), "docs")
  92. })
  93. yield* withReferences(
  94. Effect.gen(function* () {
  95. const references = yield* ProjectReference.Service
  96. const git = path.join(repos, "github.com", "owner", "repo")
  97. expect(yield* references.list()).toMatchObject([
  98. { name: "docs", kind: "local", path: docs },
  99. { name: "sdk", kind: "git", path: git },
  100. ])
  101. expect(yield* references.resolveMention("docs/README.md")).toMatchObject({
  102. name: "docs",
  103. kind: "reference",
  104. target: "README.md",
  105. path: path.join(docs, "README.md"),
  106. })
  107. expect(yield* references.resolveMention("docs/missing.md")).toMatchObject({ name: "docs", kind: "missing" })
  108. expect(yield* references.resolveMention("docs/../outside.md")).toMatchObject({ name: "docs", kind: "invalid" })
  109. expect(yield* references.resolveMention("unknown")).toBeUndefined()
  110. expect(yield* references.resolveMention("sdk")).toMatchObject({ name: "sdk", kind: "reference", path: git })
  111. expect(yield* references.containsManagedPath(path.join(git, "README.md"))).toBe(true)
  112. expect(yield* references.containsManagedPath(path.join(docs, "README.md"))).toBe(false)
  113. yield* references.ensurePath()
  114. expect(calls).toHaveLength(1)
  115. }).pipe(
  116. Effect.provide(
  117. testLayer({
  118. directory: nested,
  119. project,
  120. repos,
  121. documents: [
  122. document({ docs: { path: "./old-docs" }, sdk: "owner/old" }),
  123. document({ docs: { path: "./docs" }, sdk: { repository: "owner/repo", branch: "main" } }),
  124. ],
  125. ensure: (input) => Effect.sync(() => result(repos, calls, input)),
  126. }),
  127. ),
  128. ),
  129. )
  130. })
  131. })),
  132. )
  133. it.live("is inert while the runtime flag is disabled", () =>
  134. withoutReferences(withTmp((tmp) => {
  135. const calls: RepositoryCache.EnsureInput[] = []
  136. return Effect.gen(function* () {
  137. const references = yield* ProjectReference.Service
  138. expect(yield* references.list()).toEqual([])
  139. expect(yield* references.get("sdk")).toBeUndefined()
  140. expect(yield* references.resolveMention("sdk")).toBeUndefined()
  141. expect(yield* references.containsManagedPath(path.join(tmp.path, "repos", "github.com", "owner", "repo"))).toBe(false)
  142. yield* references.ensurePath()
  143. expect(calls).toEqual([])
  144. }).pipe(
  145. Effect.provide(
  146. testLayer({
  147. directory: tmp.path,
  148. project: tmp.path,
  149. repos: path.join(tmp.path, "repos"),
  150. documents: [document({ sdk: "owner/repo" })],
  151. ensure: (input) => Effect.sync(() => result(path.join(tmp.path, "repos"), calls, input)),
  152. }),
  153. ),
  154. )
  155. })),
  156. )
  157. it.live("starts Git materialization in the background without blocking the location layer", () =>
  158. withTmp((tmp) =>
  159. Effect.gen(function* () {
  160. const started = yield* Deferred.make<void>()
  161. yield* withReferences(
  162. Effect.gen(function* () {
  163. expect(yield* (yield* ProjectReference.Service).list()).toHaveLength(1)
  164. yield* Deferred.await(started).pipe(
  165. Effect.timeoutOrElse({ duration: "1 second", orElse: () => Effect.die(new Error("refresh did not start")) }),
  166. )
  167. }).pipe(
  168. Effect.provide(
  169. testLayer({
  170. directory: tmp.path,
  171. project: tmp.path,
  172. repos: path.join(tmp.path, "repos"),
  173. documents: [document({ sdk: "owner/repo" })],
  174. ensure: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
  175. }),
  176. ),
  177. ),
  178. )
  179. }),
  180. ),
  181. )
  182. })
  183. function document(references: ConfigReference.Info) {
  184. return new Config.Loaded({ source: { type: "memory" }, info: Schema.decodeUnknownSync(Config.Info)({ references }) })
  185. }
  186. function result(repos: string, calls: RepositoryCache.EnsureInput[], input: RepositoryCache.EnsureInput): RepositoryCache.Result {
  187. calls.push(input)
  188. return {
  189. repository: input.reference.label,
  190. host: input.reference.host,
  191. remote: input.reference.remote,
  192. localPath: Repository.cachePath(repos, input.reference),
  193. status: "cached",
  194. branch: input.branch,
  195. }
  196. }
  197. function testLayer(input: {
  198. directory: string
  199. project: string
  200. repos: string
  201. documents: Config.Loaded[]
  202. ensure: RepositoryCache.Interface["ensure"]
  203. }) {
  204. return ProjectReference.layer.pipe(
  205. Layer.provide(
  206. Layer.mergeAll(
  207. AppFileSystem.defaultLayer,
  208. Global.layerWith({ home: path.join(input.directory, "home"), repos: input.repos }),
  209. Layer.succeed(
  210. Location.Service,
  211. Location.Service.of(
  212. location({ directory: AbsolutePath.make(input.directory) }, { projectDirectory: AbsolutePath.make(input.project) }),
  213. ),
  214. ),
  215. Layer.succeed(Config.Service, Config.Service.of({ directories: () => Effect.succeed([]), get: () => Effect.succeed(input.documents) })),
  216. Layer.succeed(RepositoryCache.Service, RepositoryCache.Service.of({ ensure: input.ensure })),
  217. ),
  218. ),
  219. )
  220. }
  221. function withTmp<A, E, R>(body: (tmp: Awaited<ReturnType<typeof tmpdir>>) => Effect.Effect<A, E, R>) {
  222. return Effect.acquireUseRelease(Effect.promise(() => tmpdir()), body, (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()))
  223. }
  224. function withReferences<A, E, R>(body: Effect.Effect<A, E, R>) {
  225. return withEnv({ OPENCODE_EXPERIMENTAL_REFERENCES: "true" }, body)
  226. }
  227. function withoutReferences<A, E, R>(body: Effect.Effect<A, E, R>) {
  228. return withEnv({ OPENCODE_EXPERIMENTAL: undefined, OPENCODE_EXPERIMENTAL_REFERENCES: undefined }, body)
  229. }
  230. function withEnv<A, E, R>(env: Record<string, string | undefined>, body: Effect.Effect<A, E, R>) {
  231. return Effect.acquireUseRelease(
  232. Effect.sync(() => {
  233. const previous = Object.fromEntries(Object.keys(env).map((key) => [key, process.env[key]]))
  234. for (const [key, value] of Object.entries(env)) {
  235. if (value === undefined) delete process.env[key]
  236. else process.env[key] = value
  237. }
  238. return previous
  239. }),
  240. () => body,
  241. (previous) =>
  242. Effect.sync(() => {
  243. for (const [key, value] of Object.entries(previous)) {
  244. if (value === undefined) delete process.env[key]
  245. else process.env[key] = value
  246. }
  247. }),
  248. )
  249. }