session-instructions.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { describe, expect, test } from "bun:test"
  2. import fs from "fs/promises"
  3. import path from "path"
  4. import { DateTime, Effect, Layer, Stream } from "effect"
  5. import { Message } from "@opencode-ai/ai"
  6. import { Agent } from "@opencode-ai/core/agent"
  7. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  8. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  9. import { Config } from "@opencode-ai/core/config"
  10. import { Database } from "@opencode-ai/core/database/database"
  11. import { Bus } from "@opencode-ai/core/bus"
  12. import { FSUtil } from "@opencode-ai/util/fs-util"
  13. import { Global } from "@opencode-ai/util/global"
  14. import { Image } from "@opencode-ai/core/image"
  15. import { Location } from "@opencode-ai/core/location"
  16. import { LocationMutation } from "@opencode-ai/core/location-mutation"
  17. import { Model } from "@opencode-ai/core/model"
  18. import { Permission } from "@opencode-ai/core/permission"
  19. import { Project } from "@opencode-ai/core/project"
  20. import { Provider } from "@opencode-ai/core/provider"
  21. import { ReadTool } from "@opencode-ai/core/tool/plugin/read"
  22. import { ReadToolFileSystem } from "@opencode-ai/core/tool/read-filesystem"
  23. import { SessionEvent } from "@opencode-ai/core/session/event"
  24. import { SessionExecution } from "@opencode-ai/core/session/execution"
  25. import { SessionInstructions } from "@opencode-ai/core/session/instructions"
  26. import { SessionMessage } from "@opencode-ai/core/session/message"
  27. import { SessionProjector } from "@opencode-ai/core/session/projector"
  28. import { SessionStore } from "@opencode-ai/core/session/store"
  29. import { Session } from "@opencode-ai/core/session"
  30. import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message"
  31. import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
  32. import { Tool } from "@opencode-ai/core/tool"
  33. import { tempLocationLayer } from "./fixture/location"
  34. import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
  35. import { testEffect } from "./lib/effect"
  36. import { permissionLayer } from "./lib/permission"
  37. import { globalProjectLayer } from "./lib/project"
  38. import { executeTool, registerToolPlugin } from "./lib/tool"
  39. const readToolNode = makeLocationNode({
  40. name: "test/read-tool-plugin",
  41. layer: Layer.effectDiscard(registerToolPlugin(ReadTool.Plugin)),
  42. deps: [
  43. Tool.node,
  44. ReadToolFileSystem.node,
  45. LocationMutation.node,
  46. Image.node,
  47. Permission.node,
  48. SessionInstructions.node,
  49. FSUtil.node,
  50. Location.node,
  51. ],
  52. })
  53. const permission = permissionLayer({ assert: () => Effect.void })
  54. const config = Config.testLayer()
  55. const imageLayer = AppNodeBuilder.build(Image.node, [[Config.node, config]])
  56. const testLayer = AppNodeBuilder.build(
  57. LayerNode.group([
  58. Database.node,
  59. Bus.node,
  60. SessionProjector.node,
  61. SessionStore.node,
  62. Session.node,
  63. Location.node,
  64. FSUtil.node,
  65. LocationMutation.node,
  66. ReadToolFileSystem.node,
  67. readToolNode,
  68. Tool.node,
  69. Tool.node,
  70. PluginHooks.node,
  71. SessionInstructions.node,
  72. Global.node,
  73. Image.node,
  74. ]),
  75. [
  76. [Project.node, globalProjectLayer],
  77. [SessionExecution.node, SessionExecution.noopLayer],
  78. [Location.node, tempLocationLayer],
  79. [Permission.node, permission],
  80. [Config.node, config],
  81. [Image.node, imageLayer],
  82. ],
  83. ) as unknown as Layer.Layer<unknown>
  84. const it = testEffect(testLayer)
  85. const identity = {
  86. agent: Agent.ID.make("build"),
  87. messageID: SessionMessage.ID.make("msg_nearby"),
  88. }
  89. const readCall = (sessionID: Session.ID, id: string, readPath: string): Parameters<Tool.Snapshot["execute"]>[0] => ({
  90. sessionID,
  91. ...identity,
  92. call: { type: "tool-call", id, name: "read", input: { path: readPath } },
  93. })
  94. const writeAgents = (file: string, content: string) => Effect.promise(() => fs.writeFile(file, content))
  95. const mkdir = (dir: string) => Effect.promise(() => fs.mkdir(dir, { recursive: true }))
  96. const synthetics = (sessionID: Session.ID) =>
  97. Effect.gen(function* () {
  98. const store = yield* SessionStore.Service
  99. return (yield* store.context(sessionID)).filter((message) => message.type === "synthetic")
  100. })
  101. // Seed a prior synthetic message with an instruction dedup ledger, simulating a prior turn
  102. // after the Location layer was reopened (in-memory set empty).
  103. const seedSynthetic = (sessionID: Session.ID, paths: string[]) =>
  104. Effect.gen(function* () {
  105. const bus = yield* Bus.Service
  106. yield* bus.publish(SessionEvent.Synthetic, {
  107. sessionID,
  108. text: `Instructions from: ${paths[0]}\nprior`,
  109. description: `Loaded ${paths[0]}`,
  110. metadata: { instruction: { paths } },
  111. })
  112. })
  113. describe("SessionInstructions", () => {
  114. it.effect("injects AGENTS.md files above a read, excludes the Location root, and dedups across reads", () =>
  115. Effect.gen(function* () {
  116. const location = yield* Location.Service
  117. const dir = location.directory
  118. const rootPath = path.resolve(dir, "AGENTS.md")
  119. const subPath = path.resolve(dir, "sub", "AGENTS.md")
  120. const deepPath = path.resolve(dir, "sub", "deep", "AGENTS.md")
  121. const otherPath = path.resolve(dir, "sub", "other", "AGENTS.md")
  122. yield* mkdir(path.dirname(deepPath))
  123. yield* mkdir(path.dirname(otherPath))
  124. yield* writeAgents(rootPath, "root-instructions")
  125. yield* writeAgents(subPath, "sub-instructions")
  126. yield* writeAgents(deepPath, "deep-instructions")
  127. yield* writeAgents(otherPath, "other-instructions")
  128. yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "deep", "file.txt"), "file content"))
  129. yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "other", "file2.txt"), "file content 2"))
  130. const session = yield* Session.Service
  131. const registry = yield* Tool.Service
  132. const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
  133. // A read deep under sub/ discovers deep and sub AGENTS.md, walking up to but
  134. // excluding the Location root (already supplied by core initial instructions).
  135. yield* executeTool(registry, readCall(sessionID, "call-deep", "sub/deep/file.txt"))
  136. const firstInjected = yield* synthetics(sessionID)
  137. expect(firstInjected).toHaveLength(1)
  138. expect(firstInjected[0]!.text).toBe(
  139. `Instructions from: ${deepPath}\ndeep-instructions\n\nInstructions from: ${subPath}\nsub-instructions`,
  140. )
  141. expect(firstInjected[0]!.description).toBe(
  142. `Loaded ${path.relative(dir, deepPath)}, ${path.relative(dir, subPath)}`,
  143. )
  144. // The synthetic's metadata carries the durable dedup ledger.
  145. expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [deepPath, subPath] } })
  146. expect(firstInjected[0]!.text).not.toContain("root-instructions")
  147. // A sibling read under sub/other discovers only the new AGENTS.md; sub is already
  148. // injected for this session so it is not re-emitted, and the root is still excluded.
  149. yield* executeTool(registry, readCall(sessionID, "call-other", "sub/other/file2.txt"))
  150. const secondInjected = yield* synthetics(sessionID)
  151. expect(secondInjected).toHaveLength(2)
  152. expect(secondInjected[1]!.text).toBe(`Instructions from: ${otherPath}\nother-instructions`)
  153. expect(secondInjected[1]!.description).toBe(`Loaded ${path.relative(dir, otherPath)}`)
  154. expect(secondInjected[1]!.metadata).toEqual({ instruction: { paths: [otherPath] } })
  155. expect(secondInjected.some((message) => message.text.includes("root-instructions"))).toBe(false)
  156. }),
  157. )
  158. it.effect("does not re-inject paths already recorded in durable session history", () =>
  159. Effect.gen(function* () {
  160. const location = yield* Location.Service
  161. const dir = location.directory
  162. const rootPath = path.resolve(dir, "AGENTS.md")
  163. const subPath = path.resolve(dir, "sub", "AGENTS.md")
  164. yield* mkdir(path.resolve(dir, "sub"))
  165. yield* writeAgents(rootPath, "root-instructions")
  166. yield* writeAgents(subPath, "sub-instructions")
  167. yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "file.txt"), "content"))
  168. const session = yield* Session.Service
  169. const registry = yield* Tool.Service
  170. const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
  171. // Seed the durable history with a prior synthetic that already claims sub's AGENTS.md
  172. // via the instruction metadata ledger.
  173. yield* seedSynthetic(sessionID, [subPath])
  174. expect(yield* synthetics(sessionID)).toHaveLength(1)
  175. yield* executeTool(registry, readCall(sessionID, "call-sub", "sub/file.txt"))
  176. // The durable claim on the prior synthetic prevents re-injection; no new synthetic.
  177. expect(yield* synthetics(sessionID)).toHaveLength(1)
  178. }),
  179. )
  180. it.effect(
  181. "discovers AGENTS.md on a directory listing, including the listed directory's own, and dedups with a later file read",
  182. () =>
  183. Effect.gen(function* () {
  184. const location = yield* Location.Service
  185. const dir = location.directory
  186. const rootPath = path.resolve(dir, "AGENTS.md")
  187. const pkgPath = path.resolve(dir, "packages", "foo", "AGENTS.md")
  188. yield* mkdir(path.resolve(dir, "packages", "foo"))
  189. yield* writeAgents(rootPath, "root-instructions")
  190. yield* writeAgents(pkgPath, "pkg-instructions")
  191. yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "packages", "foo", "file.txt"), "content"))
  192. const session = yield* Session.Service
  193. const registry = yield* Tool.Service
  194. const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
  195. // Listing packages/foo/ discovers its own AGENTS.md, walking up to but excluding
  196. // the Location root (already supplied by core initial instructions).
  197. yield* executeTool(registry, readCall(sessionID, "call-list", "packages/foo"))
  198. const firstInjected = yield* synthetics(sessionID)
  199. expect(firstInjected).toHaveLength(1)
  200. expect(firstInjected[0]!.text).toBe(`Instructions from: ${pkgPath}\npkg-instructions`)
  201. expect(firstInjected[0]!.description).toBe(`Loaded ${path.relative(dir, pkgPath)}`)
  202. expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [pkgPath] } })
  203. expect(firstInjected[0]!.text).not.toContain("root-instructions")
  204. // A subsequent file read under the listed directory is a dedup: pkg's AGENTS.md is
  205. // already injected for this session, so nothing new is emitted.
  206. yield* executeTool(registry, readCall(sessionID, "call-file", "packages/foo/file.txt"))
  207. expect(yield* synthetics(sessionID)).toHaveLength(1)
  208. }),
  209. )
  210. it.effect("listing the Location root directory injects no instructions", () =>
  211. Effect.gen(function* () {
  212. const location = yield* Location.Service
  213. const dir = location.directory
  214. const rootPath = path.resolve(dir, "AGENTS.md")
  215. const subPath = path.resolve(dir, "sub", "AGENTS.md")
  216. yield* mkdir(path.resolve(dir, "sub"))
  217. yield* writeAgents(rootPath, "root-instructions")
  218. yield* writeAgents(subPath, "sub-instructions")
  219. const session = yield* Session.Service
  220. const registry = yield* Tool.Service
  221. const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
  222. // The walk starts and stops at the Location root: the root AGENTS.md is searched but
  223. // dropped by the dirname filter, and up() only walks upward so nested dirs are unseen.
  224. yield* executeTool(registry, readCall(sessionID, "call-root-list", "."))
  225. expect(yield* synthetics(sessionID)).toHaveLength(0)
  226. }),
  227. )
  228. it.effect("loads instructions directly without a read", () =>
  229. Effect.gen(function* () {
  230. const location = yield* Location.Service
  231. const dir = location.directory
  232. const subPath = path.resolve(dir, "sub", "AGENTS.md")
  233. yield* mkdir(path.resolve(dir, "sub"))
  234. yield* writeAgents(subPath, "sub-instructions")
  235. const session = yield* Session.Service
  236. const sessionInstructions = yield* SessionInstructions.Service
  237. const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
  238. yield* sessionInstructions.load({ sessionID, paths: [subPath] })
  239. const injected = yield* synthetics(sessionID)
  240. expect(injected).toHaveLength(1)
  241. expect(injected[0]!.text).toBe(`Instructions from: ${subPath}\nsub-instructions`)
  242. expect(injected[0]!.description).toBe(`Loaded ${path.relative(dir, subPath)}`)
  243. expect(injected[0]!.metadata).toEqual({ instruction: { paths: [subPath] } })
  244. }),
  245. )
  246. test("toLLMMessages does not forward synthetic metadata to the provider", () => {
  247. const created = DateTime.makeUnsafe(0)
  248. const model = Model.Ref.make({ id: Model.ID.make("model"), providerID: Provider.ID.make("provider") })
  249. const synthetic = SessionMessage.Synthetic.make({
  250. id: SessionMessage.ID.make("msg_synthetic"),
  251. type: "synthetic",
  252. text: "Instructions from: /repo/sub/AGENTS.md\ncontent",
  253. description: "Loaded /repo/sub/AGENTS.md",
  254. metadata: { instruction: { paths: ["/repo/sub/AGENTS.md"] } },
  255. time: { created },
  256. })
  257. const messages = toLLMMessages([synthetic], model)
  258. expect(messages).toHaveLength(1)
  259. expect(messages[0]!.role).toBe("user")
  260. expect(messages[0]!.content).toEqual([{ type: "text", text: "Instructions from: /repo/sub/AGENTS.md\ncontent" }])
  261. // Metadata is bookkeeping for the dedup ledger; the model must not see it.
  262. expect(messages[0]!.metadata).toBeUndefined()
  263. })
  264. })