Skip to content

"Context" here means everything the model can see besides the current user message: the system prompt, hierarchical memory, workspace files, conversation history, and tool outputs. Context is assembled before a request and reshaped between requests.

The implementation is spread across:

FileResponsibility
packages/core/src/context/memoryContextManager.tsRefreshes hierarchical memory and just-in-time subdirectory memory.
packages/core/src/utils/memoryDiscovery.tsFinds and reads M31A.md files.
packages/core/src/services/fileDiscoveryService.tsApplies ignore rules to workspace files.
packages/core/src/context/chatCompressionService.tsCompacts history.
packages/core/src/context/toolDistillationService.tsSpills oversized tool output to disk.
packages/core/src/context/toolOutputMaskingService.tsMasks older tool outputs.
packages/core/src/tools/topicTool.tsMaintains topic and intent narration.

1. Discovering M31A.md ​

MemoryContextManager.refresh() discovers memory from four sources:

  1. Global — M31A.md in the per-user .m31a directory.
  2. Extension — context files declared by active extensions, sorted and deduplicated.
  3. Project — files found by walking upward from every trusted workspace root. The walk stops at the first boundary marker; .git is the default, which normally makes the repository root the ceiling. Boundary markers that are absolute or contain .. are ignored.
  4. User-project — a private memory index in the project's temp memory directory, with a legacy M31A.md fallback.

Paths are deduplicated by file identity to behave correctly on case-insensitive filesystems. Files are read with context.importFormat (flat or tree) and concatenated into a HierarchicalMemory object with global, extension, project, and userProjectMemory fields.

Two details matter in practice:

  • Project memory is only exposed when the folder is trusted. In an untrusted folder the project string is empty.
  • MCP server instructions are appended to project memory before it is handed to prompt assembly, again only for trusted folders.

M31A_SYSTEM_MD can override the whole system prompt template, while M31A_WRITE_SYSTEM_MD can dump the assembled prompt for inspection. Inside the app, /init creates a starter context file, /memory show displays loaded memory, and /memory reload triggers a fresh discovery pass.

2. Names, include directories, and JIT memory ​

context.fileName accepts a string or an array of filenames; the helper getAllM31aMdFilenames() in packages/core/src/tools/memoryTool.ts exposes the effective list to prompt assembly. context.discoveryMaxDirs exists in settings with a default of 200, but the upward walk in memoryDiscovery.ts currently stops at boundary markers rather than consulting that value; do not rely on it as a hard search limit.

--include-directories ../lib,../shared adds roots to the workspace context. context.loadMemoryFromIncludeDirectories controls whether those extra roots are scanned for their own M31A.md files during /memory reload. Missing directories are skipped.

Just-in-time subdirectory memory is a third tier: when the agent accesses a path, MemoryContextManager.discoverContext() walks upward from that path to the trusted root and loads any not-yet-seen M31A.md files, deduplicating against files already loaded. This keeps deep-package instructions available without front-loading every file into the first request.

3. File filtering ​

FileDiscoveryService in packages/core/src/services/fileDiscoveryService.ts decides which workspace files are visible to search and expansion:

SettingDefaultEffect
context.fileFiltering.respectGitIgnoretrueHonor .gitignore.
context.fileFiltering.respectM31aIgnoretrueHonor .m31aignore.
context.fileFiltering.customIgnoreFilePaths[]Additional ignore files.
context.fileFiltering.enableRecursiveFileSearchtrueRecursive at-reference search.
context.fileFiltering.enableFuzzySearchtrueFuzzy file matching.

Environment context is filtered separately: advanced.excludedEnvVars defaults to DEBUG and DEBUG_MODE, and advanced.ignoreLocalEnv can suppress project .env files entirely. See Configuration for the settings surface.

4. Compression ​

ChatCompressionService reduces history when token usage crosses a fraction of the model's context window. model.compressionThreshold defaults to 0.5. The experimental contextManagement settings add explicit budgets:

json
{
  "experimental": {"contextManagement": true},
  "contextManagement": {
    "historyWindow": {"maxTokens": 150000, "retainedTokens": 40000},
    "messageLimits": {
      "normalMaxTokens": 2500,
      "retainedMaxTokens": 12000,
      "normalizationHeadRatio": 0.25
    }
  }
}

When enabled, historyWindow.retainedTokens tokens are protected from collapse. Without it, the compression service still protects the three most recent tool response turns (RECENT_TURNS_PROTECTED) and exempts retrieval tools such as read_file, get_internal_docs, glob, and grep_search from being collapsed into snippets. Older function responses are capped around 2 KB when collapsed, with a 64 KB budget for exempt retrieval history and a 256 KB history-size trigger for earlier collapsing.

PreCompress hooks run before compaction, so they can back up or analyze the conversation. Manual controls are /compress (aliases /summarize and /compact) and /context-window.

INFO

experimental.contextManagement, historyWindow, and the message-limit settings are experimental; exact behavior may change between releases.

5. Distillation and masking ​

These are two separate mechanisms in packages/core/src/context/:

  • Distillation (toolDistillationService.ts) triggers when a single tool output exceeds roughly toolMaxOutputTokens * 4 characters. The raw output is saved to disk under the project temp directory, a compact placeholder is put in its place, and very large outputs may be summarized by a secondary model call. read_file and read_many_files are exempt because they already have native large-output handling. Outputs above one million characters skip structural map generation.
  • Masking (toolOutputMaskingService.ts) is a backward scan over the whole history. It protects the newest ~50,000 tool tokens (DEFAULT_TOOL_PROTECTION_THRESHOLD) and optionally the latest turn (protectLatestTurn), then masks older functionResponse parts once more than ~30,000 prunable tokens exist. Masked outputs are replaced by a marker and can be read back from the tool-outputs directory. activate_skill, ask_user, enter_plan_mode, and exit_plan_mode outputs are never masked.

Both mechanisms target tool output, not user text or model reasoning, because tool logs are usually the largest and most reconstructable part of a conversation.

6. Topic narration ​

general.topicUpdateNarration defaults to true. The update_topic tool sets a topic title, an optional summary, and a strategic intent. The tool's result is displayed as a notice in the UI, and the active topic (sanitized to a single line) is reinjected at the end of the system prompt as [Active Topic: ...]. The same state is used by the prompt's workflow sections to keep long sessions focused.

Turn this off when you want minimal output or when a script consumes plain text; see Headless mode.

7. Where to observe the result ​

  • /memory show and /memory reload for discovered instructions.
  • /context-window for current usage.
  • /compress for a manual compaction.
  • M31A_CONTEXT_TRACE_DIR enables context tracing for debugging.

Next steps ​

Built with VitePress. Powered by NVIDIA NIM.