session-instructions.test.ts 14 KB

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