Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/cli/src/server-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,22 @@ 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)
),
file: process.env.OPENCODE_CONFIG,
content: process.env.OPENCODE_CONFIG_CONTENT,
},
instructions: {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In V1, OPENCODE_DISABLE_CLAUDE_CODE_PROMPT only disabled ~/.claude/CLAUDE.md; project CLAUDE.md files stayed on unless OPENCODE_DISABLE_CLAUDE_CODE was set (V1 rules.mdx: "Disable only ~/.claude/CLAUDE.md"). Here both variables go into the same claude flag, so _PROMPT=1 also drops project CLAUDE.md files. To match V1, the global fallback needs its own switch: e.g. instructions.claude set from DISABLE_CLAUDE_CODE only, plus something like instructions.claudeGlobal set from DISABLE_CLAUDE_CODE || DISABLE_CLAUDE_CODE_PROMPT, used only for claudeGlobalFile in instruction.ts. The new instructions.mdx paragraph would need the same update.

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,
},
Expand Down
28 changes: 17 additions & 11 deletions packages/core/src/config/plugin/instruction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [],
Expand All @@ -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)) {
Expand All @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions packages/core/src/instruction-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -40,13 +41,19 @@ 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>
}

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

Expand Down Expand Up @@ -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,
Expand All @@ -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")
}
Expand Down
17 changes: 9 additions & 8 deletions packages/core/src/tool/plugin/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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({
Expand All @@ -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) => {
Expand All @@ -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}` })
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand Down
88 changes: 86 additions & 2 deletions packages/core/test/instruction-discovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)] : [])
Expand All @@ -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({
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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" }])
}),
)
})
2 changes: 2 additions & 0 deletions packages/core/test/session-generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) })
Expand Down
27 changes: 27 additions & 0 deletions packages/core/test/session-instructions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -50,6 +51,7 @@ const readToolNode = makeLocationNode({
Image.node,
Permission.node,
SessionInstructions.node,
InstructionDiscovery.node,
Skill.node,
FSUtil.node,
Environment.node,
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions packages/core/test/session-runner-recorded.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) })
Expand Down
Loading
Loading