How Roo Code's Context Management System Processes @file Mentions

Roo Code treats any token starting with @ as a mention and processes it through a dedicated pipeline that extracts file content and delivers it to the LLM as structured blocks while maintaining security through path validation and ignore rules.

Roo Code, an AI-powered coding assistant, implements a sophisticated context management system that transforms user-typed @file mentions into rich, structured context for large language models. This system ensures that when you reference files using @path/to/file syntax in the Roo Code interface, the actual content is securely extracted, formatted, and inserted into the conversation without leaking binary data or violating project ignore rules.

Mention Detection with mentionRegex

The context management system begins by detecting potential mentions using a robust regular expression defined in src/shared/context-mentions.ts. The mentionRegex pattern identifies unescaped "@" characters that appear at the start of a line or preceded by whitespace, while helper utilities like unescapeSpaces handle escaped spaces within paths.

This regex recognizes several mention types:

  • Absolute file and folder paths (@/path/to/file)
  • URLs (@https://…)
  • Special keywords (@problems, @git-changes, @terminal)
  • Git SHA shortcuts

For exhaustive scanning of entire prompts, the system uses mentionRegexGlobal, which applies the same pattern with global flags to capture all instances within user input.

Parsing User Prompts

Once detected, mentions flow into the parseMentions function located in src/core/mentions/index.ts. This function orchestrates the transformation pipeline through several precise steps.

Extracting Unique Mentions

First, parseMentions extracts all matches using text.matchAll(mentionRegexGlobal) and builds a Set<string> of unique mentions. This deduplication prevents the same file from being processed multiple times if mentioned repeatedly in a single prompt.

Generating Clean References

The function replaces each mention in the original text with a clean reference (e.g., 'src/file.ts'), ensuring the LLM sees readable placeholders. The actual file content is supplied separately through MentionContentBlock objects, maintaining a clear separation between the prompt structure and the file data.

Security Validation and Path Resolution

For every mention beginning with "/", the system invokes getFileOrFolderContentWithMetadata to resolve and validate the target before reading. This function performs several critical safety checks to secure the context management system.

Path Resolution and Traversal Protection

The system calls path.resolve(cwd, unescapedPath) to anchor every mention to the current working directory. This resolution prevents directory traversal attacks by ensuring that relative path components like ../ cannot escape the project root, effectively sandboxing file access to the intended workspace.

Binary File Guard

Before reading, the system checks isBinaryFile to detect image, video, and other binary formats. These files are automatically skipped from text extraction and handled through separate image-attachment flows, ensuring the LLM context remains free of base64-encoded blobs or binary garbage.

RooIgnore Enforcement

When a RooIgnoreController is provided, the system calls validateAccess to check whether the requested path matches .rooignore patterns. Files matching ignore rules return a notification block stating Note: File is ignored by .rooignore. rather than their contents, protecting sensitive files like environment variables or build artifacts from exposure.

Folder Handling

When a mention ends with "/", the system treats it as a directory reference. It generates a tree listing and recursively processes all non-ignored, non-binary files within that folder, aggregating their contents into separate blocks while respecting the same security constraints applied to individual files.

Content Processing and Formatting

After validation, the system retrieves and formats file content for LLM consumption.

Reading File Metadata

The extractTextFromFileWithMetadata function, leveraging utilities from src/integrations/misc/extract-text.ts, pulls the file's text content, counts lines, and identifies whether truncation is necessary. This metadata enables the system to handle files of any size without overwhelming the context window.

Formatting Content Blocks

The formatFileReadResult function wraps validated content in read_file-style blocks with standardized headers like [read_file for 'src/file.ts']. When content exceeds limits, the system appends Gemini-style truncation warnings indicating the current range (e.g., "Showing lines 1-200 of 542 total lines") and suggests next-offset parameters for incremental reading.

Context Tracking for Window Budgeting

Every successfully read file triggers FileContextTracker.trackFileContext(mentionPath, "file_mentioned") from src/core/context-tracking/FileContextTracker.ts. This tracking mechanism records which files have contributed to the current prompt, enabling advanced features like context window budgeting and incremental caching that prevent redundant token consumption.

The tracker maintains a history of referenced files with their inclusion reasons, allowing the system to optimize subsequent LLM requests by omitting previously processed content when appropriate.

Error Handling and Request Aggregation

The system aggregates all processed mentions into ParseMentionsResult.contentBlocks, which the task executor appends to LLM requests alongside the cleaned prompt text. The final transformation into provider-specific payloads occurs in src/core/mentions/processUserContentMentions.ts, which converts MentionContentBlock[] into the appropriate format for the specific model.

When files cannot be accessed, the system returns explicit error blocks formatted as [read_file for '…']\nError: … rather than failing silently. Binary files receive notices stating Note: Binary file omitted from context., while ignored files display the ignore-specific messaging mentioned previously.

Practical Implementation Example

The following TypeScript example demonstrates how to process a prompt containing @file mentions:

import { parseMentions } from "./src/core/mentions/index.ts";
import { FileContextTracker } from "./src/core/context-tracking/FileContextTracker.ts";

const prompt = `
Please review the recent changes in @/src/core/mentions/index.ts
and also look at the helper @/src/shared/context-mentions.ts.
`;

// Parse the prompt with context tracking
const tracker = new FileContextTracker();
const { text, contentBlocks } = await parseMentions(
  prompt,
  "/repo/root",               // cwd
  tracker,                    // FileContextTracker
  undefined,                  // optional RooIgnoreController
);

// Cleaned prompt text with placeholders
console.log(text);
// Output:
// Please review the recent changes in 'src/core/mentions/index.ts'
// and also look at the helper 'src/shared/context-mentions.ts'.

// Content blocks sent to the LLM
for (const block of contentBlocks) {
  console.log(block.content);
}

Sample block output format:

[read_file for 'src/core/mentions/index.ts']
File: src/core/mentions/index.ts
import fs from "fs/promises"
import * as path from "path"
…
IMPORTANT: File content truncated.
Status: Showing lines 1-200 of 542 total lines.
To read more: Use the read_file tool with offset=201 and limit=200.

Summary

  • Pattern Detection: The mentionRegex in src/shared/context-mentions.ts identifies @tokens including files, URLs, and special keywords using mentionRegexGlobal for exhaustive scanning.
  • Secure Resolution: parseMentions in src/core/mentions/index.ts validates paths against the CWD, checks .rooignore rules via RooIgnoreController, and skips binary files using isBinaryFile.
  • Structured Output: File content is wrapped in standardized blocks with truncation metadata and offset suggestions for large files through formatFileReadResult.
  • Context Tracking: FileContextTracker records every mentioned file with trackFileContext to enable context window budgeting and prevent redundant processing.
  • Error Transparency: Failed reads return explicit error messages within the content blocks, while binary and ignored files receive descriptive placeholder notices.

Frequently Asked Questions

How does Roo Code prevent directory traversal attacks with @file mentions?

The system calls path.resolve(cwd, unescapedPath) for every file mention to anchor the path to the current working directory. This resolution ensures that relative path components like ../ cannot escape the project root, effectively sandboxing file access to the intended workspace according to the RooCodeInc/Roo-Code source code.

What happens when I mention a folder instead of a specific file?

When a mention ends with "/" (e.g., @/src/utils/), getFileOrFolderContentWithMetadata generates a tree listing of the directory. It then recursively processes all non-ignored, non-binary files within that folder, aggregating their contents into separate blocks while respecting .rooignore patterns and binary file exclusions.

Why does Roo Code track file context separately from the main prompt?

The FileContextTracker maintains a record of all files that enter the context with trackFileContext(mentionPath, "file_mentioned"). This separation enables context window budgeting—allowing the system to calculate token usage accurately—and supports incremental caching strategies where previously processed files can be omitted or summarized in subsequent requests.

Can I mention binary files like images using the @ syntax?

While the regex detects @tokens for any path, the isBinaryFile guard in getFileOrFolderContentWithMetadata identifies binary content (images, videos) and returns a placeholder note instead of the raw data. Binary files are handled through separate image-attachment flows, ensuring the LLM receives appropriate context without base64-encoded blobs cluttering the text interface.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →