session-instructions.test.ts 14 KB

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