fix(core): fall back to CLAUDE.md where no AGENTS.md exists (#64474)

Co-authored-by: Aiden Cline <aiden@anoma.ly>
Co-authored-by: neriousy <filip@anoma.ly>
This commit is contained in:
opencode-agent[bot] 2026-11-17 18:05:02 +01:00 • committed by GitHub
parent cbfd30e520
commit 7828491cc9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 208 additions and 32 deletions

View file

@ -124,7 +124,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
project: !truthy(
process.env.OPENCODE_CONFIG_PROJECT_DISABLE ?? process.env.OPENCODE_DISABLE_PROJECT_CONFIG,
),
// .claude is only read for skills, so both flags gate the same roots.
// Config reads .claude only for skills; CLAUDE.md is gated under instructions.
claude: !(
truthy(process.env.OPENCODE_DISABLE_CLAUDE_CODE) ||
truthy(process.env.OPENCODE_DISABLE_CLAUDE_CODE_SKILLS)
@ -132,6 +132,14 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
file: process.env.OPENCODE_CONFIG,
content: process.env.OPENCODE_CONFIG_CONTENT,
},
instructions: {
claude: !truthy(process.env.OPENCODE_DISABLE_CLAUDE_CODE),
// As in V1, the prompt flag only skips ~/.claude/CLAUDE.md.
claudeGlobal: !(
truthy(process.env.OPENCODE_DISABLE_CLAUDE_CODE) ||
truthy(process.env.OPENCODE_DISABLE_CLAUDE_CODE_PROMPT)
),
},
windows: {
gitbash: process.env.OPENCODE_GIT_BASH_PATH,
},

View file

@ -39,6 +39,10 @@ export const Plugin = define({
const project = discovery.project && FSUtil.contains(root, start)
const stop = FSUtil.contains(home, start) ? home : root
const globalFile = yield* fs.resolve(join(global.config, "AGENTS.md"))
// ~/.claude/CLAUDE.md stands in for the global AGENTS.md when it is missing.
const claudeGlobalFile = yield* fs.resolve(join(home, ".claude", "CLAUDE.md"))
const names = InstructionDiscovery.filenames(discovery)
const globalFiles = discovery.claudeGlobal ? [globalFile, claudeGlobalFile] : [globalFile]
const loaded: { current: Loaded } = { current: { type: "available", files: [] } }
const configured: { sources: string[]; remote: Map<string, InstructionDiscovery.File> } = {
sources: [],
@ -49,11 +53,11 @@ export const Plugin = define({
// The ancestor walk can reach the global file when the location sits
// beneath the global config dir; global: false excludes it there too.
const candidates = [
...(discovery.global ? [globalFile] : []),
...(discovery.global ? globalFiles : []),
...(project
? ancestorDirectories(start, stop)
.map((directory) => join(directory, "AGENTS.md"))
.filter((file) => discovery.global || file !== globalFile)
.flatMap((directory) => names.map((name) => join(directory, name)))
.filter((file) => discovery.global || !globalFiles.includes(file))
: []),
]
for (const file of new Set(candidates)) {
@ -76,18 +80,20 @@ export const Plugin = define({
})
const globalSource = Effect.fn("ConfigInstructionPlugin.globalSource")(function* () {
if (!discovery.global || !(yield* fs.isFile(globalFile))) return []
const file = yield* read(globalFile)
return file instanceof InstructionDiscovery.File ? [file] : []
if (!discovery.global) return []
for (const candidate of globalFiles) {
if (!(yield* fs.isFile(candidate))) continue
const file = yield* read(candidate)
return file instanceof InstructionDiscovery.File ? [file] : []
}
return []
})
const projectSource = Effect.fn("ConfigInstructionPlugin.projectSource")(function* () {
if (!project) return []
const walked = yield* Effect.forEach(
yield* fs.up({ targets: ["AGENTS.md"], start, stop, type: "file" }),
fs.resolve,
)
const discovered = new Set(walked.filter((file) => discovery.global || file !== globalFile))
const found = yield* fs.up({ targets: names, start, stop, type: "file" })
const walked = yield* Effect.forEach(InstructionDiscovery.preferAgents(found), fs.resolve)
const discovered = new Set(walked.filter((file) => discovery.global || !globalFiles.includes(file)))
const files = yield* Effect.forEach(discovered, read, { concurrency: "unbounded" })
if (files.some((file) => file === undefined)) return Instructions.unavailable
return files.filter((file) => file instanceof InstructionDiscovery.File)

View file

@ -3,6 +3,7 @@ export * as InstructionDiscovery from "./instruction-discovery.js"
import { Context, Effect, Layer, Schema, Types } from "effect"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { createPatch } from "diff"
import { basename, dirname, join } from "path"
import { Bus } from "./bus.js"
import { Instructions } from "./instructions/index.js"
import { State } from "./state.js"
@ -40,6 +41,10 @@ export interface Interface extends State.Transformable<Editor> {
// Move it into plugin config once plugins can consume their own options.
readonly project: boolean
readonly global: boolean
// Also read CLAUDE.md where no AGENTS.md exists.
readonly claude: boolean
// Read ~/.claude/CLAUDE.md when the global AGENTS.md is missing.
readonly claudeGlobal: boolean
readonly list: () => Effect.Effect<File[] | Instructions.Unavailable>
readonly load: () => Effect.Effect<Instructions.List>
}
@ -47,6 +52,8 @@ export interface Interface extends State.Transformable<Editor> {
export const Options = Schema.Struct({
project: Schema.optional(Schema.Boolean),
global: Schema.optional(Schema.Boolean),
claude: Schema.optional(Schema.Boolean),
claudeGlobal: Schema.optional(Schema.Boolean),
})
export type Options = typeof Options.Type
@ -98,6 +105,8 @@ export const layer = (options?: Options) =>
return Service.of({
project: options?.project !== false,
global: options?.global !== false,
claude: options?.claude !== false,
claudeGlobal: options?.claudeGlobal !== false,
transform: state.transform,
reload: state.reload,
list,
@ -120,6 +129,16 @@ export function configured(options?: Options) {
export const node = configured()
// CLAUDE.md stands in for AGENTS.md in a directory that has none.
export function filenames(discovery: Pick<Interface, "claude">) {
return discovery.claude ? ["AGENTS.md", "CLAUDE.md"] : ["AGENTS.md"]
}
/** Drops each CLAUDE.md whose directory also has an AGENTS.md among `found`. */
export function preferAgents(found: readonly string[]) {
return found.filter((file) => basename(file) !== "CLAUDE.md" || !found.includes(join(dirname(file), "AGENTS.md")))
}
function render(files: ReadonlyArray<File>) {
return files.map((file) => `Instructions from: ${file.path}\n${file.content}`).join("\n\n")
}

View file

@ -10,6 +10,7 @@ import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js"
import { Flag } from "../../flag.js"
import { Location } from "../../location.js"
import { FileAccess } from "../../file-access.js"
import { InstructionDiscovery } from "../../instruction-discovery.js"
import { Permission } from "../../permission.js"
import { SessionInstructions } from "../../session/instructions.js"
import { AbsolutePath } from "../../schema.js"
@ -19,7 +20,6 @@ import { ReadToolFileSystem } from "../read-filesystem.js"
import { Environment } from "../../environment/index.js"
export const name = "read"
const FILENAME = "AGENTS.md"
const LocationInput = Schema.Struct({
path: Schema.String.annotate({ description: "File or directory to read" }),
offset: ReadToolFileSystem.PageInput.fields.offset.annotate({
@ -46,6 +46,7 @@ export const Plugin = {
const config = yield* Config.Service
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload())
const flags = yield* Flag.Service
const discovery = yield* InstructionDiscovery.Service
yield* ctx.tool
.transform((editor) => {
@ -68,8 +69,7 @@ export const Plugin = {
output: ReadToolFileSystem.Output,
execute: (input, context) => {
return Effect.gen(function* () {
if (input.limit === 0)
return yield* new ToolFailure({ message: "Limit must be a positive integer" })
if (input.limit === 0) return yield* new ToolFailure({ message: "Limit must be a positive integer" })
if (Skill.isUri(input.path)) {
const parsed = parseSkillUri(input.path)
if (!parsed) return yield* new ToolFailure({ message: `File not found: ${input.path}` })
@ -143,7 +143,7 @@ export const Plugin = {
}),
),
)
// After a successful read, discover nearby AGENTS.md walking up to the Location
// After a successful read, discover nearby AGENTS.md (or CLAUDE.md) walking up to the Location
// root exclusive and inject them as durable synthetic instructions. For a
// directory listing the walk starts at the directory itself (so its own AGENTS.md
// is discovered); for a file it starts at the file's dirname. External reads are
@ -155,14 +155,15 @@ export const Plugin = {
// The Location and its ancestors are already supplied by initial instructions,
// even when an upward walk from elsewhere in the project cannot reach root.
const discovered = yield* fs.up({
targets: [FILENAME],
targets: InstructionDiscovery.filenames(discovery),
start: result.content.type === "directory" ? resolved : dirname(resolved),
stop: root,
type: "file",
})
const candidates = (yield* Effect.forEach(discovered, fs.resolve)).filter(
(file) => !FSUtil.contains(dirname(file), root) && file !== resolved,
)
const candidates = (yield* Effect.forEach(
InstructionDiscovery.preferAgents(discovered),
fs.resolve,
)).filter((file) => !FSUtil.contains(dirname(file), root) && file !== resolved)
if (candidates.length === 0) return
yield* sessionInstructions.load({ sessionID: context.sessionID, paths: candidates })
}).pipe(

View file

@ -33,6 +33,8 @@ const instructionLayer = (input: {
instructions?: string[]
http?: HttpClient.HttpClient
project?: boolean
claude?: boolean
claudeGlobal?: boolean
}) => {
const watcher = Watcher.testLayer
const config = Config.testLayer(input.instructions ? [configured(input.instructions)] : [])
@ -49,7 +51,13 @@ const instructionLayer = (input: {
]),
[
Config.node.replace(config),
InstructionDiscovery.node.replace(InstructionDiscovery.configured({ project: input.project })),
InstructionDiscovery.node.replace(
InstructionDiscovery.configured({
project: input.project,
claude: input.claude,
claudeGlobal: input.claudeGlobal,
}),
),
Global.node.replace(
input.config || input.home
? Global.layerWith({
@ -223,11 +231,17 @@ describe("ConfigInstructionPlugin.Plugin", () => {
const watcher = yield* Watcher.Test
expect(yield* watcher.subscriptions()).toEqual([
{ path: globalFile, type: "file" },
{ path: path.join(home, ".claude", "CLAUDE.md"), type: "file" },
{ path: packageFile, type: "file" },
{ path: path.join(directory, "CLAUDE.md"), type: "file" },
{ path: path.join(project, "packages", "AGENTS.md"), type: "file" },
{ path: path.join(project, "packages", "CLAUDE.md"), type: "file" },
{ path: projectFile, type: "file" },
{ path: path.join(project, "CLAUDE.md"), type: "file" },
{ path: sharedFile, type: "file" },
{ path: path.join(shared, "CLAUDE.md"), type: "file" },
{ path: path.join(home, "AGENTS.md"), type: "file" },
{ path: path.join(home, "CLAUDE.md"), type: "file" },
])
expect(yield* watcher.subscriptions()).not.toContainEqual({
path: path.join(tmp.path, "AGENTS.md"),
@ -415,6 +429,72 @@ describe("ConfigInstructionPlugin.Plugin", () => {
),
)
it.live("falls back to CLAUDE.md where no AGENTS.md exists", () =>
tmpdirScoped().pipe(
Effect.flatMap((tmp) => {
const global = path.join(tmp.path, "global")
const home = path.join(tmp.path, "home")
const project = path.join(home, "repo")
const directory = path.join(project, "packages", "core")
const claudeGlobal = path.join(home, ".claude", "CLAUDE.md")
const projectAgents = path.join(project, "AGENTS.md")
const packageClaude = path.join(directory, "CLAUDE.md")
const load = (options: { claude?: boolean; claudeGlobal?: boolean } = {}) =>
Effect.gen(function* () {
const discovery = yield* start()
return (yield* readInitial(yield* discovery.load())).text
}).pipe(Effect.provide(layer(options)), Effect.scoped)
const layer = (options: { claude?: boolean; claudeGlobal?: boolean }) =>
instructionLayer({
config: global,
home,
...options,
locationServiceLayer: Layer.succeed(
Location.Service,
Location.Service.of(
location({ directory: AbsolutePath.make(directory) }, { projectDirectory: AbsolutePath.make(project) }),
),
),
})
return Effect.gen(function* () {
yield* Effect.promise(async () => {
await fs.mkdir(path.dirname(claudeGlobal), { recursive: true })
await fs.mkdir(directory, { recursive: true })
await fs.writeFile(claudeGlobal, "claude global")
await fs.writeFile(projectAgents, "project agents")
await fs.writeFile(path.join(project, "CLAUDE.md"), "project claude")
await fs.writeFile(packageClaude, "package claude")
})
expect(yield* load()).toBe(
[
`Instructions from: ${claudeGlobal}\nclaude global`,
`Instructions from: ${packageClaude}\npackage claude`,
`Instructions from: ${projectAgents}\nproject agents`,
].join("\n\n"),
)
// The prompt flag only drops the global fallback, as in V1.
const withoutGlobal = yield* load({ claudeGlobal: false })
expect(withoutGlobal).not.toContain("claude global")
expect(withoutGlobal).toContain(`Instructions from: ${packageClaude}\npackage claude`)
yield* Effect.promise(async () => {
await fs.mkdir(global, { recursive: true })
await fs.writeFile(path.join(global, "AGENTS.md"), "global agents")
})
const preferred = yield* load()
expect(preferred).toContain(`Instructions from: ${path.join(global, "AGENTS.md")}\nglobal agents`)
expect(preferred).not.toContain("claude global")
const disabled = yield* load({ claude: false, claudeGlobal: false })
expect(disabled).not.toContain("CLAUDE.md")
expect(disabled).toContain(`Instructions from: ${projectAgents}\nproject agents`)
})
}),
),
)
it.live("keeps an empty AGENTS.md as available context", () =>
tmpdirScoped().pipe(
Effect.flatMap((tmp) =>
@ -495,9 +575,13 @@ describe("ConfigInstructionPlugin.Plugin", () => {
const watcher = yield* Watcher.Test
expect(yield* watcher.subscriptions()).toEqual([
{ path: path.join(global, "AGENTS.md"), type: "file" },
{ path: path.join(home, ".claude", "CLAUDE.md"), type: "file" },
{ path: path.join(directory, "AGENTS.md"), type: "file" },
{ path: path.join(directory, "CLAUDE.md"), type: "file" },
{ path: path.join(project, "packages", "AGENTS.md"), type: "file" },
{ path: path.join(project, "packages", "CLAUDE.md"), type: "file" },
{ path: path.join(project, "AGENTS.md"), type: "file" },
{ path: path.join(project, "CLAUDE.md"), type: "file" },
])
}).pipe(
Effect.provide(
@ -719,7 +803,7 @@ describe("ConfigInstructionPlugin.Plugin", () => {
)
const repo = path.resolve("/repo")
expect(observed.values).toEqual([{ targets: ["AGENTS.md"], start: repo, stop: repo, type: "file" }])
expect(observed.values).toEqual([{ targets: ["AGENTS.md", "CLAUDE.md"], start: repo, stop: repo, type: "file" }])
}),
)
})

View file

@ -127,6 +127,8 @@ const builtins = Layer.mock(InstructionBuiltIns.Service, {
const discovery = Layer.mock(InstructionDiscovery.Service, {
project: true,
global: true,
claude: true,
claudeGlobal: true,
load: () => Effect.succeed(Instructions.empty),
})
const skills = Layer.mock(SkillInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })

View file

@ -14,6 +14,7 @@ import { Global } from "@opencode/util/global"
import { Image } from "@opencode/core/image"
import { Location } from "@opencode/core/location"
import { FileAccess } from "@opencode/core/file-access"
import { InstructionDiscovery } from "@opencode/core/instruction-discovery"
import { Environment } from "@opencode/core/environment/index"
import { Model } from "@opencode/core/model"
import { Permission } from "@opencode/core/permission"
@ -50,6 +51,7 @@ const readToolNode = makeLocationNode({
Image.node,
Permission.node,
SessionInstructions.node,
InstructionDiscovery.node,
Skill.node,
FSUtil.node,
Environment.node,
@ -196,6 +198,31 @@ describe("SessionInstructions", () => {
}),
)
it.live("falls back to CLAUDE.md above a read where a directory has no AGENTS.md", () =>
Effect.gen(function* () {
const location = yield* Location.Service
const dir = location.directory
const subAgents = path.resolve(dir, "sub", "AGENTS.md")
const deepClaude = path.resolve(dir, "sub", "deep", "CLAUDE.md")
yield* mkdir(path.resolve(dir, "sub", "deep"))
yield* writeAgents(subAgents, "sub-agents")
yield* writeAgents(path.resolve(dir, "sub", "CLAUDE.md"), "sub-claude")
yield* writeAgents(deepClaude, "deep-claude")
yield* Effect.promise(() => fs.writeFile(path.resolve(dir, "sub", "deep", "file.txt"), "content"))
const session = yield* Session.Service
const registry = yield* Tool.Service
const sessionID = (yield* session.create({ location: Location.Ref.make({ directory: dir }) })).id
yield* executeTool(registry, readCall(sessionID, "call-deep", "sub/deep/file.txt"))
const injected = yield* synthetics(sessionID)
expect(injected).toHaveLength(1)
expect(injected[0]!.text).toBe(
`Instructions from: ${deepClaude}\ndeep-claude\n\nInstructions from: ${subAgents}\nsub-agents`,
)
}),
)
it.live("does not re-inject paths already recorded in durable session history", () =>
Effect.gen(function* () {
const location = yield* Location.Service

View file

@ -79,6 +79,8 @@ const systemContext = Layer.mock(InstructionBuiltIns.Service, { load: () => Effe
const instructionContext = Layer.mock(InstructionDiscovery.Service, {
project: true,
global: true,
claude: true,
claudeGlobal: true,
load: () => Effect.succeed(Instructions.empty),
})
const skillInstructions = Layer.mock(SkillInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })

View file

@ -391,6 +391,8 @@ const layer = Layer.unwrap(
const instructionContext = Layer.mock(InstructionDiscovery.Service, {
project: true,
global: true,
claude: true,
claudeGlobal: true,
load: () => Effect.succeed(Instructions.empty),
})
const skillInstructions = Layer.mock(SkillInstructions.Service, {

View file

@ -15,6 +15,7 @@ import { Skill } from "@opencode/core/skill"
import { AbsolutePath } from "@opencode/core/schema"
import { Global } from "@opencode/util/global"
import { FileAccess } from "@opencode/core/file-access"
import { InstructionDiscovery } from "@opencode/core/instruction-discovery"
import { Flag } from "@opencode/core/flag"
import { hostEnvironmentLayer } from "./fixture/environment"
import { location } from "./fixture/location"
@ -39,6 +40,7 @@ const readToolNode = makeLocationNode({
Image.node,
Permission.node,
SessionInstructions.node,
InstructionDiscovery.node,
Skill.node,
FSUtil.node,
Environment.node,
@ -831,9 +833,10 @@ describe("ReadTool", () => {
)
expect(yield* readMissing(tmp.path, "short/ui.ts")).toBe("File not found: short/ui.ts")
// Case-insensitive filesystems, such as macOS by default, simply read the file.
expect([undefined, `File not found: case/readme.md\n\nDid you mean one of these?\n${path.join("case", "README.md")}`]).toContain(
yield* readMissing(tmp.path, "case/readme.md"),
)
expect([
undefined,
`File not found: case/readme.md\n\nDid you mean one of these?\n${path.join("case", "README.md")}`,
]).toContain(yield* readMissing(tmp.path, "case/readme.md"))
}),
),
)

View file

@ -40,6 +40,14 @@ export const ServerOptions = Schema.Struct({
content: Schema.optional(Schema.String),
}),
),
instructions: Schema.optional(
Schema.Struct({
// false skips the per-directory CLAUDE.md fallback.
claude: Schema.optional(Schema.Boolean),
// false skips the ~/.claude/CLAUDE.md fallback.
claudeGlobal: Schema.optional(Schema.Boolean),
}),
),
windows: Schema.optional(
Schema.Struct({
gitbash: Schema.optional(Schema.String),

View file

@ -153,7 +153,13 @@ function makeRoutes<AuthError, AuthServices>(
content: options.config?.content,
}),
),
InstructionDiscovery.node.replace(InstructionDiscovery.configured({ project: options.config?.project })),
InstructionDiscovery.node.replace(
InstructionDiscovery.configured({
project: options.config?.project,
claude: options.instructions?.claude,
claudeGlobal: options.instructions?.claudeGlobal,
}),
),
ShellSelect.node.replace(ShellSelect.configured({ gitbash: options.windows?.gitbash })),
Mcp.node.replace(
Mcp.configured({

View file

@ -38,9 +38,15 @@ Keep guidance that applies everywhere in the global file. Put repository-wide gu
If the workspace is outside the project root, only the global file is loaded. Set `OPENCODE_DISABLE_PROJECT_CONFIG=1` to skip project `AGENTS.md` discovery without disabling the global file.
<Callout type="note">
OpenCode V2 recognizes `AGENTS.md` only. It does not use `CLAUDE.md` as a fallback.
</Callout>
### CLAUDE.md fallback
In any directory without an `AGENTS.md`, OpenCode reads `CLAUDE.md` instead. Without a global
`~/.config/opencode/AGENTS.md`, it reads `~/.claude/CLAUDE.md`. A directory's `AGENTS.md` always wins over its
`CLAUDE.md`, so a symlink between the two loads once.
Set `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1` to skip only `~/.claude/CLAUDE.md`, or `OPENCODE_DISABLE_CLAUDE_CODE=1` to
skip every `CLAUDE.md` and `.claude` skills. The server reads both when it starts. For the background service, persist
them with `opencode service set env` and run `opencode service restart`.
## Discovery

View file

@ -552,9 +552,11 @@ require a V2 rewrite. See [Skills](/skills).
Existing `AGENTS.md` files stay in place. V2 discovers the global `~/.config/opencode/AGENTS.md` and ambient `AGENTS.md`
files from the current directory up to home. For projects outside home, discovery stops at the project root.
If a V1 setup relied on a `CLAUDE.md` fallback, move that guidance into the applicable `AGENTS.md`. V2 currently only
discovers `AGENTS.md`; because non-API V1 behavior is intended to remain compatible, also file a compatibility issue with
the affected project details. See [Instructions](/instructions).
V2 keeps the V1 `CLAUDE.md` fallback: a directory without `AGENTS.md` uses its `CLAUDE.md`, and `~/.claude/CLAUDE.md`
stands in for a missing global `AGENTS.md`. As before, `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` skips only
`~/.claude/CLAUDE.md` and `OPENCODE_DISABLE_CLAUDE_CODE` skips every `CLAUDE.md`. Unlike V1, which stopped at the
first file name found anywhere up the tree, V2 picks per directory, so an `AGENTS.md` at the root no longer hides a
nested `CLAUDE.md`. See [Instructions](/instructions).
## Terminal client configuration