[FEATURE]: Context Auto-Discovery: Load AGENTS.md from Directories When Accessing Files #3943

Open
opened 2026-02-16 17:42:02 -05:00 by yindo · 14 comments
Owner

Originally created by @Ithril-Laydec on GitHub (Dec 28, 2025).

Originally assigned to: @thdxr on GitHub.

Feature hasn't been suggested before.

  • I have verified this feature I'm about to request hasn't been suggested before.

Describe the enhancement you want to request

Problem

In large monorepos, we have to choose what information to load into context. With a large AGENTS.md file, we load a lot of context that might not be necessary for all conversations.

Typical structure example:

monorepo/
├── AGENTS.md              # Global project rules
├── packages/
│   ├── backend/
│   │   ├── src/
│   │   └── AGENTS.md      # Backend-specific rules
│   ├── frontend/
│   │   ├── src/
│   │   └── AGENTS.md      # Frontend-specific rules
│   └── mobile/
│       ├── src/
│       └── AGENTS.md      # Mobile-specific rules

Current workaround: Manually list all instruction files in opencode.json:

{
  "instructions": [
    "AGENTS.md",
    "packages/backend/AGENTS.md",
    "packages/frontend/AGENTS.md",
    "packages/mobile/AGENTS.md"
  ]
}

Problem with this approach: This loads ALL instruction files at startup, overloading the context with irrelevant information (e.g., loading mobile rules when working on backend code). This doesn't scale and defeats the purpose of having per-module context.


Proposed Solution

Mimic Claude Code's auto-discovery so that when a file is read or written in a subdirectory, the relevant AGENTS.md is automatically loaded without the LLM having to manually decide to read it.

Features:

  1. Loaded file cache to avoid duplicates in the same session
  2. Configuration option to disable the feature if not desired
  3. Two loading strategies:
    • "up": Search for AGENTS.md upward to the worktree (default)
    • "exact": Only load AGENTS.md from the exact file directory

Advanced Configuration

{
  "autoDiscovery": {
    "enabled": true,
    "patterns": ["AGENTS.md", "CLAUDE.md"],
    "strategy": "up" // "up" | "exact"
  }
}

Why This Matters

  • Zero-config: Works without configuration for standard project structures
  • Automatic scalability: No need to update config when adding modules
  • Better context accuracy: LLM receives relevant instructions automatically
  • Monorepo support: Essential for modern architectures (Next.js, Turborepo, Nx)
  • Parity with Claude Code: Users expect similar behavior across AI coding tools

Step-by-Step Flow: "up" Strategy (Search Upward)

Structure:
monorepo/
├── AGENTS.md                    # [A] Global rules
├── packages/
│   └── backend/
│       ├── AGENTS.md            # [B] Backend rules
│       └── routes/
│           ├── AGENTS.md        # [C] Routes rules
│           └── auth.ts          # ← File being read

LLM: readFile("packages/backend/routes/auth.ts")

Step 1: Detect directory → "packages/backend/routes/"
Step 2: Search upward:
  → packages/backend/routes/AGENTS.md  ✅ [C] Found! → Load
  → packages/backend/AGENTS.md         ✅ [B] Found! → Load
  → packages/AGENTS.md                 ❌ Does not exist
  → AGENTS.md                          ✅ [A] Already loaded by system

Result: LLM receives context from [C] + [B] + [A]

Step-by-Step Flow: "exact" Strategy (Current Directory Only)

Same structure as before:
monorepo/
├── AGENTS.md                    # [A] Global rules
├── packages/
│   └── backend/
│       ├── AGENTS.md            # [B] Backend rules
│       └── routes/
│           ├── AGENTS.md        # [C] Routes rules
│           └── auth.ts          # ← File being read

LLM: readFile("packages/backend/routes/auth.ts")

Step 1: Detect directory → "packages/backend/routes/"
Step 2: Search ONLY in that directory:
  → packages/backend/routes/AGENTS.md  ✅ [C] Found! → Load
  → (Does NOT search in parent directories)

Result: LLM receives context from [C] + [A] (root already loaded)

When to use each strategy?

  • "up" (recommended): When you want the LLM to have full module + submodule context
  • "exact": When each subdirectory has completely independent context and you don't want to "inherit" rules from parent folders

Difference with #4479

I've read issue #4479 and consider this proposal to be complementary but not the same:

  • #4479: Vertical search outside the git root (for monorepos with AGENTS.md in parent folders)
  • This proposal: Horizontal search within the project (for modules with their own context)

Both features can coexist and solve different use cases in complex monorepos.


Implementation Offer

If this sounds good, I'd like to implement it myself or help implement it.


Originally created by @Ithril-Laydec on GitHub (Dec 28, 2025). Originally assigned to: @thdxr on GitHub. ### Feature hasn't been suggested before. - [x] I have verified this feature I'm about to request hasn't been suggested before. ### Describe the enhancement you want to request ## Problem In large monorepos, we have to choose what information to load into context. With a large AGENTS.md file, we load a lot of context that might not be necessary for all conversations. **Typical structure example:** ``` monorepo/ ├── AGENTS.md # Global project rules ├── packages/ │ ├── backend/ │ │ ├── src/ │ │ └── AGENTS.md # Backend-specific rules │ ├── frontend/ │ │ ├── src/ │ │ └── AGENTS.md # Frontend-specific rules │ └── mobile/ │ ├── src/ │ └── AGENTS.md # Mobile-specific rules ``` **Current workaround:** Manually list all instruction files in `opencode.json`: ```json { "instructions": [ "AGENTS.md", "packages/backend/AGENTS.md", "packages/frontend/AGENTS.md", "packages/mobile/AGENTS.md" ] } ``` **Problem with this approach:** This loads ALL instruction files at startup, overloading the context with irrelevant information (e.g., loading mobile rules when working on backend code). This doesn't scale and defeats the purpose of having per-module context. --- ## Proposed Solution Mimic Claude Code's auto-discovery so that when a file is read or written in a subdirectory, the relevant AGENTS.md is automatically loaded without the LLM having to manually decide to read it. **Features:** 1. **Loaded file cache** to avoid duplicates in the same session 2. **Configuration option** to disable the feature if not desired 3. **Two loading strategies**: - `"up"`: Search for AGENTS.md upward to the worktree (default) - `"exact"`: Only load AGENTS.md from the exact file directory --- ## Advanced Configuration ```json { "autoDiscovery": { "enabled": true, "patterns": ["AGENTS.md", "CLAUDE.md"], "strategy": "up" // "up" | "exact" } } ``` --- ## Why This Matters - ✅ **Zero-config**: Works without configuration for standard project structures - ✅ **Automatic scalability**: No need to update config when adding modules - ✅ **Better context accuracy**: LLM receives relevant instructions automatically - ✅ **Monorepo support**: Essential for modern architectures (Next.js, Turborepo, Nx) - ✅ **Parity with Claude Code**: Users expect similar behavior across AI coding tools --- ## Step-by-Step Flow: `"up"` Strategy (Search Upward) ``` Structure: monorepo/ ├── AGENTS.md # [A] Global rules ├── packages/ │ └── backend/ │ ├── AGENTS.md # [B] Backend rules │ └── routes/ │ ├── AGENTS.md # [C] Routes rules │ └── auth.ts # ← File being read LLM: readFile("packages/backend/routes/auth.ts") Step 1: Detect directory → "packages/backend/routes/" Step 2: Search upward: → packages/backend/routes/AGENTS.md ✅ [C] Found! → Load → packages/backend/AGENTS.md ✅ [B] Found! → Load → packages/AGENTS.md ❌ Does not exist → AGENTS.md ✅ [A] Already loaded by system Result: LLM receives context from [C] + [B] + [A] ``` --- ## Step-by-Step Flow: `"exact"` Strategy (Current Directory Only) ``` Same structure as before: monorepo/ ├── AGENTS.md # [A] Global rules ├── packages/ │ └── backend/ │ ├── AGENTS.md # [B] Backend rules │ └── routes/ │ ├── AGENTS.md # [C] Routes rules │ └── auth.ts # ← File being read LLM: readFile("packages/backend/routes/auth.ts") Step 1: Detect directory → "packages/backend/routes/" Step 2: Search ONLY in that directory: → packages/backend/routes/AGENTS.md ✅ [C] Found! → Load → (Does NOT search in parent directories) Result: LLM receives context from [C] + [A] (root already loaded) ``` **When to use each strategy?** - **`"up"` (recommended)**: When you want the LLM to have full module + submodule context - **`"exact"`**: When each subdirectory has completely independent context and you don't want to "inherit" rules from parent folders --- ## Difference with #4479 I've read issue #4479 and consider this proposal to be **complementary but not the same**: - **#4479**: Vertical search outside the git root (for monorepos with AGENTS.md in parent folders) - **This proposal**: Horizontal search within the project (for modules with their own context) Both features can coexist and solve different use cases in complex monorepos. --- ## Implementation Offer If this sounds good, I'd like to implement it myself or help implement it. ---
yindo added the discussion label 2026-02-16 17:42:02 -05:00
Author
Owner

@github-actions[bot] commented on GitHub (Dec 28, 2025):

This issue might be a duplicate of existing issues. Please check:

  • #4479: Configurable instruction file search boundary and file types - proposes similar functionality for searching AGENTS.md upward within git root or filesystem root
  • #4758: Custom instruction files in opencode.jsonc not being loaded - relates to loading multiple instruction files from configuration
  • #2225: Automatically load @ referenced files in AGENTS.md into context - proposes auto-loading of files referenced in instructions

The main difference with your proposal is that you're suggesting automatic discovery based on file access patterns (when a file is read/written), while #4479 focuses on configurable search boundaries and file types. Your approach complements and extends these existing proposals by adding dynamic, context-aware loading rather than just configuration-based approaches.

Feel free to ignore if your specific use case differs from these issues.

@github-actions[bot] commented on GitHub (Dec 28, 2025): This issue might be a duplicate of existing issues. Please check: - #4479: Configurable instruction file search boundary and file types - proposes similar functionality for searching AGENTS.md upward within git root or filesystem root - #4758: Custom instruction files in opencode.jsonc not being loaded - relates to loading multiple instruction files from configuration - #2225: Automatically load @ referenced files in AGENTS.md into context - proposes auto-loading of files referenced in instructions The main difference with your proposal is that you're suggesting automatic discovery based on file access patterns (when a file is read/written), while #4479 focuses on configurable search boundaries and file types. Your approach complements and extends these existing proposals by adding **dynamic, context-aware** loading rather than just configuration-based approaches. Feel free to ignore if your specific use case differs from these issues.
Author
Owner

@ragnsan commented on GitHub (Dec 31, 2025):

Yes, this would be sick. Was just looking for this. Claude Code does this and it's super valuable. We also have a lot of nested AGENTS.md in packages and apps in our monorepos and don't want to pollute the context window with files that are not needed in a session

@ragnsan commented on GitHub (Dec 31, 2025): Yes, this would be sick. Was just looking for this. Claude Code does this and it's super valuable. We also have a lot of nested AGENTS.md in packages and apps in our monorepos and don't want to pollute the context window with files that are not needed in a session
Author
Owner

@WilliamsHoward commented on GitHub (Jan 5, 2026):

Couldn't agree more. In practical applications, project structures are frequently large and complex, significantly increasing token overhead. This feature allows for more efficient token utilization. can't wait to have this feature in opencode.

@WilliamsHoward commented on GitHub (Jan 5, 2026): Couldn't agree more. In practical applications, project structures are frequently large and complex, significantly increasing token overhead. This feature allows for more efficient token utilization. can't wait to have this feature in opencode.
Author
Owner

@YourTechBud commented on GitHub (Jan 10, 2026):

This is such an important feature to have. I work in a monorepo and its extremely tiring to reference all relevant AGENTS.md file by hand. This is supposed to be a part of the Agents.md spec as well.

4. Large monorepo? Use nested AGENTS.md files for subprojects

Place another AGENTS.md inside each package. Agents automatically read the nearest file in the directory tree, so the closest one takes precedence and every subproject can ship tailored instructions. For example, at time of writing the main OpenAI repo has 88 AGENTS.md files.

@YourTechBud commented on GitHub (Jan 10, 2026): This is such an important feature to have. I work in a monorepo and its extremely tiring to reference all relevant AGENTS.md file by hand. This is supposed to be a part of the [Agents.md](https://agents.md/) spec as well. > #### 4. Large monorepo? Use nested AGENTS.md files for subprojects > Place another AGENTS.md inside each package. Agents automatically read the nearest file in the directory tree, so the closest one takes precedence and every subproject can ship tailored instructions. For example, at time of writing the main OpenAI repo has 88 AGENTS.md files.
Author
Owner

@ragnsan commented on GitHub (Jan 10, 2026):

This is such an important feature to have. I work in a monorepo and its extremely tiring to reference all relevant AGENTS.md file by hand. This is supposed to be a part of the Agents.md spec as well.

4. Large monorepo? Use nested AGENTS.md files for subprojects

Place another AGENTS.md inside each package. Agents automatically read the nearest file in the directory tree, so the closest one takes precedence and every subproject can ship tailored instructions. For example, at time of writing the main OpenAI repo has 88 AGENTS.md files.

Yeah, agreed. Have made a plugin to have the agent read nested AGENTS.md files in subdirs until this (hopefully) becomes a built-in!

@ragnsan commented on GitHub (Jan 10, 2026): > This is such an important feature to have. I work in a monorepo and its extremely tiring to reference all relevant AGENTS.md file by hand. This is supposed to be a part of the [Agents.md](https://agents.md/) spec as well. > > > #### 4. Large monorepo? Use nested AGENTS.md files for subprojects > > Place another AGENTS.md inside each package. Agents automatically read the nearest file in the directory tree, so the closest one takes precedence and every subproject can ship tailored instructions. For example, at time of writing the main OpenAI repo has 88 AGENTS.md files. Yeah, agreed. Have made a plugin to have the agent read nested AGENTS.md files in subdirs until this (hopefully) becomes a built-in!
Author
Owner

@YourTechBud commented on GitHub (Jan 10, 2026):

@ragnsan would ve lovely uf you could share some details about the plugin. Maybe a github repo link?

@YourTechBud commented on GitHub (Jan 10, 2026): @ragnsan would ve lovely uf you could share some details about the plugin. Maybe a github repo link?
Author
Owner

@bailey-busc commented on GitHub (Jan 19, 2026):

I have a functioning implementation of a similar idea as described in #9511, but I like the configuration approach you outline here better than what I came up with. Current plan is to adapt it to the configuration interface proposed here and PR it.

@bailey-busc commented on GitHub (Jan 19, 2026): I have a functioning implementation of a similar idea as described in #9511, but I like the configuration approach you outline here better than what I came up with. Current plan is to adapt it to the configuration interface proposed here and PR it.
Author
Owner

@TomLucidor commented on GitHub (Jan 20, 2026):

Is this part of the AGENTS.md shared specs?

@TomLucidor commented on GitHub (Jan 20, 2026): Is this part of the `AGENTS.md` shared specs?
Author
Owner

@allisoneer commented on GitHub (Jan 21, 2026):

https://github.com/anomalyco/opencode/issues/7361

I went with the "vanilla" approach. But damn that advanced config looks potentially sick. I actually had a similar pattern matching setup in my todo list for my own tools. Would be rad if it was in opencode directly and with reasonable defaults.

@allisoneer commented on GitHub (Jan 21, 2026): https://github.com/anomalyco/opencode/issues/7361 I went with the "vanilla" approach. But damn that advanced config looks potentially sick. I actually had a similar pattern matching setup in my todo list for my own tools. Would be rad if it was in opencode directly and with reasonable defaults.
Author
Owner

@YourTechBud commented on GitHub (Jan 31, 2026):

I think this has already been implemented now:

Image
@YourTechBud commented on GitHub (Jan 31, 2026): I think this has already been implemented now: <img width="380" height="49" alt="Image" src="https://github.com/user-attachments/assets/dcd0d8f5-7baa-4e6f-b26b-4e28c31ba3fa" />
Author
Owner

@YourTechBud commented on GitHub (Jan 31, 2026):

@thdxr we can close this now

@YourTechBud commented on GitHub (Jan 31, 2026): @thdxr we can close this now
Author
Owner

@YuukanOO commented on GitHub (Feb 11, 2026):

I don't think this was implemented (tested on v1.1.59). I have simple sandbox with multiple directories. In each directory, I put an AGENTS.md file with this rule (with a different header in each subdirectory):

Every file in this directory should start with:

// This file was generated by an agent in a nested folder.

Using Kimi K2.5 and the following prompt:

create a js hello world in @frontend/nested_folder/ 

I got the file frontend/nested_folder/hello.js:

// This file was generated by an agent.

console.log("Hello World");

Which match the root AGENTS.md instruction, not the nested one.

Image
@YuukanOO commented on GitHub (Feb 11, 2026): I don't think this was implemented (tested on v1.1.59). I have simple sandbox with multiple directories. In each directory, I put an `AGENTS.md` file with this rule (**with a different header in each subdirectory)**: ```md Every file in this directory should start with: // This file was generated by an agent in a nested folder. ``` Using Kimi K2.5 and the following prompt: ``` create a js hello world in @frontend/nested_folder/ ``` I got the file `frontend/nested_folder/hello.js`: ```js // This file was generated by an agent. console.log("Hello World"); ``` Which match the root `AGENTS.md` instruction, not the nested one. <img width="1087" height="802" alt="Image" src="https://github.com/user-attachments/assets/7cd8a502-9fa4-49bc-a74b-4d11338e8c84" />
Author
Owner

@YourTechBud commented on GitHub (Feb 11, 2026):

@YuukanOO i think auto loading only works when you read a files. Globs dont count.

@YourTechBud commented on GitHub (Feb 11, 2026): @YuukanOO i think auto loading only works when you read a files. Globs dont count.
Author
Owner

@ragnsan commented on GitHub (Feb 12, 2026):

Yeah, confirming that it's working for me and that I yoinked out our custom plugin

@ragnsan commented on GitHub (Feb 12, 2026): Yeah, confirming that it's working for me and that I yoinked out our custom plugin
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: anomalyco/opencode#3943