> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch17-system-prompts-and-context-assembly/17.2-workspace-and-context-file-injection.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 17.2 Workspace and Context File Injection

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~450,000 tokens, Output \~36,000 tokens (Chapter 17 total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In Section 17.1, we saw that the `buildAgentSystemPrompt` function injects a set of `EmbeddedContextFile` objects into the `# Project Context` section of the system prompt. But where do these files come from? How are they loaded, filtered, truncated, and ultimately become part of the prompt?

This section will trace the complete lifecycle of context files: from Markdown files on the workspace disk to text fragments finally embedded in the LLM context window.

## 17.2.1 Workspace Root Directory Resolution (`src/agents/workspace.ts`)

### Default Workspace Path

Each OpenClaw instance has a **workspace directory** that stores bootstrap files and user configurations needed for Agent execution. The default path is:

```typescript
// src/agents/workspace.ts
export function resolveDefaultAgentWorkspaceDir(
  env: NodeJS.ProcessEnv = process.env,
  homedir: () => string = os.homedir,
): string {
  const profile = env.OPENCLAW_PROFILE?.trim();
  if (profile && profile.toLowerCase() !== "default") {
    return path.join(homedir(), ".openclaw", `workspace-${profile}`);
  }
  return path.join(homedir(), ".openclaw", "workspace");
}
```

* **Default Profile**: `~/.openclaw/workspace`
* **Custom Profile**: `~/.openclaw/workspace-{profile}`

Multi-profile support allows running multiple OpenClaw instances on the same machine, each with an independent workspace.

> **Sidebar — Profile (Configuration Profile)**
>
> A profile is a common software configuration isolation pattern. Similar to browser "user profiles" or AWS CLI's `--profile` parameter, OpenClaw's profile is controlled via the `OPENCLAW_PROFILE` environment variable, allowing a single user to maintain multiple completely independent Agent configurations.

### Eight Bootstrap Files

OpenClaw defines eight standard **bootstrap files** that form the Agent's "knowledge base":

```typescript
// src/agents/workspace.ts
export const DEFAULT_AGENTS_FILENAME = "AGENTS.md";
export const DEFAULT_SOUL_FILENAME = "SOUL.md";
export const DEFAULT_TOOLS_FILENAME = "TOOLS.md";
export const DEFAULT_IDENTITY_FILENAME = "IDENTITY.md";
export const DEFAULT_USER_FILENAME = "USER.md";
export const DEFAULT_HEARTBEAT_FILENAME = "HEARTBEAT.md";
export const DEFAULT_BOOTSTRAP_FILENAME = "BOOTSTRAP.md";
export const DEFAULT_MEMORY_FILENAME = "MEMORY.md";
```

| File           | Purpose                                          | Corresponding PromptMode |
| -------------- | ------------------------------------------------ | ------------------------ |
| `AGENTS.md`    | Agent behavior guidance, project standards       | full + minimal           |
| `SOUL.md`      | Personality definition, tone, style              | full                     |
| `TOOLS.md`     | Tool usage guide (user-defined)                  | full + minimal           |
| `IDENTITY.md`  | Agent identity information (name, emoji, avatar) | full                     |
| `USER.md`      | User preference information                      | full                     |
| `HEARTBEAT.md` | Custom prompt for heartbeat checks               | full                     |
| `BOOTSTRAP.md` | General bootstrap information                    | full                     |
| `MEMORY.md`    | Long-term memory storage                         | full                     |

Note that `AGENTS.md` and `TOOLS.md` are the **only two** bootstrap files passed to sub-Agents (see `SUBAGENT_BOOTSTRAP_ALLOWLIST` below).

### Workspace Initialization

`ensureAgentWorkspace` is responsible for creating the workspace directory and populating it with default bootstrap file templates:

```typescript
// src/agents/workspace.ts (simplified)
export async function ensureAgentWorkspace(params?: {
  dir?: string;
  ensureBootstrapFiles?: boolean;
}): Promise<{ dir: string; agentsPath?: string; ... }> {
  const dir = resolveUserPath(rawDir);
  await fs.mkdir(dir, { recursive: true });
  
  if (!params?.ensureBootstrapFiles) return { dir };
  
  // Check if this is a brand new workspace (all files missing)
  const isBrandNewWorkspace = await (async () => {
    const paths = [agentsPath, soulPath, toolsPath, ...];
    const existing = await Promise.all(
      paths.map(async (p) => {
        try { await fs.access(p); return true; }
        catch { return false; }
      })
    );
    return existing.every((v) => !v);
  })();
  
  // Load default content from template directory
  const agentsTemplate = await loadTemplate(DEFAULT_AGENTS_FILENAME);
  const soulTemplate = await loadTemplate(DEFAULT_SOUL_FILENAME);
  // ...load other templates
  
  // Write only if file doesn't exist (don't overwrite user modifications)
  await writeFileIfMissing(agentsPath, agentsTemplate);
  await writeFileIfMissing(soulPath, soulTemplate);
  // ...write other files
  
  // Brand new workspace also initializes Git repository
  await ensureGitRepo(dir, isBrandNewWorkspace);
  
  return { dir, agentsPath, soulPath, ... };
}
```

Key design decisions:

1. **`writeFileIfMissing`** uses the `wx` flag (exclusive creation) of `fs.writeFile`, ensuring that existing user files are never overwritten.
2. **Brand new workspace detection**: Only when all standard files are missing is it considered a brand new workspace, at which point `BOOTSTRAP.md` is written and Git is initialized.
3. **Git initialization**: The purpose of automatic `git init` is to make workspace file changes traceable, but it won't error if Git is unavailable.

### Front Matter Stripping

Template files may contain YAML Front Matter (metadata for documentation systems), which needs to be stripped during loading:

```typescript
function stripFrontMatter(content: string): string {
  if (!content.startsWith("---")) return content;
  const endIndex = content.indexOf("\n---", 3);
  if (endIndex === -1) return content;
  const start = endIndex + "\n---".length;
  return content.slice(start).replace(/^\s+/, "");
}
```

> **Sidebar — YAML Front Matter**
>
> YAML Front Matter is a YAML-formatted metadata block wrapped in `---` at the beginning of a Markdown file, commonly seen in static site generators like Jekyll and Hugo. For example:
>
> ```
> ---
> title: AGENTS.md Template
> version: 2
> ---
> # Actual Content...
> ```
>
> OpenClaw's template files use Front Matter to store version information, but these metadata blocks need to be removed when injecting into prompts.

### Bootstrap File Loading

`loadWorkspaceBootstrapFiles` loads all bootstrap files at once:

```typescript
// src/agents/workspace.ts
export async function loadWorkspaceBootstrapFiles(
  dir: string
): Promise<WorkspaceBootstrapFile[]> {
  const resolvedDir = resolveUserPath(dir);
  
  // Fixed list of files
  const entries = [
    { name: DEFAULT_AGENTS_FILENAME, filePath: path.join(resolvedDir, "AGENTS.md") },
    { name: DEFAULT_SOUL_FILENAME,   filePath: path.join(resolvedDir, "SOUL.md") },
    { name: DEFAULT_TOOLS_FILENAME,  filePath: path.join(resolvedDir, "TOOLS.md") },
    { name: DEFAULT_IDENTITY_FILENAME, filePath: path.join(resolvedDir, "IDENTITY.md") },
    { name: DEFAULT_USER_FILENAME,   filePath: path.join(resolvedDir, "USER.md") },
    { name: DEFAULT_HEARTBEAT_FILENAME, filePath: path.join(resolvedDir, "HEARTBEAT.md") },
    { name: DEFAULT_BOOTSTRAP_FILENAME, filePath: path.join(resolvedDir, "BOOTSTRAP.md") },
  ];
  
  // Append MEMORY.md (optional, with deduplication logic)
  entries.push(...(await resolveMemoryBootstrapEntries(resolvedDir)));
  
  // Read each file, mark as missing if not found
  const result: WorkspaceBootstrapFile[] = [];
  for (const entry of entries) {
    try {
      const content = await fs.readFile(entry.filePath, "utf-8");
      result.push({ name: entry.name, path: entry.filePath, content, missing: false });
    } catch {
      result.push({ name: entry.name, path: entry.filePath, missing: true });
    }
  }
  return result;
}
```

`resolveMemoryBootstrapEntries` checks both `MEMORY.md` and `memory.md` (case variants) and uses `fs.realpath` for deduplication — if both point to the same file (e.g., via symlink), only one copy is kept.

### Sub-Agent File Filtering

Sub-Agents can only receive `AGENTS.md` and `TOOLS.md`; other bootstrap files are filtered out:

```typescript
const SUBAGENT_BOOTSTRAP_ALLOWLIST = new Set([
  DEFAULT_AGENTS_FILENAME, 
  DEFAULT_TOOLS_FILENAME,
]);

export function filterBootstrapFilesForSession(
  files: WorkspaceBootstrapFile[],
  sessionKey?: string,
): WorkspaceBootstrapFile[] {
  if (!sessionKey || !isSubagentSessionKey(sessionKey)) return files;
  return files.filter((file) => SUBAGENT_BOOTSTRAP_ALLOWLIST.has(file.name));
}
```

`isSubagentSessionKey` determines whether a session is a sub-Agent based on the session key format. This means sub-Agents don't receive SOUL.md (personality), USER.md (user preferences), and other information — they only need to know project standards and tool usage guidelines.

## 17.2.2 Bootstrap Files: AGENTS.md / SOUL.md / TOOLS.md

### AGENTS.md: Project Standards File

`AGENTS.md` is the most important bootstrap file, defining Agent behavior standards within a specific project. A typical `AGENTS.md` might contain:

```markdown
# AGENTS.md - AI Agent Operational Guidelines

## Project Structure
- src/ contains the main application code
- tests/ contains unit and integration tests

## Coding Standards
- Use TypeScript strict mode
- All functions must have JSDoc comments
- Tests must use vitest

## Deployment
- CI runs on GitHub Actions
- Deploy to AWS via CDK
```

The design philosophy of AGENTS.md is to let users describe project constraints and standards in natural language, which the Agent references before executing any operations.

### SOUL.md: Personality Definition File

`SOUL.md` controls the Agent's "personality" — tone, expression style, role definition. Recalling Section 17.1, if SOUL.md is detected in the system prompt, a special instruction is inserted:

```
If SOUL.md is present, embody its persona and tone. 
Avoid stiff, generic replies; follow its guidance unless 
higher-priority instructions override it.
```

An example SOUL.md:

```markdown
# Soul

You are "Aria", a friendly but precise engineering assistant.
- Keep responses concise and technical
- Use emoji sparingly (only for emphasis)
- When uncertain, say so directly
- Prefer code examples over verbose explanations
```

### TOOLS.md: Tool Usage Guide

`TOOLS.md` is a user-defined tool usage guide. Note that it differs from the Tooling section in the system prompt — the Tooling section is auto-generated by OpenClaw, while TOOLS.md is user-written supplementary documentation. The system prompt explicitly states:

```
TOOLS.md does not control tool availability; 
it is user guidance for how to use external tools.
```

### resolveBootstrapFilesForRun: Complete Bootstrap File Resolution Chain

`resolveBootstrapFilesForRun` (in `bootstrap-files.ts`) chains all the above steps into a complete resolution pipeline:

```typescript
// src/agents/bootstrap-files.ts
export async function resolveBootstrapFilesForRun(params: {
  workspaceDir: string;
  config?: OpenClawConfig;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
}): Promise<WorkspaceBootstrapFile[]> {
  const sessionKey = params.sessionKey ?? params.sessionId;
  
  // Step 1: Load all bootstrap files
  const allFiles = await loadWorkspaceBootstrapFiles(params.workspaceDir);
  
  // Step 2: Filter by session type (sub-Agents keep only allowlist files)
  const filteredFiles = filterBootstrapFilesForSession(allFiles, sessionKey);
  
  // Step 3: Apply bootstrap hook overrides
  return applyBootstrapHookOverrides({
    files: filteredFiles,
    workspaceDir: params.workspaceDir,
    config: params.config,
    sessionKey: params.sessionKey,
    sessionId: params.sessionId,
    agentId: params.agentId,
  });
}
```

Flow diagram:

```
Disk Files              Filtering              Hooks
┌──────────┐          ┌──────────┐          ┌──────────┐
│ AGENTS.md│          │ Sub-Agent?│          │ Hook     │
│ SOUL.md  │  ────►  │ Allowlist │  ────►  │ Modify/  │  ────►  Final List
│ TOOLS.md │          │ Filter    │          │ Replace  │
│ ...      │          │          │          │          │
└──────────┘          └──────────┘          └──────────┘
```

### resolveBootstrapContextForRun: Files → Context Fragments

The final step converts `WorkspaceBootstrapFile[]` to `EmbeddedContextFile[]` (format directly injectable into prompts):

```typescript
// src/agents/bootstrap-files.ts
export async function resolveBootstrapContextForRun(params: {
  workspaceDir: string;
  config?: OpenClawConfig;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  warn?: (message: string) => void;
}): Promise<{
  bootstrapFiles: WorkspaceBootstrapFile[];
  contextFiles: EmbeddedContextFile[];
}> {
  const bootstrapFiles = await resolveBootstrapFilesForRun(params);
  const contextFiles = buildBootstrapContextFiles(bootstrapFiles, {
    maxChars: resolveBootstrapMaxChars(params.config),
    warn: params.warn,
  });
  return { bootstrapFiles, contextFiles };
}
```

### Truncation Strategy

When bootstrap file content exceeds the maximum character limit (default 20,000 characters), `buildBootstrapContextFiles` calls `trimBootstrapContent` to truncate:

```typescript
// src/agents/pi-embedded-helpers/bootstrap.ts
const DEFAULT_BOOTSTRAP_MAX_CHARS = 20_000;
const BOOTSTRAP_HEAD_RATIO = 0.7;  // Keep first 70%
const BOOTSTRAP_TAIL_RATIO = 0.2;  // Keep last 20%

function trimBootstrapContent(
  content: string,
  fileName: string,
  maxChars: number,
): TrimBootstrapResult {
  const trimmed = content.trimEnd();
  if (trimmed.length <= maxChars) {
    return { content: trimmed, truncated: false, ... };
  }
  
  const headChars = Math.floor(maxChars * BOOTSTRAP_HEAD_RATIO);
  const tailChars = Math.floor(maxChars * BOOTSTRAP_TAIL_RATIO);
  const head = trimmed.slice(0, headChars);
  const tail = trimmed.slice(-tailChars);
  
  const marker = [
    "",
    `[...truncated, read ${fileName} for full content...]`,
    `…(truncated ${fileName}: kept ${headChars}+${tailChars} chars of ${trimmed.length})…`,
    "",
  ].join("\n");
  
  return {
    content: [head, marker, tail].join("\n"),
    truncated: true,
    ...
  };
}
```

The truncation strategy uses a "keep head and tail" design:

* **First 70%**: File beginning usually contains the most important information (titles, core rules)
* **Last 20%**: File end may contain recently added entries or summaries
* **Middle 10%**: Space for truncation marker, informing the model it can use the `read` tool to access full content

For missing files, a marker is injected:

```typescript
if (file.missing) {
  result.push({
    path: file.name,
    content: `[MISSING] Expected at: ${file.path}`,
  });
  continue;
}
```

## 17.2.3 Bootstrap Hooks (`src/agents/bootstrap-hooks.ts`)

Bootstrap hooks allow external plugins to **modify or replace** file content after loading but before injecting into the prompt.

### Hook Mechanism

```typescript
// src/agents/bootstrap-hooks.ts
export async function applyBootstrapHookOverrides(params: {
  files: WorkspaceBootstrapFile[];
  workspaceDir: string;
  config?: OpenClawConfig;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
}): Promise<WorkspaceBootstrapFile[]> {
  const agentId = params.agentId ??
    (params.sessionKey 
      ? resolveAgentIdFromSessionKey(params.sessionKey) 
      : undefined);
  
  // Build hook context
  const context: AgentBootstrapHookContext = {
    workspaceDir: params.workspaceDir,
    bootstrapFiles: params.files,
    cfg: params.config,
    sessionKey: params.sessionKey,
    sessionId: params.sessionId,
    agentId,
  };
  
  // Create and trigger internal hook event
  const event = createInternalHookEvent(
    "agent",          // namespace
    "bootstrap",      // event name
    sessionKey,       // event source
    context,          // mutable context
  );
  await triggerInternalHook(event);
  
  // Hooks can modify context.bootstrapFiles
  const updated = (event.context as AgentBootstrapHookContext).bootstrapFiles;
  return Array.isArray(updated) ? updated : params.files;
}
```

Hooks work by **modifying the context object in place**: after receiving the `context.bootstrapFiles` array, hook handlers can:

* **Append** new bootstrap files
* **Remove** unwanted files
* **Replace** file content
* **Reorder** files

If a hook doesn't modify `bootstrapFiles` (or returns a non-array value), the original file list is used as a fallback.

> **Sidebar — Hook Pattern**
>
> A hook is an extension point pattern that allows external code to "hook in" and modify behavior when specific events occur. In OpenClaw, `triggerInternalHook` iterates through all registered hook handlers and calls them in sequence. This is similar to Webpack's Plugin system — plugins extend core functionality by listening to specific hook events without modifying core code.

### Use Cases

Typical use cases for bootstrap hooks include:

1. **Conditional injection**: Dynamically add specific bootstrap content based on the current Agent ID or channel.
2. **Sensitive information filtering**: Remove content that shouldn't be exposed to specific sessions before injecting into the prompt.
3. **Content enrichment**: Pull information from external data sources and inject into bootstrap files.

## 17.2.4 Workspace Templates (`src/agents/workspace-templates.ts`)

### Template Directory Resolution

When a workspace is first initialized, default bootstrap file content needs to be loaded from a template directory. `resolveWorkspaceTemplateDir` is responsible for locating the template directory:

```typescript
// src/agents/workspace-templates.ts
const FALLBACK_TEMPLATE_DIR = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)),
  "../../docs/reference/templates",
);

let cachedTemplateDir: string | undefined;

export async function resolveWorkspaceTemplateDir(opts?: {
  cwd?: string;
  argv1?: string;
  moduleUrl?: string;
}): Promise<string> {
  if (cachedTemplateDir) return cachedTemplateDir;
  
  const packageRoot = await resolveOpenClawPackageRoot({ ... });
  const candidates = [
    packageRoot ? path.join(packageRoot, "docs", "reference", "templates") : null,
    cwd ? path.resolve(cwd, "docs", "reference", "templates") : null,
    FALLBACK_TEMPLATE_DIR,
  ].filter(Boolean) as string[];
  
  for (const candidate of candidates) {
    if (await pathExists(candidate)) {
      cachedTemplateDir = candidate;
      return candidate;
    }
  }
  
  cachedTemplateDir = candidates[0] ?? FALLBACK_TEMPLATE_DIR;
  return cachedTemplateDir;
}
```

The resolution strategy is prioritized as follows:

1. **Package root** `docs/reference/templates/` (npm install scenario)
2. **Current working directory** `docs/reference/templates/` (development scenario)
3. **Fallback path**: `../../docs/reference/templates` relative to current module

### Caching Strategy

The template directory path uses **module-level caching** (`cachedTemplateDir`), ensuring it's resolved only once during the entire process lifetime. The `resetWorkspaceTemplateDirCache` function is used to reset the cache during testing:

```typescript
export function resetWorkspaceTemplateDirCache() {
  cachedTemplateDir = undefined;
  resolvingTemplateDir = undefined;
}
```

### Concurrency Safety

Note that `resolveWorkspaceTemplateDir` uses a `resolvingTemplateDir` Promise variable to prevent concurrent resolution. When multiple calls arrive simultaneously, the first call starts actual resolution, and subsequent calls wait for the same Promise:

```typescript
let resolvingTemplateDir: Promise<string> | undefined;

export async function resolveWorkspaceTemplateDir(...): Promise<string> {
  if (cachedTemplateDir) return cachedTemplateDir;
  if (resolvingTemplateDir) return resolvingTemplateDir; // Wait for ongoing resolution
  
  resolvingTemplateDir = (async () => {
    // Actual resolution logic...
  })();
  
  try {
    return await resolvingTemplateDir;
  } finally {
    resolvingTemplateDir = undefined; // Reset, allow re-resolution if cache is cleared
  }
}
```

> **Sidebar — Promise Deduplication**
>
> This is a common async programming pattern: when multiple callers request the same async resource, the operation is executed only once, and all callers share the same Promise. This avoids duplicate filesystem operations or network requests. In OpenClaw, this pattern is used in multiple places including template directory resolution and model configuration loading.

### Complete Context Injection Flow

Chaining all content in this section together, the complete flow from disk files to final prompt injection is as follows:

```
┌──────────────────────────────────────────────────────────┐
│ 1. resolveWorkspaceTemplateDir                           │
│    Find template directory → docs/reference/templates/   │
└──────────────────┬───────────────────────────────────────┘
                   │
┌──────────────────▼───────────────────────────────────────┐
│ 2. ensureAgentWorkspace                                   │
│    Create workspace → Initialize bootstrap files from     │
│    templates (writeFileIfMissing)                         │
└──────────────────┬───────────────────────────────────────┘
                   │
┌──────────────────▼───────────────────────────────────────┐
│ 3. loadWorkspaceBootstrapFiles                            │
│    Load 8 bootstrap files from workspace →                │
│    WorkspaceBootstrapFile[]                               │
└──────────────────┬───────────────────────────────────────┘
                   │
┌──────────────────▼───────────────────────────────────────┐
│ 4. filterBootstrapFilesForSession                         │
│    Sub-Agent filtering → Keep only AGENTS.md + TOOLS.md  │
└──────────────────┬───────────────────────────────────────┘
                   │
┌──────────────────▼───────────────────────────────────────┐
│ 5. applyBootstrapHookOverrides                            │
│    Trigger "agent:bootstrap" hook → Allow plugins to     │
│    modify file list                                       │
└──────────────────┬───────────────────────────────────────┘
                   │
┌──────────────────▼───────────────────────────────────────┐
│ 6. buildBootstrapContextFiles                             │
│    Truncate oversized files (keep head 70% + tail 20%) →  │
│    EmbeddedContextFile[]                                  │
└──────────────────┬───────────────────────────────────────┘
                   │
┌──────────────────▼───────────────────────────────────────┐
│ 7. buildAgentSystemPrompt                                 │
│    Inject EmbeddedContextFile[] into # Project Context    │
│    section                                                │
└──────────────────────────────────────────────────────────┘
```

***

## Section Summary

1. **Workspace** is OpenClaw's core filesystem abstraction, located by default at `~/.openclaw/workspace`, supporting multi-instance isolation through the Profile mechanism.
2. **Eight bootstrap files** each have distinct roles: `AGENTS.md` defines project standards, `SOUL.md` defines personality, `TOOLS.md` guides tool usage, `IDENTITY.md` carries identity information, etc.
3. **Sub-Agent filtering** ensures sub-Agents only receive necessary context (AGENTS.md and TOOLS.md), avoiding injection of irrelevant information.
4. **Bootstrap hooks** provide extension points, allowing plugins to modify bootstrap file content after loading but before injection.
5. **Template system** provides out-of-the-box default configuration for new workspaces, using a "write-only, never-overwrite" strategy to protect user customizations.
6. **Truncation strategy** (keep head 70% + tail 20%) controls token consumption while preserving the most important information in files.
