> 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.1-building-system-prompts.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 17.1 Building System Prompts

> **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 Chapters 7 and 8, we explored how the PiAgent runtime executes the Agent loop and the model selection and failover mechanisms. But before an Agent sends its first request to a large language model, there is a critical step — **constructing the System Prompt**.

The system prompt is the "meta-instruction" of LLM conversations, telling the model "who you are, what you can do, and what rules you should follow." OpenClaw's system prompt is not a static text block, but rather a collection of **dynamically assembled fragments** concatenated together. Different session types (main Agent vs sub-Agent), different runtime environments (sandbox vs host machine), and different channels (Telegram vs Signal) all affect the final generated prompt content.

This section will analyze the three-layer system prompt construction framework: base templates, runtime parameters, and the final prompt diagnostic report.

## 17.1.1 Base Prompt Template (`src/agents/system-prompt.ts`)

### PromptMode: Three Prompt Modes

OpenClaw defines three prompt modes to control the "verbosity level" of system prompts:

```typescript
// src/agents/system-prompt.ts
export type PromptMode = "full" | "minimal" | "none";
```

| Mode        | Purpose            | Content                                                                     |
| ----------- | ------------------ | --------------------------------------------------------------------------- |
| `"full"`    | Main Agent session | All feature sections: tools, safety, skills, memory, messaging, voice, etc. |
| `"minimal"` | Sub-Agent session  | Only: tool list, workspace, runtime information                             |
| `"none"`    | Ultra-minimal mode | Only a single identity declaration line                                     |

When the mode is `"none"`, the function directly returns a single line:

```typescript
if (promptMode === "none") {
  return "You are a personal assistant running inside OpenClaw.";
}
```

> **Sidebar — Difference Between System Prompt and User Message**
>
> In large language model APIs, messages are generally divided into three roles: `system` (system), `user` (user), and `assistant` (assistant). The system prompt is a "hidden instruction" placed at the beginning of the conversation that users typically cannot see, but it has the strongest constraining power on model behavior. All of OpenClaw's behavioral standards — from tool usage to safety restrictions — are encoded in the system prompt.

### buildAgentSystemPrompt: Core Construction Function

`buildAgentSystemPrompt` is the entry point for the entire system prompt. It accepts a large parameter object covering almost all dimensions of the OpenClaw runtime that might affect the prompt:

```typescript
// src/agents/system-prompt.ts (simplified parameter list)
export function buildAgentSystemPrompt(params: {
  workspaceDir: string;              // Workspace directory
  promptMode?: PromptMode;            // Prompt mode
  toolNames?: string[];               // Available tool names list
  toolSummaries?: Record<string, string>; // Tool descriptions
  skillsPrompt?: string;              // Skills XML fragment
  contextFiles?: EmbeddedContextFile[];// Context files
  extraSystemPrompt?: string;         // Extra prompt (e.g., sub-Agent context)
  ownerNumbers?: string[];            // Owner phone numbers list
  userTimezone?: string;              // User timezone
  runtimeInfo?: { ... };              // Runtime environment information
  sandboxInfo?: { ... };              // Sandbox configuration
  memoryCitationsMode?: MemoryCitationsMode; // Memory citation mode
  // ...more parameters
}): string { ... }
```

The function internally assembles various feature sections into a string array in **fixed order**, then joins them with `\n`. Below we analyze each section one by one.

### Section One: Tooling (Tool List)

This is the first core section of the prompt. It presents all available tools to the model in list form:

```typescript
// src/agents/system-prompt.ts
const coreToolSummaries: Record<string, string> = {
  read: "Read file contents",
  write: "Create or overwrite files",
  edit: "Make precise edits to files",
  exec: "Run shell commands (pty available for TTY-required CLIs)",
  web_search: "Search the web (Brave API)",
  browser: "Control web browser",
  canvas: "Present/eval/snapshot the Canvas",
  cron: "Manage cron jobs and wake events",
  message: "Send messages and channel actions",
  sessions_spawn: "Spawn a sub-agent session",
  // ...more tools
};
```

The system maintains a **tool ordering table** `toolOrder` to ensure frequently-used tools (`read`, `write`, `edit`) always appear first. For **external tools** not in the standard list (such as custom tools provided by MCP), they are appended to the end in alphabetical order:

```typescript
const enabledTools = toolOrder.filter((tool) => availableTools.has(tool));
const toolLines = enabledTools.map((tool) => {
  const summary = coreToolSummaries[tool] ?? externalToolSummaries.get(tool);
  const name = resolveToolName(tool);
  return summary ? `- ${name}: ${summary}` : `- ${name}`;
});
// Append external tools
for (const tool of extraTools.toSorted()) {
  const name = resolveToolName(tool);
  toolLines.push(summary ? `- ${name}: ${summary}` : `- ${name}`);
}
```

It's worth noting that tool names are **case-sensitive**. OpenClaw preserves the original case passed by the caller through the `resolveToolName` function, while using lowercase internally for deduplication and matching.

### Section Two: Tool Call Style (Tool Invocation Style)

This small section guides the model on when to "silently" call tools and when to explain to the user:

```
Default: do not narrate routine, low-risk tool calls (just call the tool).
Narrate only when it helps: multi-step work, complex/challenging problems, 
sensitive actions (e.g., deletions), or when the user explicitly asks.
```

### Section Three: Safety (Safety Guidelines)

The safety section embodies OpenClaw's adherence to Anthropic's Constitutional AI principles:

```typescript
const safetySection = [
  "## Safety",
  "You have no independent goals: do not pursue self-preservation, " +
    "replication, resource acquisition, or power-seeking...",
  "Prioritize safety and human oversight over completion...",
  "Do not manipulate or persuade anyone to expand access or disable safeguards...",
];
```

> **Sidebar — Constitutional AI**
>
> Constitutional AI is an AI alignment method proposed by Anthropic. Its core idea is to establish a clear set of behavioral guidelines (a "constitution") for AI and train the model to internalize these principles. OpenClaw's Safety section is a concrete implementation of this concept — embedding safety boundaries into every Agent conversation through the system prompt.

### Section Four: Skills (Skill System)

The skills section only appears in "full" mode (skipped when `isMinimal`). It guides the model on how to select appropriate skills from the `<available_skills>` list:

```typescript
function buildSkillsSection(params: {
  skillsPrompt?: string;
  isMinimal: boolean;
  readToolName: string;
}) {
  if (params.isMinimal) return [];
  const trimmed = params.skillsPrompt?.trim();
  if (!trimmed) return [];
  return [
    "## Skills (mandatory)",
    "Before replying: scan <available_skills> <description> entries.",
    `- If exactly one skill clearly applies: read its SKILL.md at <location> ` +
      `with \`${params.readToolName}\`, then follow it.`,
    "- If multiple could apply: choose the most specific one...",
    "- If none clearly apply: do not read any SKILL.md.",
    trimmed,  // Actual skills XML list
  ];
}
```

The skills XML fragment format is as follows (generated by the Skills module, see later sections):

```xml
<available_skills>
  <skill>
    <name>git-master</name>
    <description>MUST USE for ANY git operations...</description>
    <location>/path/to/SKILL.md</location>
  </skill>
</available_skills>
```

### Section Five: Memory Recall (Memory Recall)

When the tool list includes `memory_search` or `memory_get`, the memory section guides the model to search memory files before answering questions involving historical information:

```typescript
function buildMemorySection(params: {
  isMinimal: boolean;
  availableTools: Set<string>;
  citationsMode?: MemoryCitationsMode;
}) {
  if (params.isMinimal) return [];
  if (!params.availableTools.has("memory_search") && 
      !params.availableTools.has("memory_get")) {
    return [];
  }
  const lines = [
    "## Memory Recall",
    "Before answering anything about prior work, decisions, dates, " +
      "people, preferences, or todos: run memory_search on MEMORY.md + " +
      "memory/*.md; then use memory_get to pull only the needed lines.",
  ];
  // Decide whether to require citations based on citationsMode
  if (params.citationsMode === "off") {
    lines.push("Citations are disabled...");
  } else {
    lines.push("Citations: include Source: <path#line>...");
  }
  return lines;
}
```

### Sections Six through Ten: Conditional Sections

The following sections appear based on runtime conditions:

| Section                 | Condition                               | Function                                                   |
| ----------------------- | --------------------------------------- | ---------------------------------------------------------- |
| **User Identity**       | ownerNumbers configured and not minimal | Inform the model which phone numbers are "owners"          |
| **Current Date & Time** | userTimezone configured                 | Provide current timezone information                       |
| **Reply Tags**          | Not minimal mode                        | Guide use of `[[reply_to_current]]` and similar reply tags |
| **Messaging**           | Not minimal and has message tool        | Cross-channel message sending guidance                     |
| **Voice (TTS)**         | TTS hint configured                     | Voice synthesis behavior guidance                          |

Taking `buildMessagingSection` as an example, its logic is particularly complex because it needs to handle different channel messaging capabilities:

```typescript
function buildMessagingSection(params: {
  isMinimal: boolean;
  availableTools: Set<string>;
  messageChannelOptions: string;    // e.g., "signal|telegram|discord"
  inlineButtonsEnabled: boolean;    // Whether current channel supports inline buttons
  runtimeChannel?: string;          // Current runtime channel
}) {
  if (params.isMinimal) return [];
  return [
    "## Messaging",
    "- Reply in current session → automatically routes to the source channel",
    "- Cross-session messaging → use sessions_send(sessionKey, message)",
    params.availableTools.has("message")
      ? [
          "### message tool",
          "- Use `message` for proactive sends + channel actions...",
          `- If multiple channels, pass \`channel\` (${params.messageChannelOptions}).`,
          params.inlineButtonsEnabled
            ? "- Inline buttons supported..."
            : `- Inline buttons not enabled for ${params.runtimeChannel}...`,
        ].join("\n")
      : "",
  ];
}
```

### Section Eleven: Workspace (Workspace)

The workspace section always exists (even in minimal mode), informing the model of the current working directory:

```
## Workspace
Your working directory is: /home/user/.openclaw/workspace
Treat this directory as the single global workspace for file operations.
```

### Section Twelve: Sandbox (Sandbox)

When sandbox execution is enabled (Docker isolated environment), detailed sandbox information is inserted:

```typescript
params.sandboxInfo?.enabled ? [
  "## Sandbox",
  "You are running in a sandboxed runtime (tools execute in Docker).",
  params.sandboxInfo.workspaceDir
    ? `Sandbox workspace: ${params.sandboxInfo.workspaceDir}`
    : "",
  params.sandboxInfo.elevated?.allowed
    ? "Elevated exec is available for this session."
    : "",
  // ...more sandbox details
].filter(Boolean).join("\n") : ""
```

> **Sidebar — Sandbox**
>
> A sandbox is a security isolation mechanism that restricts program execution to a controlled environment, preventing it from affecting the host system. OpenClaw implements sandboxing through Docker containers — Agent tool calls (such as `exec`, `write`) execute within the container. Even if the model generates dangerous commands (like `rm -rf /`), they won't damage the host machine. The sandbox also supports "elevation" mode, allowing host machine commands to be executed under specific conditions.

### Section Thirteen: Context File Injection

This is the **largest volume** section of the prompt. OpenClaw injects bootstrap files from the workspace (such as AGENTS.md, SOUL.md) under the `# Project Context` heading:

```typescript
const contextFiles = params.contextFiles ?? [];
if (contextFiles.length > 0) {
  const hasSoulFile = contextFiles.some((file) => {
    const baseName = file.path.split("/").pop() ?? file.path;
    return baseName.toLowerCase() === "soul.md";
  });
  lines.push("# Project Context", 
    "The following project context files have been loaded:");
  if (hasSoulFile) {
    lines.push(
      "If SOUL.md is present, embody its persona and tone. " +
        "Avoid stiff, generic replies; follow its guidance..."
    );
  }
  for (const file of contextFiles) {
    lines.push(`## ${file.path}`, "", file.content, "");
  }
}
```

Note that special handling is done for the `SOUL.md` file — if a SOUL file exists, the model is instructed to "embody its persona and tone." This is part of OpenClaw's identity system (see Section 17.3).

### Sections Fourteen through Sixteen: Silent Replies, Heartbeats, Runtime

**Silent Replies**: When the model determines no reply is needed, it returns a special token (`SILENT_REPLY_TOKEN`), which OpenClaw uses to determine whether to send a message to the user.

**Heartbeats**: OpenClaw periodically sends heartbeat messages to the Agent. If everything is normal, the Agent replies with `HEARTBEAT_OK`. This mechanism is used to detect whether the Agent needs to proactively report anomalies.

**Runtime**: The last line contains all metadata of the current runtime, formatted as:

```
Runtime: agent=default | host=macbook | repo=/project | os=Darwin 24.0 (arm64) | 
  node=v22.0.0 | model=anthropic/claude-sonnet-4-20250514 | channel=telegram | 
  capabilities=inlineButtons | thinking=off
```

This line is generated by the `buildRuntimeLine` function:

```typescript
export function buildRuntimeLine(
  runtimeInfo?: { ... },
  runtimeChannel?: string,
  runtimeCapabilities: string[] = [],
  defaultThinkLevel?: ThinkLevel,
): string {
  return `Runtime: ${[
    runtimeInfo?.agentId ? `agent=${runtimeInfo.agentId}` : "",
    runtimeInfo?.host ? `host=${runtimeInfo.host}` : "",
    runtimeInfo?.repoRoot ? `repo=${runtimeInfo.repoRoot}` : "",
    runtimeInfo?.model ? `model=${runtimeInfo.model}` : "",
    runtimeChannel ? `channel=${runtimeChannel}` : "",
    `thinking=${defaultThinkLevel ?? "off"}`,
  ].filter(Boolean).join(" | ")}`;
}
```

### Complete Prompt Assembly Flow

Concatenating all the above sections, the complete flow of `buildAgentSystemPrompt` is as follows:

```
┌─────────────────────────────────────────────┐
│  "You are a personal assistant..."          │  Identity declaration
├─────────────────────────────────────────────┤
│  ## Tooling                                  │  Tool list (always present)
│  ## Tool Call Style                          │  Invocation style
│  ## Safety                                   │  Safety guidelines
├─────────────────────────────────────────────┤
│  ## OpenClaw CLI Quick Reference             │  CLI reference
│  ## Skills (mandatory)         [full only]   │  Skills list
│  ## Memory Recall              [full + tool] │  Memory recall
│  ## OpenClaw Self-Update       [full + gw]   │  Self-update
│  ## Model Aliases              [full only]   │  Model aliases
├─────────────────────────────────────────────┤
│  ## Workspace                                │  Workspace path (always)
│  ## Documentation              [full only]   │  Documentation path
│  ## Sandbox                    [if enabled]  │  Sandbox information
│  ## User Identity              [full only]   │  User identity
│  ## Current Date & Time        [if timezone] │  Date and time
├─────────────────────────────────────────────┤
│  ## Workspace Files (injected)               │  Injected files note
│  ## Reply Tags                 [full only]   │  Reply tags
│  ## Messaging                  [full only]   │  Messaging guidance
│  ## Voice (TTS)                [full + tts]  │  Voice hint
├─────────────────────────────────────────────┤
│  ## Group Chat Context / Subagent Context    │  Extra context
│  ## Reactions                  [if channel]  │  Reaction guidance
│  ## Reasoning Format           [if tag hint] │  Reasoning format
├─────────────────────────────────────────────┤
│  # Project Context                           │  Bootstrap file content
│    ## AGENTS.md                               │
│    ## SOUL.md                                 │
│    ## TOOLS.md                                │
│    ## ...                                     │
├─────────────────────────────────────────────┤
│  ## Silent Replies             [full only]   │  Silent replies
│  ## Heartbeats                 [full only]   │  Heartbeat mechanism
│  ## Runtime                                  │  Runtime metadata
└─────────────────────────────────────────────┘
```

Finally, all lines are concatenated into a complete string via `lines.filter(Boolean).join("\n")`. A typical full-mode prompt might have **3,000-10,000 characters** (excluding injected context files), and with AGENTS.md and other files can reach **20,000-50,000 characters**.

## 17.1.2 Prompt Parameters (`src/agents/system-prompt-params.ts`)

The prompt template references many runtime information — user timezone, current time, Git repository root directory, etc. These parameters are unified by the `buildSystemPromptParams` function.

### SystemPromptRuntimeParams Type

```typescript
// src/agents/system-prompt-params.ts
export type RuntimeInfoInput = {
  agentId?: string;       // Agent identifier
  host: string;           // Hostname
  os: string;             // Operating system
  arch: string;           // CPU architecture
  node: string;           // Node.js version
  model: string;          // Current model
  defaultModel?: string;  // Default model
  channel?: string;       // Message channel
  capabilities?: string[];// Channel capabilities
  channelActions?: string[]; // Channel supported actions
  repoRoot?: string;      // Git repository root directory
};

export type SystemPromptRuntimeParams = {
  runtimeInfo: RuntimeInfoInput;
  userTimezone: string;
  userTime?: string;
  userTimeFormat?: ResolvedTimeFormat;
};
```

### Parameter Parsing Flow

```typescript
export function buildSystemPromptParams(params: {
  config?: OpenClawConfig;
  agentId?: string;
  runtime: Omit<RuntimeInfoInput, "agentId">;
  workspaceDir?: string;
  cwd?: string;
}): SystemPromptRuntimeParams {
  // 1. Parse Git repository root directory
  const repoRoot = resolveRepoRoot({
    config: params.config,
    workspaceDir: params.workspaceDir,
    cwd: params.cwd,
  });
  // 2. Parse user timezone
  const userTimezone = resolveUserTimezone(
    params.config?.agents?.defaults?.userTimezone
  );
  // 3. Parse time format preference (12/24 hour)
  const userTimeFormat = resolveUserTimeFormat(
    params.config?.agents?.defaults?.timeFormat
  );
  // 4. Format current time
  const userTime = formatUserTime(new Date(), userTimezone, userTimeFormat);
  
  return {
    runtimeInfo: { agentId: params.agentId, ...params.runtime, repoRoot },
    userTimezone,
    userTime,
    userTimeFormat,
  };
}
```

### Git Repository Root Detection

The `resolveRepoRoot` function is responsible for finding the Git root directory of the current project. It uses a three-level priority strategy:

```typescript
function resolveRepoRoot(params: {
  config?: OpenClawConfig;
  workspaceDir?: string;
  cwd?: string;
}): string | undefined {
  // Priority 1: Explicitly specified in configuration
  const configured = params.config?.agents?.defaults?.repoRoot?.trim();
  if (configured) {
    const resolved = path.resolve(configured);
    if (fs.statSync(resolved).isDirectory()) return resolved;
  }
  // Priority 2: Search upward from workspace directory or CWD for .git
  const candidates = [params.workspaceDir, params.cwd].filter(Boolean);
  for (const candidate of candidates) {
    const root = findGitRoot(path.resolve(candidate));
    if (root) return root;
  }
  return undefined;
}
```

The `findGitRoot` implementation uses the classic "upward traversal" algorithm — starting from the initial directory, it checks parent directories level by level for the presence of a `.git` file or directory, searching up to 12 levels:

```typescript
function findGitRoot(startDir: string): string | null {
  let current = path.resolve(startDir);
  for (let i = 0; i < 12; i += 1) {
    const gitPath = path.join(current, ".git");
    try {
      const stat = fs.statSync(gitPath);
      if (stat.isDirectory() || stat.isFile()) return current;
    } catch { /* continue upward */ }
    const parent = path.dirname(current);
    if (parent === current) break; // Reached root directory
    current = parent;
  }
  return null;
}
```

> **Sidebar — Can `.git` Be a File?**
>
> Usually `.git` is a directory containing all Git repository metadata (objects, refs, etc.). But in Git submodule and `git worktree` scenarios, `.git` becomes a **file** whose content points to the actual `.git` directory. Therefore, `findGitRoot` checks both `isDirectory()` and `isFile()` cases.

### Timezone and Time Format

Timezone resolution (`resolveUserTimezone`) prioritizes the configured value and falls back to the system's `Intl.DateTimeFormat().resolvedOptions().timeZone`:

```typescript
// src/agents/date-time.ts
export function resolveUserTimezone(configured?: string): string {
  const trimmed = configured?.trim();
  if (trimmed) {
    try {
      // Validate timezone validity
      new Intl.DateTimeFormat("en-US", { timeZone: trimmed }).format(new Date());
      return trimmed;
    } catch { /* ignore invalid timezone */ }
  }
  return Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC";
}
```

Time format detection (`resolveUserTimeFormat`) performs different detection based on the operating system:

* **macOS**: Read `defaults read -g AppleICUForce24HourTime`
* **Windows**: Read via PowerShell `(Get-Culture).DateTimeFormat.ShortTimePattern`
* **Others**: Use `Intl.DateTimeFormat` to format 13:00 and check if the result contains "13"

The final time formatting result looks like: "Wednesday, February 18th, 2026 — 8:49 AM".

## 17.1.3 Prompt Report (`src/agents/system-prompt-report.ts`)

When the system prompt construction is complete, OpenClaw generates a **diagnostic report** (`SessionSystemPromptReport`) to monitor and debug prompt token consumption. This is critical for preventing prompt bloat from overflowing the context window.

### Report Structure

```typescript
// src/agents/system-prompt-report.ts (inferred report structure)
type SessionSystemPromptReport = {
  source: string;          // Prompt source identifier
  generatedAt: number;     // Generation timestamp
  sessionId?: string;
  sessionKey?: string;
  provider?: string;
  model?: string;
  workspaceDir?: string;
  bootstrapMaxChars: number; // Bootstrap file max characters
  sandbox?: { ... };       // Sandbox configuration
  systemPrompt: {
    chars: number;           // Total characters
    projectContextChars: number;   // Project context characters
    nonProjectContextChars: number; // Non-project context characters
  };
  injectedWorkspaceFiles: Array<{
    name: string;
    path: string;
    missing: boolean;
    rawChars: number;        // Raw character count
    injectedChars: number;   // Injected character count
    truncated: boolean;      // Whether truncated
  }>;
  skills: {
    promptChars: number;     // Total skills prompt characters
    entries: Array<{ name: string; blockChars: number }>;
  };
  tools: {
    listChars: number;       // Tool list characters
    schemaChars: number;     // Tool JSON Schema total characters
    entries: Array<{
      name: string;
      summaryChars: number;
      schemaChars: number;
      propertiesCount: number | null;
    }>;
  };
};
```

### Skill Parsing: parseSkillBlocks

The report needs to know how many characters each skill occupies. `parseSkillBlocks` uses regular expressions to extract individual `<skill>` blocks from the skills XML:

```typescript
function parseSkillBlocks(
  skillsPrompt: string
): Array<{ name: string; blockChars: number }> {
  const blocks = Array.from(
    skillsPrompt.matchAll(/<skill>[\s\S]*?<\/skill>/gi)
  ).map((match) => match[0] ?? "");
  
  return blocks.map((block) => {
    const name = block.match(/<name>\s*([^<]+?)\s*<\/name>/i)?.[1]?.trim() 
      || "(unknown)";
    return { name, blockChars: block.length };
  }).filter((b) => b.blockChars > 0);
}
```

### Tool Statistics: buildToolsEntries

The description length and JSON Schema size of each tool are counted:

```typescript
function buildToolsEntries(
  tools: AgentTool[]
): Array<{ name; summaryChars; schemaChars; propertiesCount }> {
  return tools.map((tool) => {
    const summaryChars = (tool.description || tool.label || "").length;
    const schemaChars = tool.parameters 
      ? JSON.stringify(tool.parameters).length 
      : 0;
    const propertiesCount = tool.parameters?.properties
      ? Object.keys(tool.parameters.properties).length
      : null;
    return { name: tool.name, summaryChars, schemaChars, propertiesCount };
  });
}
```

### Injected File Statistics: buildInjectedWorkspaceFiles

For each bootstrap file, the report records its raw size, injected size, and whether it was truncated:

```typescript
function buildInjectedWorkspaceFiles(params: {
  bootstrapFiles: WorkspaceBootstrapFile[];
  injectedFiles: EmbeddedContextFile[];
  bootstrapMaxChars: number;
}): SessionSystemPromptReport["injectedWorkspaceFiles"] {
  const injectedByName = new Map(
    params.injectedFiles.map((f) => [f.path, f.content])
  );
  return params.bootstrapFiles.map((file) => {
    const rawChars = file.missing ? 0 : (file.content ?? "").trimEnd().length;
    const injected = injectedByName.get(file.name);
    const injectedChars = injected ? injected.length : 0;
    const truncated = !file.missing && rawChars > params.bootstrapMaxChars;
    return {
      name: file.name,
      path: file.path,
      missing: file.missing,
      rawChars,
      injectedChars,
      truncated,
    };
  });
}
```

### Main Uses of the Report

1. **Token Budget Monitoring**: Through `systemPrompt.chars` and the character counts of each subsection, operations staff can quickly identify which part caused prompt bloat.
2. **Truncation Alerts**: When bootstrap files exceed `bootstrapMaxChars` (default 20,000 characters) and are truncated, the `truncated` flag in the report triggers an alert.
3. **Tool Audit**: `tools.schemaChars` counts the total size of all tool JSON Schemas. When external tools provided by MCP are excessive, the Schema may consume large amounts of context space, and the report helps identify such issues.
4. **Skill Overhead Analysis**: `skills.entries` lists the character count of each skill block, helping identify oversized skill definitions.

***

## Section Summary

1. **System prompt** is the core mechanism for controlling Agent behavior in OpenClaw, adopting a **modular assembly** pattern — over a dozen feature sections are dynamically concatenated based on runtime conditions.
2. **Three PromptModes** (full/minimal/none) provide different verbosity levels for different scenarios: main Agents get complete instructions, sub-Agents get a streamlined version, and ultra-minimal mode retains only the identity declaration.
3. **Runtime parameters** (`buildSystemPromptParams`) are responsible for parsing timezone, time format, Git repository root directory, and other environment information, using a "configuration priority, system detection fallback" strategy.
4. **Prompt report** (`buildSystemPromptReport`) creates detailed statistics for each prompt generation, serving as the first line of defense against context window overflow.
5. **Prompt size management** is a key challenge — bootstrap file truncation, tool Schema statistics, and skill character counting together form OpenClaw's token budget management system.
