Skip to content

Commit ab85ac4

Browse files
feat(config): prefer redcode.json with opencode.json fallback (#32)
* feat(config): prefer redcode.json with opencode.json fallback The global config directory is already `~/.config/redcode/`, but the file inside it was still OpenCode-named, so the effective path read as an accident. Teach every config scope to prefer the Redcode-named file while continuing to accept the OpenCode-named one. Precedence follows the shape the loader already had. A directory's config names are merged, not shadowed — `opencode.json` and `opencode.jsonc` already merged with the later name winning — so `redcode.json` and `redcode.jsonc` are appended to that list rather than replacing it. Both files apply and the Redcode-named one wins the fields they share. Directory proximity still outranks the file name. Nothing is created beside an existing config. The global seed and the `opencode mcp add` target only use a Redcode name when no config exists at all; otherwise the file already on disk is edited in place. Also point the `customize-opencode` skill at `~/.config/redcode/`, which has been the real config directory since the directory rename. Claude-Session: https://claude.ai/code/session_016rycAgbtqsRQH4qBv8nkE7 * fix(core): create redcode.json when hook import has no config to edit `Hook.importClaude` writes into the project's highest-priority config document, which now correctly resolves to a Redcode-named file when one exists. Only a project with no config at all falls through to creating one, and that path still used the OpenCode name — the one remaining place where a brand-new file would be created under the old name. Claude-Session: https://claude.ai/code/session_016rycAgbtqsRQH4qBv8nkE7
1 parent e8295f1 commit ab85ac4

14 files changed

Lines changed: 274 additions & 36 deletions

File tree

‎.changeset/tidy-moons-invite.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
"opencode": patch
3+
---
4+
5+
Prefer `redcode.json` / `redcode.jsonc` for global and project configuration, keeping `opencode.json` / `opencode.jsonc` as a fallback.
6+
7+
The global config directory is already `~/.config/redcode/`, but the file inside it was still OpenCode-named. Both names are now read everywhere, in every scope. Existing configs keep working with no migration and no warning: when a directory holds both names they are merged exactly the way `opencode.json` and `opencode.jsonc` already merge, with the Redcode-named file winning the fields they share. Directory proximity still outranks the file name, so a nested `opencode.json` beats a `redcode.json` further up.
8+
9+
Files are never created beside an existing config. A global config or an `opencode mcp add` target is only written under the Redcode name when no config exists at all; otherwise the file already on disk is edited in place.
10+
11+
The `customize-opencode` skill no longer points the agent at `~/.config/opencode/`, which has not been the config directory since the directory rename.

‎packages/core/src/config.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,11 @@ const layer = Layer.effect(
143143
const global = yield* Global.Service
144144
const location = yield* Location.Service
145145
const policy = yield* Policy.Service
146-
const names = ["opencode.json", "opencode.jsonc"]
146+
// Ordered from lowest to highest precedence. Every name present in a directory is
147+
// loaded and merged, so a Redcode-named file overrides the legacy OpenCode-named
148+
// one field by field rather than replacing it. A directory holding only the
149+
// OpenCode-named file keeps behaving exactly as before.
150+
const names = ["opencode.json", "opencode.jsonc", "redcode.json", "redcode.jsonc"]
147151
const decodeOptions = { errors: "all", onExcessProperty: "ignore", propertyOrder: "original" } as const
148152
const decodeInfo = Schema.decodeUnknownOption(Info, decodeOptions)
149153
const decodeV1Info = Schema.decodeUnknownOption(ConfigV1.Info, decodeOptions)

‎packages/core/src/hook.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,10 @@ const layer = Layer.effect(
176176
!FSUtil.contains(global.config, entry.path) &&
177177
FSUtil.contains(location.project.directory, entry.path),
178178
)
179-
const target = documents.at(-1)?.path ?? path.join(location.project.directory, "opencode.json")
179+
// Prefer the highest-priority config the project already has, whatever it is named, so
180+
// hooks never land in a second file beside an existing one. Only a project with no config
181+
// at all gets one created, under the Redcode name.
182+
const target = documents.at(-1)?.path ?? path.join(location.project.directory, "redcode.json")
180183
const current = (yield* fs.readFileStringSafe(target).pipe(Effect.orDie)) ?? "{}\n"
181184
const next = applyEdits(
182185
current,

‎packages/core/src/plugin/skill.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const Plugin = define({
2020
skill: SkillV2.Info.make({
2121
name: "customize-opencode",
2222
description:
23-
"Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, commands, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.",
23+
"Use ONLY when the user is editing or creating opencode's own configuration: redcode.json, redcode.jsonc, the legacy opencode.json and opencode.jsonc, files under .opencode/, or files under ~/.config/redcode/. Also use when creating or fixing opencode agents, subagents, commands, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.",
2424
location: AbsolutePath.make("/builtin/customize-opencode.md"),
2525
content: CustomizeOpencodeContent,
2626
}),

‎packages/core/src/plugin/skill/customize-opencode.md‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,36 +23,41 @@ shape before writing config, **fetch that URL and read the schema directly**
2323
rather than guessing. opencode hard-fails on invalid config, so the cost of a
2424
wrong shape is a broken startup.
2525

26-
Independently, every `opencode.json` should declare
26+
Independently, every config file should declare
2727
`"$schema": "https://opencode.ai/config.json"` so the user's editor catches
2828
mistakes as they type.
2929

3030
## Applying changes
3131

3232
Config is loaded once when opencode starts and is not hot-reloaded. After
33-
saving changes to `opencode.json`, an agent file, a skill, a plugin, or any
33+
saving changes to the config file, an agent file, a skill, a plugin, or any
3434
other config-time file, **tell the user to quit and restart opencode** for
3535
the changes to take effect. The running session will keep using the
3636
already-loaded config until then.
3737

3838
## Where files live
3939

40-
| Scope | Path |
41-
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
42-
| Project config | `./opencode.json`, `./opencode.jsonc`, or `.opencode/opencode.json` (opencode walks up from the cwd to the worktree root) |
43-
| Global config | `~/.config/opencode/opencode.json` or `~/.config/opencode/opencode.jsonc` (NOT `~/.opencode/`) |
44-
| Project agents | `.opencode/agent/<name>.md` or `.opencode/agents/<name>.md` |
45-
| Global agents | `~/.config/opencode/agent(s)/<name>.md` |
46-
| Project commands | `.opencode/command/<name>.md` or `.opencode/commands/<name>.md` |
47-
| Global commands | `~/.config/opencode/command(s)/<name>.md` |
48-
| Project skills | `.opencode/skill(s)/<name>/SKILL.md` |
49-
| Global skills | `~/.config/opencode/skill(s)/<name>/SKILL.md` |
50-
| External skills (auto-loaded) | `~/.claude/skills/<name>/SKILL.md`, `~/.agents/skills/<name>/SKILL.md` |
40+
| Scope | Path |
41+
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
42+
| Project config | `./redcode.json`, `./redcode.jsonc`, or `.opencode/redcode.json` (opencode walks up from the cwd to the worktree root) |
43+
| Global config | `~/.config/redcode/redcode.json` or `~/.config/redcode/redcode.jsonc` (NOT `~/.opencode/`) |
44+
| Project agents | `.opencode/agent/<name>.md` or `.opencode/agents/<name>.md` |
45+
| Global agents | `~/.config/redcode/agent(s)/<name>.md` |
46+
| Project commands | `.opencode/command/<name>.md` or `.opencode/commands/<name>.md` |
47+
| Global commands | `~/.config/redcode/command(s)/<name>.md` |
48+
| Project skills | `.opencode/skill(s)/<name>/SKILL.md` |
49+
| Global skills | `~/.config/redcode/skill(s)/<name>/SKILL.md` |
50+
| External skills (auto-loaded) | `~/.claude/skills/<name>/SKILL.md`, `~/.agents/skills/<name>/SKILL.md` |
5151

5252
Configs from each scope are deep-merged. Project overrides global. Unknown
53-
top-level keys in `opencode.json` are rejected with `ConfigInvalidError`.
53+
top-level keys in the config file are rejected with `ConfigInvalidError`.
5454

55-
## opencode.json
55+
The legacy `opencode.json` / `opencode.jsonc` names are still read everywhere the
56+
`redcode.*` names are. When a directory holds both, they are merged and the
57+
`redcode.*` file wins. Edit the file that already exists rather than creating a
58+
second one beside it.
59+
60+
## Config file fields
5661

5762
Every field is optional.
5863

‎packages/core/test/config/config.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,112 @@ describe("Config", () => {
209209
),
210210
)
211211

212+
it.live("loads a directory holding only the legacy opencode names exactly as before", () =>
213+
Effect.acquireRelease(
214+
Effect.promise(() => tmpdir()),
215+
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
216+
).pipe(
217+
Effect.flatMap((tmp) =>
218+
Effect.gen(function* () {
219+
yield* Effect.promise(() =>
220+
fs.writeFile(
221+
path.join(tmp.path, "opencode.jsonc"),
222+
JSON.stringify({ $schema: "legacy", providers: { legacy: provider } }),
223+
),
224+
)
225+
return yield* Effect.gen(function* () {
226+
const documents = (yield* (yield* Config.Service).entries()).filter((entry) => entry.type === "document")
227+
228+
expect(documents.map((document) => document.path)).toEqual([path.join(tmp.path, "opencode.jsonc")])
229+
expect(documents.map((document) => document.info.$schema)).toEqual(["legacy"])
230+
expect(documents[0]?.info.providers?.legacy).toBeInstanceOf(ConfigProvider.Info)
231+
}).pipe(Effect.provide(testLayer(tmp.path)))
232+
}),
233+
),
234+
),
235+
)
236+
237+
it.live("merges redcode over opencode names in one directory, redcode last", () =>
238+
Effect.acquireRelease(
239+
Effect.promise(() => tmpdir()),
240+
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
241+
).pipe(
242+
Effect.flatMap((tmp) =>
243+
Effect.gen(function* () {
244+
yield* Effect.promise(() =>
245+
Promise.all([
246+
fs.writeFile(
247+
path.join(tmp.path, "opencode.json"),
248+
JSON.stringify({ $schema: "opencode-json", model: "legacy/json", providers: { legacy: provider } }),
249+
),
250+
fs.writeFile(
251+
path.join(tmp.path, "opencode.jsonc"),
252+
JSON.stringify({ $schema: "opencode-jsonc", default_agent: "legacy" }),
253+
),
254+
fs.writeFile(path.join(tmp.path, "redcode.json"), JSON.stringify({ $schema: "redcode-json" })),
255+
fs.writeFile(
256+
path.join(tmp.path, "redcode.jsonc"),
257+
JSON.stringify({ $schema: "redcode-jsonc", model: "current/jsonc" }),
258+
),
259+
]),
260+
)
261+
return yield* Effect.gen(function* () {
262+
const entries = yield* (yield* Config.Service).entries()
263+
const documents = entries.filter((entry) => entry.type === "document")
264+
265+
expect(documents.map((document) => document.path)).toEqual([
266+
path.join(tmp.path, "opencode.json"),
267+
path.join(tmp.path, "opencode.jsonc"),
268+
path.join(tmp.path, "redcode.json"),
269+
path.join(tmp.path, "redcode.jsonc"),
270+
])
271+
// Every name is merged rather than shadowed, so keys only the legacy files
272+
// define survive while the redcode-named file wins the ones they share.
273+
expect(Config.latest(entries, "model")).toBe("current/jsonc")
274+
expect(Config.latest(entries, "$schema")).toBe("redcode-jsonc")
275+
expect(Config.latest(entries, "default_agent")).toBe("legacy")
276+
expect(Config.latest(entries, "providers")?.legacy).toBeInstanceOf(ConfigProvider.Info)
277+
}).pipe(Effect.provide(testLayer(tmp.path)))
278+
}),
279+
),
280+
),
281+
)
282+
283+
it.live("keeps directory proximity ranked above the file name", () =>
284+
Effect.acquireRelease(
285+
Effect.promise(() => tmpdir()),
286+
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
287+
).pipe(
288+
Effect.flatMap((tmp) => {
289+
const global = path.join(tmp.path, "global")
290+
const root = path.join(tmp.path, "project")
291+
const directory = path.join(root, "packages")
292+
return Effect.gen(function* () {
293+
yield* Effect.promise(async () => {
294+
await fs.mkdir(global, { recursive: true })
295+
await fs.mkdir(directory, { recursive: true })
296+
await Promise.all([
297+
fs.writeFile(path.join(global, "opencode.jsonc"), JSON.stringify({ $schema: "global-legacy" })),
298+
fs.writeFile(path.join(global, "redcode.jsonc"), JSON.stringify({ $schema: "global-current" })),
299+
fs.writeFile(path.join(root, "redcode.jsonc"), JSON.stringify({ $schema: "root-current" })),
300+
fs.writeFile(path.join(directory, "opencode.json"), JSON.stringify({ $schema: "nested-legacy" })),
301+
])
302+
})
303+
304+
return yield* Effect.gen(function* () {
305+
const entries = yield* (yield* Config.Service).entries()
306+
307+
// A nested legacy-named file still beats a redcode-named one higher up, and the
308+
// global directory still loses to both.
309+
expect(
310+
entries.filter((entry) => entry.type === "document").map((document) => document.info.$schema),
311+
).toEqual(["global-legacy", "global-current", "root-current", "nested-legacy"])
312+
}).pipe(Effect.provide(testLayer(directory, global, root)))
313+
})
314+
}),
315+
),
316+
)
317+
212318
it.live("does not load legacy config.json files", () =>
213319
Effect.acquireRelease(
214320
Effect.promise(() => tmpdir()),

‎packages/core/test/hook.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,8 @@ describe("HookV2", () => {
122122
path.join(project.path, "state"),
123123
)
124124
const written = await fs.readFile(path.join(project.path, "opencode.jsonc"), "utf8")
125+
// The existing legacy-named config is edited in place; no redcode.json appears beside it.
126+
expect(result.target).toBe(path.join(project.path, "opencode.jsonc"))
125127
expect(result.imported).toBe(1)
126128
expect(result.restart_required).toBe(true)
127129
expect(written).toContain("// keep me")
@@ -144,7 +146,7 @@ describe("HookV2", () => {
144146
project.path,
145147
path.join(project.path, "state"),
146148
)
147-
expect(result.target).toBe(path.join(project.path, "opencode.json"))
149+
expect(result.target).toBe(path.join(project.path, "redcode.json"))
148150
expect(await fs.readFile(global, "utf8")).toBe(JSON.stringify({ model: "global/model" }))
149151
})
150152
})

‎packages/opencode/src/cli/cmd/mcp.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -392,11 +392,15 @@ export const McpLogoutCommand = effectCmd({
392392
})
393393

394394
async function resolveConfigPath(baseDir: string, global = false) {
395-
// Check for existing config files (prefer .jsonc over .json, check .opencode/ subdirectory too)
396-
const candidates = [path.join(baseDir, "opencode.json"), path.join(baseDir, "opencode.jsonc")]
395+
// Check for existing config files (check the .opencode/ subdirectory too). Redcode names come
396+
// first so that when both exist the edit lands on the file that also wins when config is read;
397+
// a legacy-only directory still gets edited in place rather than gaining a second file, and only
398+
// a directory with no config at all gets a redcode.json created.
399+
const names = ["redcode.json", "redcode.jsonc", "opencode.json", "opencode.jsonc"]
400+
const candidates = names.map((name) => path.join(baseDir, name))
397401

398402
if (!global) {
399-
candidates.push(path.join(baseDir, ".opencode", "opencode.json"), path.join(baseDir, ".opencode", "opencode.jsonc"))
403+
candidates.push(...names.map((name) => path.join(baseDir, ".opencode", name)))
400404
}
401405

402406
for (const candidate of candidates) {
@@ -405,8 +409,8 @@ async function resolveConfigPath(baseDir: string, global = false) {
405409
}
406410
}
407411

408-
// Default to opencode.json if none exist
409-
return candidates[0]
412+
// Default to redcode.json if none exist
413+
return path.join(baseDir, "redcode.json")
410414
}
411415

412416
async function addMcpToConfig(name: string, mcpConfig: ConfigMCPV1.Info, configPath: string) {

‎packages/opencode/src/config/config.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,10 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/Co
137137
export const use = serviceUse(Service)
138138

139139
function globalConfigFile() {
140-
const candidates = ["opencode.jsonc", "opencode.json", "config.json"].map((file) =>
140+
// Highest precedence first: an existing file is always reused, so a user who only has
141+
// the legacy OpenCode-named file keeps writing to it instead of gaining a second file.
142+
// Only a fresh install with no config at all creates the Redcode-named one.
143+
const candidates = ["redcode.jsonc", "redcode.json", "opencode.jsonc", "opencode.json", "config.json"].map((file) =>
141144
path.join(Global.Path.config, file),
142145
)
143146
for (const file of candidates) {
@@ -258,6 +261,8 @@ const layer = Layer.effect(
258261
result = mergeConfig(result, yield* loadFile(path.join(Global.Path.config, "config.json"), env))
259262
result = mergeConfig(result, yield* loadFile(path.join(Global.Path.config, "opencode.json"), env))
260263
result = mergeConfig(result, yield* loadFile(path.join(Global.Path.config, "opencode.jsonc"), env))
264+
result = mergeConfig(result, yield* loadFile(path.join(Global.Path.config, "redcode.json"), env))
265+
result = mergeConfig(result, yield* loadFile(path.join(Global.Path.config, "redcode.jsonc"), env))
261266

262267
const legacy = path.join(Global.Path.config, "config")
263268
if (existsSync(legacy)) {
@@ -404,7 +409,9 @@ const layer = Layer.effect(
404409
}
405410

406411
if (!Flag.OPENCODE_DISABLE_PROJECT_CONFIG) {
407-
for (const file of yield* ConfigPaths.files("opencode", ctx.directory, ctx.worktree).pipe(Effect.orDie)) {
412+
for (const file of yield* ConfigPaths.files(["redcode", "opencode"], ctx.directory, ctx.worktree).pipe(
413+
Effect.orDie,
414+
)) {
408415
yield* merge(file, yield* loadFile(file, authEnv), "local")
409416
}
410417
}
@@ -423,7 +430,7 @@ const layer = Layer.effect(
423430

424431
for (const dir of directories) {
425432
if (dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR) {
426-
for (const file of ["opencode.json", "opencode.jsonc"]) {
433+
for (const file of ["opencode.json", "opencode.jsonc", "redcode.json", "redcode.jsonc"]) {
427434
const source = path.join(dir, file)
428435
yield* Effect.logDebug(`loading config from ${source}`)
429436
yield* merge(source, yield* loadFile(source, authEnv))
@@ -515,7 +522,7 @@ const layer = Layer.effect(
515522

516523
const managedDir = ConfigManaged.managedConfigDir()
517524
if (existsSync(managedDir)) {
518-
for (const file of ["opencode.json", "opencode.jsonc"]) {
525+
for (const file of ["opencode.json", "opencode.jsonc", "redcode.json", "redcode.jsonc"]) {
519526
const source = path.join(managedDir, file)
520527
yield* merge(source, yield* loadFile(source), "global")
521528
}

‎packages/opencode/src/config/paths.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,16 @@ import { unique } from "remeda"
77
import * as Effect from "effect/Effect"
88
import { FSUtil } from "@opencode-ai/core/fs-util"
99

10+
// `names` is ordered from highest to lowest precedence; the reversal at the end turns the
11+
// whole walk into lowest-to-highest so callers can merge it front to back.
1012
export const files = Effect.fn("ConfigPaths.projectFiles")(function* (
11-
name: string,
13+
names: string[],
1214
directory: string,
1315
worktree?: string,
1416
) {
1517
const afs = yield* FSUtil.Service
1618
return (yield* afs.up({
17-
targets: [`${name}.jsonc`, `${name}.json`],
19+
targets: names.flatMap((name) => [`${name}.jsonc`, `${name}.json`]),
1820
start: directory,
1921
stop: worktree,
2022
})).toReversed()

0 commit comments

Comments
 (0)