feat(core): make path-local instruction discovery durable

Replace synthetic-message instruction injection with a durable
discovery projection so discovered AGENTS.md files survive compaction,
forks, reverts, and restarts.

- Add the instruction_file table and the durable
  session.instructions.discovered event; projection stores each
  discovered path and content with its owning assistant-message
  boundary and durable discovery order.
- Fold discovered files into the core/instructions source through
  InstructionDiscovery, absorbing SessionInstructions. Completed
  compaction rebaselines restate discovered instructions instead of
  summarizing them away.
- Re-read discovered files live at each observation so mid-session
  edits reach the model; the frozen discovery content stands in only
  when a file becomes unreadable.
- Narrate instruction file changes as per-file deltas via diffByKey,
  restating the full set only for pure reorderings.
- Fork copies discoveries within the inherited transcript, committed
  revert removes discoveries past the revert boundary, and Session
  movement clears them so the destination initializes a complete
  baseline.
This commit is contained in:
Kit Langton 2026-07-06 14:22:53 -04:00
commit 0726f09b05
28 changed files with 1166 additions and 598 deletions

View file

@ -16,6 +16,7 @@ import contextEpochAgentMigration from "@opencode-ai/core/database/migration/202
import simplifyIntegrationCredentialsMigration from "@opencode-ai/core/database/migration/20260611192811_lush_chimera"
import simplifySessionInputMigration from "@opencode-ai/core/database/migration/20260622202450_simplify_session_input"
import renameInstructionsMigration from "@opencode-ai/core/database/migration/20260705180000_rename_instructions"
import addInstructionFileMigration from "@opencode-ai/core/database/migration/20260706181957_add_instruction_file"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { EventV2 } from "@opencode-ai/core/event"
@ -168,6 +169,21 @@ describe("DatabaseMigration", () => {
)
})
test("adds the instruction file table", async () => {
await run(
Effect.gen(function* () {
const db = yield* makeDb
yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY)`)
yield* DatabaseMigration.applyOnly(db, [addInstructionFileMigration])
expect(
yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'instruction_file'`),
).toEqual({ name: "instruction_file" })
}),
)
})
test("keeps legacy credential fields nullable", async () => {
await run(
Effect.gen(function* () {

View file

@ -1,15 +1,24 @@
import { describe, expect } from "bun:test"
import { Effect, Layer } from "effect"
import { DateTime, Effect, Layer, Schema } from "effect"
import fs from "fs/promises"
import path from "path"
import { Database } from "@opencode-ai/core/database/database"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { Global } from "@opencode-ai/core/global"
import { InstructionDiscovery } from "@opencode-ai/core/instruction-discovery"
import { Location } from "@opencode-ai/core/location"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Instructions } from "@opencode-ai/core/instructions"
import { Location } from "@opencode-ai/core/location"
import { ModelV2 } from "@opencode-ai/core/model"
import { Project } from "@opencode-ai/core/project"
import { ProjectTable } from "@opencode-ai/core/project/sql"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { SessionV2 } from "@opencode-ai/core/session"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionProjector } from "@opencode-ai/core/session/projector"
import { InstructionFileTable, SessionMessageTable, SessionTable } from "@opencode-ai/core/session/sql"
import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
@ -27,6 +36,76 @@ const instructionLayer = (input: {
...(input.filesystemLayer ? [[FSUtil.node, input.filesystemLayer] as const] : []),
])
const sessionID = SessionV2.ID.make("ses_instruction_discovery_test")
const assistantMessageID = SessionMessage.ID.make("msg_instruction_discovery")
const durableLayer = (input: { config: string; directory: string }) =>
AppNodeBuilder.build(LayerNode.group([Database.node, InstructionDiscovery.node, SessionProjector.node]), [
[Global.node, Global.layerWith({ config: input.config })],
[
Location.node,
Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(input.directory) }))),
],
])
const withDurableDiscovery = <A, E, R>(
run: (input: { directory: string; config: string; sessionID: SessionV2.ID }) => Effect.Effect<A, E, R>,
) =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
).pipe(
Effect.flatMap((tmp) => {
const directory = path.join(tmp.path, "project")
const config = path.join(tmp.path, "global")
return Effect.promise(() =>
Promise.all([fs.mkdir(directory, { recursive: true }), fs.mkdir(config, { recursive: true })]),
).pipe(
Effect.andThen(
Effect.gen(function* () {
const sessionID = SessionV2.ID.create()
const { db } = yield* Database.Service
yield* db
.insert(ProjectTable)
.values({ id: Project.ID.global, worktree: AbsolutePath.make(directory), sandboxes: [] })
.run()
.pipe(Effect.orDie)
yield* db
.insert(SessionTable)
.values({
id: sessionID,
project_id: Project.ID.global,
slug: sessionID,
directory: AbsolutePath.make(directory),
title: "instruction discovery",
version: "test",
})
.run()
.pipe(Effect.orDie)
const encoded = Schema.encodeSync(SessionMessage.Message)(
SessionMessage.Assistant.make({
id: assistantMessageID,
type: "assistant",
agent: "build",
model: { id: ModelV2.ID.make("model"), providerID: ProviderV2.ID.make("provider") },
content: [],
time: { created: DateTime.makeUnsafe(0) },
}),
)
const { id: _, type, ...data } = encoded
yield* db
.insert(SessionMessageTable)
.values({ id: assistantMessageID, session_id: sessionID, type, seq: 1, time_created: 0, data })
.run()
.pipe(Effect.orDie)
return yield* run({ directory, config, sessionID })
}),
),
Effect.provide(durableLayer({ directory, config })),
)
}),
)
describe("InstructionDiscovery", () => {
it.live("loads global and upward project AGENTS.md files as one aggregate context", () =>
Effect.acquireRelease(
@ -52,7 +131,7 @@ describe("InstructionDiscovery", () => {
})
const load = InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: global,
@ -82,18 +161,14 @@ describe("InstructionDiscovery", () => {
yield* Effect.promise(() => fs.writeFile(packageFile, "changed"))
expect(yield* Instructions.reconcile(yield* load, initialized.applied)).toMatchObject({
_tag: "Updated",
text: expect.stringContaining(`Instructions from: ${packageFile}\nchanged`),
text: `The instructions from ${packageFile} changed to:\nchanged`,
})
yield* Effect.promise(() => fs.rm(packageFile))
const partial = yield* Instructions.reconcile(yield* load, initialized.applied)
expect(partial).toEqual({
_tag: "Updated",
text: [
"These instructions replace all previously loaded ambient instructions.",
`Instructions from: ${globalFile}\nglobal`,
`Instructions from: ${projectFile}\nproject`,
].join("\n\n"),
text: `Instructions from the following files no longer apply: ${packageFile}.`,
applied: expect.any(Object),
})
@ -118,7 +193,7 @@ describe("InstructionDiscovery", () => {
const file = path.join(tmp.path, "AGENTS.md")
yield* Effect.promise(() => fs.writeFile(file, ""))
const context = yield* InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: path.join(tmp.path, "global"),
@ -136,6 +211,132 @@ describe("InstructionDiscovery", () => {
),
)
it.live("stores discovered file content at admission time", () =>
withDurableDiscovery(({ directory, sessionID }) =>
Effect.gen(function* () {
const file = path.join(directory, "src", "AGENTS.md")
yield* Effect.promise(() => fs.mkdir(path.dirname(file), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(file, "frozen"))
const discovery = yield* InstructionDiscovery.Service
yield* discovery.discover({ sessionID, assistantMessageID, paths: [file] })
yield* Effect.promise(() => fs.writeFile(file, "changed"))
const database = yield* Database.Service
expect(yield* database.db.select().from(InstructionFileTable).all().pipe(Effect.orDie)).toMatchObject([
{ session_id: sessionID, path: file, content: "frozen" },
])
}),
),
)
it.live("re-reads discovered files so mid-session edits reach the model", () =>
withDurableDiscovery(({ directory, sessionID }) =>
Effect.gen(function* () {
const file = path.join(directory, "src", "AGENTS.md")
yield* Effect.promise(() => fs.mkdir(path.dirname(file), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(file, "frozen"))
const discovery = yield* InstructionDiscovery.Service
yield* discovery.discover({ sessionID, assistantMessageID, paths: [file] })
const initialized = yield* Instructions.initialize(yield* discovery.load(sessionID))
expect(initialized.text).toContain(`Instructions from: ${file}\nfrozen`)
yield* Effect.promise(() => fs.writeFile(file, "edited"))
expect(yield* Instructions.reconcile(yield* discovery.load(sessionID), initialized.applied)).toMatchObject({
_tag: "Updated",
text: `The instructions from ${file} changed to:\nedited`,
})
}),
),
)
it.live("falls back to frozen content when a discovered file disappears", () =>
withDurableDiscovery(({ directory, sessionID }) =>
Effect.gen(function* () {
const file = path.join(directory, "src", "AGENTS.md")
yield* Effect.promise(() => fs.mkdir(path.dirname(file), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(file, "frozen"))
const discovery = yield* InstructionDiscovery.Service
yield* discovery.discover({ sessionID, assistantMessageID, paths: [file] })
yield* Effect.promise(() => fs.rm(file))
const initialized = yield* Instructions.initialize(yield* discovery.load(sessionID))
expect(initialized.text).toContain(`Instructions from: ${file}\nfrozen`)
}),
),
)
it.live("deduplicates repeated and parallel discovery", () =>
withDurableDiscovery(({ directory, sessionID }) =>
Effect.gen(function* () {
const first = path.join(directory, "one", "AGENTS.md")
const second = path.join(directory, "two", "AGENTS.md")
yield* Effect.promise(() =>
Promise.all([
fs.mkdir(path.dirname(first), { recursive: true }).then(() => fs.writeFile(first, "one")),
fs.mkdir(path.dirname(second), { recursive: true }).then(() => fs.writeFile(second, "two")),
]),
)
const discovery = yield* InstructionDiscovery.Service
yield* Effect.all(
[
discovery.discover({ sessionID, assistantMessageID, paths: [first, first, second] }),
discovery.discover({ sessionID, assistantMessageID, paths: [second, first] }),
discovery.discover({ sessionID, assistantMessageID, paths: [first] }),
],
{ concurrency: "unbounded" },
)
yield* discovery.discover({ sessionID, assistantMessageID, paths: [first, second, first] })
const database = yield* Database.Service
const rows = yield* database.db
.select({ path: InstructionFileTable.path })
.from(InstructionFileTable)
.all()
.pipe(Effect.orDie)
expect(rows.map((row) => row.path).sort()).toEqual([AbsolutePath.make(first), AbsolutePath.make(second)].sort())
}),
),
)
it.live("loads ambient and stored instructions together", () =>
withDurableDiscovery(({ directory, sessionID }) =>
Effect.gen(function* () {
const ambient = path.join(directory, "AGENTS.md")
const stored = path.join(directory, "src", "AGENTS.md")
yield* Effect.promise(() => fs.writeFile(ambient, "ambient"))
yield* Effect.promise(() => fs.mkdir(path.dirname(stored), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(stored, "stored"))
const discovery = yield* InstructionDiscovery.Service
yield* discovery.discover({ sessionID, assistantMessageID, paths: [stored] })
expect((yield* Instructions.initialize(yield* discovery.load(sessionID))).text).toBe(
`Instructions from: ${ambient}\nambient\n\nInstructions from: ${stored}\nstored`,
)
}),
),
)
it.live("does not emit synthetic messages during discovery", () =>
withDurableDiscovery(({ directory, sessionID }) =>
Effect.gen(function* () {
const file = path.join(directory, "src", "AGENTS.md")
yield* Effect.promise(() => fs.mkdir(path.dirname(file), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(file, "stored"))
const discovery = yield* InstructionDiscovery.Service
yield* discovery.discover({ sessionID, assistantMessageID, paths: [file] })
const database = yield* Database.Service
const messages = yield* database.db.select().from(SessionMessageTable).all().pipe(Effect.orDie)
expect(messages.filter((message) => message.type === "synthetic")).toEqual([])
}),
),
)
it.effect("preserves admitted instructions while observation is unavailable", () =>
Effect.gen(function* () {
const failingFS = Layer.effect(
@ -147,7 +348,7 @@ describe("InstructionDiscovery", () => {
),
).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
const context = yield* InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: "/global",
@ -187,7 +388,7 @@ describe("InstructionDiscovery", () => {
),
).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
const context = yield* InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: "/global",
@ -231,7 +432,7 @@ describe("InstructionDiscovery", () => {
).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
yield* InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: "/global",
@ -261,7 +462,7 @@ describe("InstructionDiscovery", () => {
process.env.OPENCODE_DISABLE_PROJECT_CONFIG = "1"
yield* InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: "/global",
@ -293,7 +494,7 @@ describe("InstructionDiscovery", () => {
Effect.gen(function* () {
let scanned = false
yield* InstructionDiscovery.Service.pipe(
Effect.flatMap((service) => service.load()),
Effect.flatMap((service) => service.load(sessionID)),
Effect.provide(
instructionLayer({
config: "/global",

View file

@ -1,319 +0,0 @@
import { describe, expect, test } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { DateTime, Effect, Layer } from "effect"
import { Message } from "@opencode-ai/llm"
import { AgentV2 } from "@opencode-ai/core/agent"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { Config } from "@opencode-ai/core/config"
import { Database } from "@opencode-ai/core/database/database"
import { EventV2 } from "@opencode-ai/core/event"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { Global } from "@opencode-ai/core/global"
import { Image } from "@opencode-ai/core/image"
import { Location } from "@opencode-ai/core/location"
import { LocationMutation } from "@opencode-ai/core/location-mutation"
import { ModelV2 } from "@opencode-ai/core/model"
import { PermissionV2 } from "@opencode-ai/core/permission"
import { ProjectV2 } from "@opencode-ai/core/project"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { ReadTool } from "@opencode-ai/core/tool/read"
import { ReadToolFileSystem } from "@opencode-ai/core/tool/read-filesystem"
import { SessionEvent } from "@opencode-ai/core/session/event"
import { SessionExecution } from "@opencode-ai/core/session/execution"
import { SessionInstructions } from "@opencode-ai/core/session/instructions"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionProjector } from "@opencode-ai/core/session/projector"
import { SessionStore } from "@opencode-ai/core/session/store"
import { SessionV2 } from "@opencode-ai/core/session"
import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message"
import { ToolHooks } from "@opencode-ai/core/tool/hooks"
import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { tempLocationLayer } from "./fixture/location"
import { makeLocationNode } from "@opencode-ai/core/effect/app-node"
import { testEffect } from "./lib/effect"
import { registerToolPlugin, settleTool, testModel } from "./lib/tool"
const readToolNode = makeLocationNode({
name: "test/read-tool-plugin",
layer: Layer.effectDiscard(registerToolPlugin(ReadTool.Plugin)),
deps: [
ToolRegistry.toolsNode,
ReadToolFileSystem.node,
LocationMutation.node,
Image.node,
PermissionV2.node,
SessionInstructions.node,
FSUtil.node,
Location.node,
],
})
const projects = Layer.succeed(
ProjectV2.Service,
ProjectV2.Service.of({
list: () => Effect.succeed([]),
resolve: (directory) => Effect.succeed({ id: ProjectV2.ID.global, directory }),
directories: () => Effect.succeed([]),
commit: () => Effect.void,
}),
)
const permission = Layer.succeed(
PermissionV2.Service,
PermissionV2.Service.of({
assert: () => Effect.void,
ask: () => Effect.die("unused"),
reply: () => Effect.die("unused"),
get: () => Effect.die("unused"),
forSession: () => Effect.die("unused"),
list: () => Effect.die("unused"),
}),
)
const config = Layer.succeed(Config.Service, Config.Service.of({ entries: () => Effect.succeed([]) }))
const imageLayer = AppNodeBuilder.build(Image.node, [[Config.node, config]])
const testLayer = AppNodeBuilder.build(
LayerNode.group([
Database.node,
EventV2.node,
SessionProjector.node,
SessionStore.node,
SessionV2.node,
Location.node,
FSUtil.node,
LocationMutation.node,
ReadToolFileSystem.node,
readToolNode,
ToolRegistry.node,
ToolRegistry.toolsNode,
ToolHooks.node,
SessionInstructions.node,
Global.node,
ToolOutputStore.node,
Image.node,
]),
[
[ProjectV2.node, projects],
[SessionExecution.node, SessionExecution.noopLayer],
[Location.node, tempLocationLayer],
[PermissionV2.node, permission],
[Config.node, config],
[Image.node, imageLayer],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
],
) as unknown as Layer.Layer<unknown>
const it = testEffect(testLayer)
const identity = {
agent: AgentV2.ID.make("build"),
assistantMessageID: SessionMessage.ID.make("msg_nearby"),
}
const readCall = (sessionID: SessionV2.ID, id: string, readPath: string): ToolRegistry.ExecuteInput => ({
sessionID,
...identity,
call: { type: "tool-call", id, name: "read", input: { path: readPath } },
})
const writeAgents = (file: string, content: string) => Effect.promise(() => fs.writeFile(file, content))
const mkdir = (dir: string) => Effect.promise(() => fs.mkdir(dir, { recursive: true }))
const synthetics = (sessionID: SessionV2.ID) =>
Effect.gen(function* () {
const store = yield* SessionStore.Service
return (yield* store.context(sessionID)).filter((message) => message.type === "synthetic")
})
// Seed a prior synthetic message with an instruction dedup ledger, simulating a prior turn
// after the Location layer was reopened (in-memory set empty).
const seedSynthetic = (sessionID: SessionV2.ID, paths: string[]) =>
Effect.gen(function* () {
const events = yield* EventV2.Service
yield* events.publish(SessionEvent.Synthetic, {
sessionID,
text: `Instructions from: ${paths[0]}\nprior`,
description: `Loaded ${paths[0]}`,
metadata: { instruction: { paths } },
})
})
describe("SessionInstructions", () => {
it.effect("injects AGENTS.md files above a read, excludes the Location root, and dedups across reads", () =>
Effect.gen(function* () {
const location = yield* Location.Service
const dir = location.directory
const rootPath = path.resolve(dir, "AGENTS.md")
const subPath = path.resolve(dir, "sub", "AGENTS.md")
const deepPath = path.resolve(dir, "sub", "deep", "AGENTS.md")
const otherPath = path.resolve(dir, "sub", "other", "AGENTS.md")
yield* mkdir(path.dirname(deepPath))
yield* mkdir(path.dirname(otherPath))
yield* writeAgents(rootPath, "root-instructions")
yield* writeAgents(subPath, "sub-instructions")
yield* writeAgents(deepPath, "deep-instructions")
yield* writeAgents(otherPath, "other-instructions")
yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "deep", "file.txt"), "file content"))
yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "other", "file2.txt"), "file content 2"))
const session = yield* SessionV2.Service
const registry = yield* ToolRegistry.Service
const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
// A read deep under sub/ discovers deep and sub AGENTS.md, walking up to but
// excluding the Location root (already supplied by the core/instructions baseline).
yield* settleTool(registry, readCall(sessionID, "call-deep", "sub/deep/file.txt"))
const firstInjected = yield* synthetics(sessionID)
expect(firstInjected).toHaveLength(1)
expect(firstInjected[0]!.text).toBe(
`Instructions from: ${deepPath}\ndeep-instructions\n\nInstructions from: ${subPath}\nsub-instructions`,
)
expect(firstInjected[0]!.description).toBe(
`Loaded ${path.relative(dir, deepPath)}, ${path.relative(dir, subPath)}`,
)
// The synthetic's metadata carries the durable dedup ledger.
expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [deepPath, subPath] } })
expect(firstInjected[0]!.text).not.toContain("root-instructions")
// A sibling read under sub/other discovers only the new AGENTS.md; sub is already
// injected for this session so it is not re-emitted, and the root is still excluded.
yield* settleTool(registry, readCall(sessionID, "call-other", "sub/other/file2.txt"))
const secondInjected = yield* synthetics(sessionID)
expect(secondInjected).toHaveLength(2)
expect(secondInjected[1]!.text).toBe(`Instructions from: ${otherPath}\nother-instructions`)
expect(secondInjected[1]!.description).toBe(`Loaded ${path.relative(dir, otherPath)}`)
expect(secondInjected[1]!.metadata).toEqual({ instruction: { paths: [otherPath] } })
expect(secondInjected.some((message) => message.text.includes("root-instructions"))).toBe(false)
}),
)
it.effect("does not re-inject paths already recorded in durable session history", () =>
Effect.gen(function* () {
const location = yield* Location.Service
const dir = location.directory
const rootPath = path.resolve(dir, "AGENTS.md")
const subPath = path.resolve(dir, "sub", "AGENTS.md")
yield* mkdir(path.resolve(dir, "sub"))
yield* writeAgents(rootPath, "root-instructions")
yield* writeAgents(subPath, "sub-instructions")
yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "file.txt"), "content"))
const session = yield* SessionV2.Service
const registry = yield* ToolRegistry.Service
const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
// Seed the durable history with a prior synthetic that already claims sub's AGENTS.md
// via the instruction metadata ledger.
yield* seedSynthetic(sessionID, [subPath])
expect(yield* synthetics(sessionID)).toHaveLength(1)
yield* settleTool(registry, readCall(sessionID, "call-sub", "sub/file.txt"))
// The durable claim on the prior synthetic prevents re-injection; no new synthetic.
expect(yield* synthetics(sessionID)).toHaveLength(1)
}),
)
it.effect(
"discovers AGENTS.md on a directory listing, including the listed directory's own, and dedups with a later file read",
() =>
Effect.gen(function* () {
const location = yield* Location.Service
const dir = location.directory
const rootPath = path.resolve(dir, "AGENTS.md")
const pkgPath = path.resolve(dir, "packages", "foo", "AGENTS.md")
yield* mkdir(path.resolve(dir, "packages", "foo"))
yield* writeAgents(rootPath, "root-instructions")
yield* writeAgents(pkgPath, "pkg-instructions")
yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "packages", "foo", "file.txt"), "content"))
const session = yield* SessionV2.Service
const registry = yield* ToolRegistry.Service
const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
// Listing packages/foo/ discovers its own AGENTS.md, walking up to but excluding
// the Location root (already supplied by the core/instructions baseline).
yield* settleTool(registry, readCall(sessionID, "call-list", "packages/foo"))
const firstInjected = yield* synthetics(sessionID)
expect(firstInjected).toHaveLength(1)
expect(firstInjected[0]!.text).toBe(`Instructions from: ${pkgPath}\npkg-instructions`)
expect(firstInjected[0]!.description).toBe(`Loaded ${path.relative(dir, pkgPath)}`)
expect(firstInjected[0]!.metadata).toEqual({ instruction: { paths: [pkgPath] } })
expect(firstInjected[0]!.text).not.toContain("root-instructions")
// A subsequent file read under the listed directory is a dedup: pkg's AGENTS.md is
// already injected for this session, so nothing new is emitted.
yield* settleTool(registry, readCall(sessionID, "call-file", "packages/foo/file.txt"))
expect(yield* synthetics(sessionID)).toHaveLength(1)
}),
)
it.effect("listing the Location root directory injects no instructions", () =>
Effect.gen(function* () {
const location = yield* Location.Service
const dir = location.directory
const rootPath = path.resolve(dir, "AGENTS.md")
const subPath = path.resolve(dir, "sub", "AGENTS.md")
yield* mkdir(path.resolve(dir, "sub"))
yield* writeAgents(rootPath, "root-instructions")
yield* writeAgents(subPath, "sub-instructions")
const session = yield* SessionV2.Service
const registry = yield* ToolRegistry.Service
const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
// The walk starts and stops at the Location root: the root AGENTS.md is searched but
// dropped by the dirname filter, and up() only walks upward so nested dirs are unseen.
yield* settleTool(registry, readCall(sessionID, "call-root-list", "."))
expect(yield* synthetics(sessionID)).toHaveLength(0)
}),
)
it.effect("loads instructions directly without a read", () =>
Effect.gen(function* () {
const location = yield* Location.Service
const dir = location.directory
const subPath = path.resolve(dir, "sub", "AGENTS.md")
yield* mkdir(path.resolve(dir, "sub"))
yield* writeAgents(subPath, "sub-instructions")
const session = yield* SessionV2.Service
const sessionInstructions = yield* SessionInstructions.Service
const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
yield* sessionInstructions.load({ sessionID, paths: [subPath] })
const injected = yield* synthetics(sessionID)
expect(injected).toHaveLength(1)
expect(injected[0]!.text).toBe(`Instructions from: ${subPath}\nsub-instructions`)
expect(injected[0]!.description).toBe(`Loaded ${path.relative(dir, subPath)}`)
expect(injected[0]!.metadata).toEqual({ instruction: { paths: [subPath] } })
}),
)
test("toLLMMessages does not forward synthetic metadata to the provider", () => {
const created = DateTime.makeUnsafe(0)
const model = ModelV2.Ref.make({ id: ModelV2.ID.make("model"), providerID: ProviderV2.ID.make("provider") })
const synthetic = SessionMessage.Synthetic.make({
id: SessionMessage.ID.make("msg_synthetic"),
type: "synthetic",
sessionID: SessionV2.ID.make("ses_test"),
text: "Instructions from: /repo/sub/AGENTS.md\ncontent",
description: "Loaded /repo/sub/AGENTS.md",
metadata: { instruction: { paths: ["/repo/sub/AGENTS.md"] } },
time: { created },
})
const messages = toLLMMessages([synthetic], model)
expect(messages).toHaveLength(1)
expect(messages[0]!.role).toBe("user")
expect(messages[0]!.content).toEqual([{ type: "text", text: "Instructions from: /repo/sub/AGENTS.md\ncontent" }])
// Metadata is bookkeeping for the dedup ledger; the model must not see it.
expect(messages[0]!.metadata).toBeUndefined()
})
})

View file

@ -10,6 +10,7 @@ import { ModelV2 } from "@opencode-ai/core/model"
import { Project } from "@opencode-ai/core/project"
import { ProjectTable } from "@opencode-ai/core/project/sql"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { Location } from "@opencode-ai/core/location"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { SessionV2 } from "@opencode-ai/core/session"
import { SessionEvent } from "@opencode-ai/core/session/event"
@ -22,6 +23,7 @@ import { SessionInput } from "@opencode-ai/core/session/input"
import { Shell } from "@opencode-ai/schema/shell"
import {
InstructionCheckpointTable,
InstructionFileTable,
SessionInputTable,
SessionMessageTable,
SessionTable,
@ -50,6 +52,15 @@ const assistantRow = (
return { id, session_id: sessionID, type, seq, time_created: DateTime.toEpochMillis(time.created), data }
}
const systemRow = (id: SessionMessage.ID, seq: number) => {
const {
id: _,
type,
...data
} = encodeMessage(SessionMessage.System.make({ id, type: "system", text: "historical update", time: { created } }))
return { id, session_id: sessionID, type, seq, time_created: DateTime.toEpochMillis(created), data }
}
describe("SessionProjector", () => {
it.effect("projects staged, cleared, and committed reverts", () =>
Effect.gen(function* () {
@ -111,6 +122,218 @@ describe("SessionProjector", () => {
}),
)
it.effect("copies only instruction files admitted within a fork boundary", () =>
Effect.gen(function* () {
const db = (yield* Database.Service).db
yield* db
.insert(ProjectTable)
.values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
.run()
yield* db
.insert(SessionTable)
.values({
id: sessionID,
project_id: Project.ID.global,
slug: "test",
directory: "/project",
title: "test",
version: "test",
})
.run()
const boundary = SessionMessage.ID.make("msg_fork_boundary")
yield* db
.insert(SessionMessageTable)
.values([
assistantRow(SessionMessage.ID.make("msg_copied"), 2),
systemRow(SessionMessage.ID.make("msg_instruction_update"), 3),
assistantRow(boundary, 4),
])
.run()
yield* db
.insert(InstructionCheckpointTable)
.values({ session_id: sessionID, baseline: "future", snapshot: {}, baseline_seq: 4 })
.run()
yield* db
.insert(InstructionFileTable)
.values([
{
session_id: sessionID,
path: AbsolutePath.make("/project/early.md"),
content: "early",
message_seq: 1,
discovered_seq: 1,
position: 0,
},
{
session_id: sessionID,
path: AbsolutePath.make("/project/edge.md"),
content: "edge",
message_seq: 2,
discovered_seq: 2,
position: 1,
},
{
session_id: sessionID,
path: AbsolutePath.make("/project/late.md"),
content: "late",
message_seq: 4,
discovered_seq: 3,
position: 2,
},
])
.run()
const forkedID = SessionV2.ID.make("ses_projector_fork")
const events = yield* EventV2.Service
yield* events.publish(SessionEvent.Forked, {
sessionID: forkedID,
parentID: sessionID,
from: boundary,
})
expect(
yield* db
.select({ path: InstructionFileTable.path, message_seq: InstructionFileTable.message_seq })
.from(InstructionFileTable)
.where(eq(InstructionFileTable.session_id, forkedID))
.orderBy(asc(InstructionFileTable.message_seq))
.all(),
).toEqual([
{ path: AbsolutePath.make("/project/early.md"), message_seq: 1 },
{ path: AbsolutePath.make("/project/edge.md"), message_seq: 2 },
])
expect(
yield* db
.select()
.from(InstructionCheckpointTable)
.where(eq(InstructionCheckpointTable.session_id, forkedID))
.get(),
).toBeUndefined()
expect(
yield* db
.select({ type: SessionMessageTable.type })
.from(SessionMessageTable)
.where(eq(SessionMessageTable.session_id, forkedID))
.all(),
).toEqual([{ type: "assistant" }])
}),
)
it.effect("clears admitted instruction files when a session moves", () =>
Effect.gen(function* () {
const db = (yield* Database.Service).db
yield* db
.insert(ProjectTable)
.values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
.run()
yield* db
.insert(SessionTable)
.values({
id: sessionID,
project_id: Project.ID.global,
slug: "test",
directory: "/project",
title: "test",
version: "test",
})
.run()
yield* db
.insert(InstructionFileTable)
.values({
session_id: sessionID,
path: AbsolutePath.make("/project/AGENTS.md"),
content: "instructions",
message_seq: 1,
discovered_seq: 1,
position: 0,
})
.run()
const events = yield* EventV2.Service
yield* events.publish(SessionEvent.Moved, {
sessionID,
location: Location.Ref.make({ directory: AbsolutePath.make("/moved") }),
})
expect(
yield* db.select().from(InstructionFileTable).where(eq(InstructionFileTable.session_id, sessionID)).all(),
).toEqual([])
}),
)
it.effect("removes only instruction files admitted after a committed revert boundary", () =>
Effect.gen(function* () {
const db = (yield* Database.Service).db
yield* db
.insert(ProjectTable)
.values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
.run()
yield* db
.insert(SessionTable)
.values({
id: sessionID,
project_id: Project.ID.global,
slug: "test",
directory: "/project",
title: "test",
version: "test",
})
.run()
const boundary = SessionMessage.ID.make("msg_instruction_boundary")
yield* db
.insert(SessionMessageTable)
.values([assistantRow(boundary, 2), assistantRow(SessionMessage.ID.make("msg_instruction_later"), 4)])
.run()
yield* db
.insert(InstructionFileTable)
.values([
{
session_id: sessionID,
path: AbsolutePath.make("/project/early.md"),
content: "early",
message_seq: 1,
discovered_seq: 1,
position: 0,
},
{
session_id: sessionID,
path: AbsolutePath.make("/project/edge.md"),
content: "edge",
message_seq: 2,
discovered_seq: 2,
position: 1,
},
{
session_id: sessionID,
path: AbsolutePath.make("/project/late.md"),
content: "late",
message_seq: 3,
discovered_seq: 3,
position: 2,
},
])
.run()
const events = yield* EventV2.Service
yield* events.publish(SessionEvent.RevertEvent.Committed, {
sessionID,
messageID: boundary,
})
expect(
yield* db
.select({ path: InstructionFileTable.path, message_seq: InstructionFileTable.message_seq })
.from(InstructionFileTable)
.where(eq(InstructionFileTable.session_id, sessionID))
.orderBy(asc(InstructionFileTable.message_seq))
.all(),
).toEqual([
{ path: AbsolutePath.make("/project/early.md"), message_seq: 1 },
{ path: AbsolutePath.make("/project/edge.md"), message_seq: 2 },
])
}),
)
it.effect("orders projected messages and context by durable aggregate sequence", () =>
Effect.gen(function* () {
const { db } = yield* Database.Service

View file

@ -73,8 +73,10 @@ const model = OpenAIChat.route
})
.model({ id: "gpt-4o-mini" })
const models = SessionRunnerModel.layerWith(() => Effect.succeed(SessionRunnerModel.resolved(model)))
const systemContext = Layer.mock(InstructionBuiltIns.Service, { load: () => Effect.succeed(Instructions.empty) })
const instructionContext = Layer.mock(InstructionDiscovery.Service, { load: () => Effect.succeed(Instructions.empty) })
const instructionBuiltIns = Layer.mock(InstructionBuiltIns.Service, { load: () => Effect.succeed(Instructions.empty) })
const instructionDiscovery = Layer.mock(InstructionDiscovery.Service, {
load: (_sessionID) => Effect.succeed(Instructions.empty),
})
const skillGuidance = Layer.mock(SkillGuidance.Service, { load: () => Effect.succeed(Instructions.empty) })
const referenceGuidance = Layer.mock(ReferenceGuidance.Service, { load: () => Effect.succeed(Instructions.empty) })
const mcpGuidance = Layer.mock(McpGuidance.Service, { load: () => Effect.succeed(Instructions.empty) })
@ -83,8 +85,8 @@ const runnerLayer = AppNodeBuilder.build(SessionRunnerLLM.node, [
[Snapshot.node, Snapshot.noopLayer],
[LayerNodePlatform.llmClient, client],
[SessionRunnerModel.node, models],
[InstructionBuiltIns.node, systemContext],
[InstructionDiscovery.node, instructionContext],
[InstructionBuiltIns.node, instructionBuiltIns],
[InstructionDiscovery.node, instructionDiscovery],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
[SkillGuidance.node, skillGuidance],
[ReferenceGuidance.node, referenceGuidance],
@ -133,8 +135,8 @@ const it = testEffect(
[PermissionV2.node, permission],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
[SessionRunnerModel.node, models],
[InstructionBuiltIns.node, systemContext],
[InstructionDiscovery.node, instructionContext],
[InstructionBuiltIns.node, instructionBuiltIns],
[InstructionDiscovery.node, instructionDiscovery],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
[SkillGuidance.node, skillGuidance],
[ReferenceGuidance.node, referenceGuidance],

View file

@ -1,4 +1,6 @@
import { describe, expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import {
LLMClient,
LLMError,
@ -44,6 +46,7 @@ import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
import { AgentV2 } from "@opencode-ai/core/agent"
import { Config } from "@opencode-ai/core/config"
import { ConfigCompaction } from "@opencode-ai/core/config/compaction"
import { Global } from "@opencode-ai/core/global"
import { Tool } from "@opencode-ai/core/tool/tool"
import {
InstructionCheckpointTable,
@ -65,6 +68,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider"
import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Schema, Stream } from "effect"
import { asc, eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
import { tmpdir } from "./fixture/tmpdir"
const requests: LLMRequest[] = []
let response: LLMEvent[] = []
@ -207,7 +211,9 @@ const systemContext = Layer.mock(InstructionBuiltIns.Service, {
),
),
})
const instructionContext = Layer.mock(InstructionDiscovery.Service, { load: () => Effect.succeed(Instructions.empty) })
const instructionContext = Layer.mock(InstructionDiscovery.Service, {
load: (_sessionID) => Effect.succeed(Instructions.empty),
})
const skillGuidance = Layer.mock(SkillGuidance.Service, {
load: (agent) =>
Effect.succeed(
@ -242,76 +248,80 @@ const config = Layer.succeed(
]),
}),
)
const runnerLayer = AppNodeBuilder.build(SessionRunnerLLM.node, [
[Snapshot.node, Snapshot.noopLayer],
[LayerNodePlatform.llmClient, client],
[SessionRunnerModel.node, models],
[InstructionBuiltIns.node, systemContext],
[InstructionDiscovery.node, instructionContext],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
[SkillGuidance.node, skillGuidance],
[ReferenceGuidance.node, referenceGuidance],
[PermissionV2.node, permission],
[Config.node, config],
[McpGuidance.node, mcpGuidance],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
const makeRunnerLayer = (discovery?: typeof instructionContext) =>
AppNodeBuilder.build(SessionRunnerLLM.node, [
[Snapshot.node, Snapshot.noopLayer],
[LayerNodePlatform.llmClient, client],
[SessionRunnerModel.node, models],
[InstructionBuiltIns.node, systemContext],
...(discovery ? [[InstructionDiscovery.node, discovery] as const] : []),
[Global.node, Global.layerWith({ config: "/nonexistent/opencode-test-config" })],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
[SkillGuidance.node, skillGuidance],
[ReferenceGuidance.node, referenceGuidance],
[PermissionV2.node, permission],
[Config.node, config],
[McpGuidance.node, mcpGuidance],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
])
const makeExecution = (runnerLayer: ReturnType<typeof makeRunnerLayer>) =>
Layer.effect(
SessionExecution.Service,
Effect.gen(function* () {
const sessionRunner = yield* SessionRunner.Service
const coordinator = yield* SessionRunCoordinator.make<SessionV2.ID, SessionRunner.RunError>({
drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }),
})
return SessionExecution.Service.of({
active: coordinator.active,
resume: coordinator.run,
wake: coordinator.wake,
interrupt: coordinator.interrupt,
awaitIdle: coordinator.awaitIdle,
})
}),
).pipe(Layer.provide(runnerLayer))
const testNode = LayerNode.group([
Database.node,
EventV2.node,
Form.node,
SessionProjector.node,
SessionStore.node,
AgentV2.node,
ToolRegistry.node,
ToolRegistry.toolsNode,
echoNode,
SessionRunnerModel.node,
InstructionBuiltIns.node,
InstructionDiscovery.node,
InstructionEntry.node,
SkillGuidance.node,
ReferenceGuidance.node,
Config.node,
Snapshot.node,
SessionRunnerLLM.node,
SessionExecution.node,
SessionV2.node,
])
const execution = Layer.effect(
SessionExecution.Service,
Effect.gen(function* () {
const sessionRunner = yield* SessionRunner.Service
const coordinator = yield* SessionRunCoordinator.make<SessionV2.ID, SessionRunner.RunError>({
drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }),
})
return SessionExecution.Service.of({
active: coordinator.active,
resume: coordinator.run,
wake: coordinator.wake,
interrupt: coordinator.interrupt,
awaitIdle: coordinator.awaitIdle,
})
}),
).pipe(Layer.provide(runnerLayer))
const it = testEffect(
AppNodeBuilder.build(
LayerNode.group([
Database.node,
EventV2.node,
Form.node,
SessionProjector.node,
SessionStore.node,
AgentV2.node,
ToolRegistry.node,
ToolRegistry.toolsNode,
echoNode,
SessionRunnerModel.node,
InstructionBuiltIns.node,
InstructionDiscovery.node,
InstructionEntry.node,
SkillGuidance.node,
ReferenceGuidance.node,
Config.node,
Snapshot.node,
SessionRunnerLLM.node,
SessionExecution.node,
SessionV2.node,
]),
[
[LayerNodePlatform.llmClient, client],
[PermissionV2.node, permission],
[SessionRunnerModel.node, models],
[InstructionBuiltIns.node, systemContext],
[InstructionDiscovery.node, instructionContext],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
[SkillGuidance.node, skillGuidance],
[ReferenceGuidance.node, referenceGuidance],
[Snapshot.node, Snapshot.noopLayer],
[SessionExecution.node, execution],
[Config.node, config],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
],
),
)
const makeTestLayer = (discovery: typeof instructionContext | undefined, execution: ReturnType<typeof makeExecution>) =>
AppNodeBuilder.build(testNode, [
[LayerNodePlatform.llmClient, client],
[PermissionV2.node, permission],
[SessionRunnerModel.node, models],
[InstructionBuiltIns.node, systemContext],
...(discovery ? [[InstructionDiscovery.node, discovery] as const] : []),
[Global.node, Global.layerWith({ config: "/nonexistent/opencode-test-config" })],
[Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
[SkillGuidance.node, skillGuidance],
[ReferenceGuidance.node, referenceGuidance],
[Snapshot.node, Snapshot.noopLayer],
[SessionExecution.node, execution],
[Config.node, config],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
])
const runnerLayer = makeRunnerLayer(instructionContext)
const it = testEffect(makeTestLayer(instructionContext, makeExecution(runnerLayer)))
const integrationIt = testEffect(makeTestLayer(undefined, makeExecution(makeRunnerLayer())))
const sessionID = SessionV2.ID.make("ses_runner_test")
const otherSessionID = SessionV2.ID.make("ses_runner_other")
@ -858,6 +868,53 @@ describe("SessionRunnerLLM", () => {
}),
)
integrationIt.live("admits persisted path-local instructions as a chronological System update", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
).pipe(
Effect.flatMap((tmp) =>
Effect.gen(function* () {
yield* setup
const session = yield* SessionV2.Service
const discovery = yield* InstructionDiscovery.Service
yield* session.prompt({ sessionID, prompt: PromptInput.Prompt.make({ text: "First" }), resume: false })
requests.length = 0
response = fragmentFixture("text", "text-instruction-discovery", ["Done"]).completeEvents
yield* session.resume(sessionID)
const assistantMessageID = (yield* session.context(sessionID)).findLast(
(message): message is SessionMessage.Assistant => message.type === "assistant",
)?.id
if (!assistantMessageID) return yield* Effect.die(new Error("Expected an assistant message"))
const file = path.join(tmp.path, "src", "AGENTS.md")
yield* Effect.promise(() => fs.mkdir(path.dirname(file), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(file, "Persisted path-local instructions"))
yield* discovery.discover({ sessionID, assistantMessageID, paths: [file] })
yield* Effect.promise(() => fs.writeFile(file, "Changed after discovery"))
yield* session.prompt({ sessionID, prompt: PromptInput.Prompt.make({ text: "Second" }), resume: false })
yield* session.resume(sessionID)
// Discovery records the path durably; observation re-reads content live,
// so the post-discovery edit is what the model gets told.
const update = `Instructions from: ${file}\nChanged after discovery`
expect(requests[1]?.messages.map((message) => message.role)).toEqual(["user", "assistant", "system", "user"])
expect(requests[1]?.messages.at(2)?.content).toEqual([{ type: "text", text: update }])
expect((yield* session.context(sessionID)).map((message) => message.type)).toEqual([
"user",
"assistant",
"system",
"user",
"assistant",
])
expect(yield* recordedEventTypes(sessionID)).toContain("session.instructions.updated.1")
expect(yield* recordedEventTypes(sessionID)).not.toContain("session.synthetic.1")
}),
),
),
)
it.effect("uses the selected model family prompt when the agent does not override it", () =>
Effect.gen(function* () {
yield* setup

View file

@ -20,7 +20,8 @@ import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
import { ReadTool } from "@opencode-ai/core/tool/read"
import { ReadToolFileSystem } from "@opencode-ai/core/tool/read-filesystem"
import { makeLocationNode } from "@opencode-ai/core/effect/app-node"
import { SessionInstructions } from "@opencode-ai/core/session/instructions"
import { InstructionDiscovery } from "@opencode-ai/core/instruction-discovery"
import { Instructions } from "@opencode-ai/core/instructions"
import { testEffect } from "./lib/effect"
import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool"
@ -33,7 +34,7 @@ const readToolNode = makeLocationNode({
LocationMutation.node,
Image.node,
PermissionV2.node,
SessionInstructions.node,
InstructionDiscovery.node,
FSUtil.node,
Location.node,
],
@ -47,6 +48,8 @@ const readCalls: {
page: ReadToolFileSystem.PageInput
}[] = []
const listCalls: ReadToolFileSystem.PageInput[] = []
const discoveredInstructions: string[][] = []
let instructionPaths: string[] = []
let resolvedType: "file" | "directory" = "file"
let resolveFailure: unknown
let readResult: FileSystem.Content | ReadToolFileSystem.TextPage = {
@ -108,6 +111,7 @@ const testFileSystem = Layer.effect(
}),
)
: Effect.succeed(path),
up: () => Effect.succeed(instructionPaths),
}),
),
),
@ -146,6 +150,10 @@ const unavailableImage = Layer.succeed(
Image.Service,
Image.Service.of({ normalize: () => Effect.fail(new Image.ResizerUnavailableError()) }),
)
const instructionDiscovery = Layer.mock(InstructionDiscovery.Service, {
load: (_sessionID) => Effect.succeed(Instructions.empty),
discover: (input) => Effect.sync(() => void discoveredInstructions.push([...input.paths])),
})
const readLayer = (imageLayer: Layer.Layer<Image.Service>) =>
AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, readToolNode]), [
[ReadToolFileSystem.node, reader],
@ -155,6 +163,7 @@ const readLayer = (imageLayer: Layer.Layer<Image.Service>) =>
[LocationMutation.node, mutation],
[FSUtil.node, testFileSystem],
[Location.node, locationLayer],
[InstructionDiscovery.node, instructionDiscovery],
[Global.node, Global.layerWith({ data: Global.Path.data })],
[ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
])
@ -167,6 +176,8 @@ describe("ReadTool", () => {
assertions.length = 0
readCalls.length = 0
listCalls.length = 0
discoveredInstructions.length = 0
instructionPaths = []
allow = true
resolvedType = "file"
resolveFailure = undefined
@ -678,6 +689,7 @@ describe("ReadTool", () => {
mime: "application/octet-stream",
}
const registry = yield* ToolRegistry.Service
instructionPaths = [path.join(process.cwd(), "sub", "AGENTS.md")]
expect(
yield* executeTool(registry, {
@ -686,6 +698,7 @@ describe("ReadTool", () => {
call: { type: "tool-call", id: "call-direct-binary", name: "read", input: { path: "late-binary" } },
}),
).toEqual({ type: "error", value: "Cannot read binary file: late-binary" })
expect(discoveredInstructions).toEqual([])
}),
)
})