Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

26.9 KB
Raw Blame
import { MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET, MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'
import {
    buildAvailableToolsBlock,
    buildQueryToolsBlock,
    buildToolDomainsBlock,
    buildToolDomainsCompact,
    type QueryToolInfo,
    type ToolInfo,
} from '@/lib/instructions'
import { formatPrompt } from '@/lib/utils'
import ACTIVITY_HISTORY_SQL from '@/templates/sections/activity-history-sql.md'
import ACTIVITY_HISTORY from '@/templates/sections/activity-history.md'
import AGENT_FEEDBACK from '@/templates/sections/agent-feedback.md'
import ANALYSIS_ARTIFACTS from '@/templates/sections/analysis-artifacts.md'
import BASIC_FUNCTIONALITY from '@/templates/sections/basic-functionality.md'
import BUSINESS_KNOWLEDGE_FIRST from '@/templates/sections/business-knowledge-first.md'
import CATALOG_TRUST_DISCOVERY from '@/templates/sections/catalog-trust-discovery.md'
import CLI_DATA_DISCOVERY from '@/templates/sections/cli-data-discovery.md'
import CLI_ERROR_HANDLING from '@/templates/sections/cli-error-handling.md'
import CLI_EXAMPLES_CLAUDE from '@/templates/sections/cli-examples-claude.md'
import CLI_EXAMPLES from '@/templates/sections/cli-examples.md'
import CLI_LEARN_COMPACT from '@/templates/sections/cli-learn-compact.md'
import CLI_LEARN from '@/templates/sections/cli-learn.md'
import CLI_RENDERING from '@/templates/sections/cli-rendering.md'
import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'
import CLI_SYNTAX from '@/templates/sections/cli-syntax.md'
import COMPACT_INSTRUCTIONS from '@/templates/sections/compact-instructions.md'
import ENTITY_SCHEMA_DISCOVERY from '@/templates/sections/entity-schema-discovery.md'
import ENV_CONTEXT from '@/templates/sections/env-context.md'
import EXAMPLES from '@/templates/sections/examples.md'
import EXEC_LEARN from '@/templates/sections/exec-learn.md'
import EXEC_TOOL_BLURB_COMPACT from '@/templates/sections/exec-tool-blurb-compact.md'
import EXEC_TOOL_BLURB from '@/templates/sections/exec-tool-blurb.md'
import EXPLAIN_CHART from '@/templates/sections/explain-chart.md'
import INBOX_FIRST from '@/templates/sections/inbox-first.md'
import METRIC_DISCOVERY_COMPACT from '@/templates/sections/metric-discovery-compact.md'
import METRIC_DISCOVERY from '@/templates/sections/metric-discovery.md'
import NOTEBOOK_PYTHON from '@/templates/sections/notebook-python.md'
import NOTEBOOK_RUN from '@/templates/sections/notebook-run.md'
import NOTEBOOK_SQL from '@/templates/sections/notebook-sql.md'
import PROJECT_SCOPE from '@/templates/sections/project-scope.md'
import RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'
import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'
import SKILLS_FIRST from '@/templates/sections/skills-first.md'
import TOOL_SEARCH from '@/templates/sections/tool-search.md'
import URL_PATTERNS from '@/templates/sections/url-patterns.md'
import { type ExecLearnGuide, LEARN_COMMAND_LINE } from '@/tools/exec-learn'
import type { BusinessKnowledgeContent } from '@/tools/types'

/** Naming a command the catalog withholds sends the agent down a path it cannot take. */
const WHATS_NEW_WITH_DOCS_SEARCH =
    "Check what's new with `call docs-search <json_input>` or the changelog (https://posthog.com/changelog.md)."
const WHATS_NEW_CHANGELOG_ONLY = "Check what's new in the changelog (https://posthog.com/changelog.md)."

const PROJECT_LOOKUP =
    'Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range.'
const GROUP_TYPES_LOOKUP = "For the project's group types, run `execute-sql` on `system.group_type_mappings`."
const SWITCH_TOOLS = ['switch-project', 'switch-organization', 'projects-get', 'organizations-get']
const SWITCH_LOOKUP =
    'To work in another project or organization, call `switch-project` or `switch-organization`. `projects-get` and `organizations-get` resolve a name to the id they take. Do not search the tool list for this.'

export interface InstructionsContext {
    guidelines: string
    tools?: ToolInfo[] | undefined
    queryTools?: QueryToolInfo[] | undefined
    /** Whether `render-ui` is actually available to this client (i.e. the client is
     *  an MCP Apps host). Gates the CLI rendering section so it never reaches clients —
     *  like Claude Code — that can't mount the iframe. */
    renderUiEnabled?: boolean | undefined
    /** Whether the notebook cell tools (`notebooks-add-cell` and friends) are
     *  advertised to this client. Gates the Python-in-a-notebook section so we never
     *  tell an agent to put its analysis in a cell type it can't create. */
    notebookCellsEnabled?: boolean | undefined
    /** Whether `notebooks-run` is advertised to this client. Gated separately from
     *  the cell tools, because a connection can carry the cell tools without the
     *  run tool, and naming a command the catalog withholds sends the agent to a
     *  name `search` and `call` cannot resolve. */
    notebookRunEnabled?: boolean | undefined
    /** Whether `docs-search` is advertised to this client. Gates every mention of
     *  the tool, so the prompt never names a command `search` and `call` cannot
     *  resolve. Carried as a field rather than derived from `tools`, which
     *  `buildExecCommandReference` drops on purpose. */
    docsSearchEnabled?: boolean | undefined
    /** Whether the Replay Vision scan tools are advertised to this client. Same reason
     *  as `docsSearchEnabled`: the line names three tools, and the reference drops `tools`. */
    replayVisionEnabled?: boolean | undefined
    businessKnowledgeContent?: BusinessKnowledgeContent | undefined
    /** Set only when the experiment flag is on and the report list and retrieve tools are advertised. */
    inboxFirstEnabled?: boolean | undefined
    /** Read-only connections lack `inbox-reports-claim`, so they get no pull-request line. */
    inboxClaimEnabled?: boolean | undefined
}

const REPLAY_VISION_TOOLS = ['vision-scanners-inline-scan', 'vision-requests-create', 'vision-requests-get']
const REPLAY_VISION =
    'To learn what happened inside session recordings (what users did, saw, or struggled with), use Replay Vision instead of SQL over the replay tables. Call `vision-scanners-inline-scan` with `session_ids` and a `prompt` for sessions you already have, or `vision-requests-create` for up to 200 sessions and read the result with `vision-requests-get`. SQL over `session_replay_events` returns recording metadata only, such as duration, URLs and event counts; use it to find candidate sessions.'

const BUSINESS_KNOWLEDGE_SEARCH_TOOL = 'business-knowledge-documents-search'
const BUSINESS_KNOWLEDGE_REPO_SEARCH_TOOL = 'business-knowledge-repositories-search'

function businessKnowledgeSearchLine(execSyntax: boolean): string {
    if (execSyntax) {
        return `- The user's own company, product, terms, or policies: run \`call ${BUSINESS_KNOWLEDGE_SEARCH_TOOL} <json_input>\` with a short, broad query.`
    }
    return `- The user's own company, product, internal terms, policies, or decisions: call \`${BUSINESS_KNOWLEDGE_SEARCH_TOOL}\` with a short, broad query. If \`business-knowledge-document-window-retrieve\` is also available, use it when a result needs more context.`
}

/** The exec line stays short to keep the exec description under Claude Code's 2048-char cap. */
function businessKnowledgeRepoSearchLine(execSyntax: boolean, hasDocumentSearch: boolean): string {
    if (execSyntax) {
        const topic = hasDocumentSearch ? "The user's own code, or doc misses" : "The user's own company, code, or docs"
        return `- ${topic}: \`call ${BUSINESS_KNOWLEDGE_REPO_SEARCH_TOOL} <json_input>\`.`
    }
    const topic = hasDocumentSearch
        ? "The user's own code, or a company question that document search does not answer"
        : "The user's own company, product, code, or docs"
    return `- ${topic}: call \`${BUSINESS_KNOWLEDGE_REPO_SEARCH_TOOL}\` with file names or topic words, not a sentence. Each repository includes its description. When a description names a handbook or docs, search that repository for those words, read the file, and cite its permalink.`
}

/** A data request can name a company term, such as "activated user", that no event or property name explains. */
const BUSINESS_KNOWLEDGE_DATA_REQUEST_EXCEPTION =
    ', except to look up in business knowledge a company term that you cannot map to an event or property'

/** The SQL section's bullets that name a tool. Each one is left out when the connection
 *  lacks a tool it names, so the guidance never sends the agent to a name it cannot call. */
function notebookSqlVars(ctx: InstructionsContext): Record<string, string> {
    const available = (tool: string): boolean => ctx.tools?.some(({ name }) => name === tool) ?? false
    const runAll = available('notebooks-run') ? ', or all at once with `notebooks-run`' : ''
    return {
        throwaway_checks: available('execute-sql')
            ? " Use `execute-sql` only for throwaway checks the notebook does not rely on, like confirming a table's columns."
            : '',
        fix_in_place:
            available('notebooks-update-cell') && available('notebooks-delete-cell')
                ? '- Fix a failing or wrong query in the same cell with `notebooks-update-cell`, and remove dead ends with `notebooks-delete-cell`, so the notebook keeps only the steps the conclusion rests on.'
                : '',
        run_later: available('notebooks-run-cell')
            ? `- To lay out dependent cells before running them, add them with \`run: false\`, then run them in order with \`notebooks-run-cell\`${runAll}.`
            : '',
    }
}

/** Resolve the field, falling back to the advertised tool list for callers that
 *  build a context without it (the CLI's `--agent-help`). */
function docsSearchAvailable(ctx: InstructionsContext): boolean {
    return ctx.docsSearchEnabled ?? ctx.tools?.some(({ name }) => name === 'docs-search') ?? false
}

function replayVisionAvailable(ctx: InstructionsContext): boolean {
    return (
        ctx.replayVisionEnabled ??
        REPLAY_VISION_TOOLS.every((tool) => ctx.tools?.some(({ name }) => name === tool)) ??
        false
    )
}

function envContextSections(ctx: InstructionsContext): string[] {
    const available = (tool: string): boolean => ctx.tools?.some(({ name }) => name === tool) ?? false
    const lookups = [
        ...(available('project-get') ? [PROJECT_LOOKUP] : []),
        ...(SWITCH_TOOLS.every(available) ? [SWITCH_LOOKUP] : []),
        ...(available('execute-sql') ? [GROUP_TYPES_LOOKUP] : []),
    ]
    return lookups.length > 0 ? [formatPrompt(ENV_CONTEXT, { env_lookups: lookups.join(' ') })] : []
}

/**
 * Composes MCP instruction prompts for the two client modes (tools-mode and
 * single-exec). Each mode declares an ordered list of subprompts under
 * `services/mcp/src/templates/sections/`; subprompts that appear in multiple
 * modes live in a single file, so prose can't drift.
 */
export class InstructionsFormatter {
    private knowledgeFirstSections(ctx: InstructionsContext): string[] {
        return this.knowledgeFirstSectionsForCapabilities({
            docsSearchEnabled: docsSearchAvailable(ctx),
            businessKnowledgeSearchEnabled: ctx.tools?.some(({ name }) => name === BUSINESS_KNOWLEDGE_SEARCH_TOOL),
            businessKnowledgeRepoSearchEnabled: ctx.tools?.some(
                ({ name }) => name === BUSINESS_KNOWLEDGE_REPO_SEARCH_TOOL
            ),
            businessKnowledgeContent: ctx.businessKnowledgeContent,
            execSyntax: false,
        })
    }

    /** In tools mode a bare name is how the agent calls a tool. In exec mode this
     *  mandate leads the tool description, ahead of the section that teaches the
     *  dispatcher grammar, so a bare name reads as a command and is rejected. */
    private knowledgeFirstSectionsForCapabilities(opts: {
        docsSearchEnabled?: boolean | undefined
        businessKnowledgeSearchEnabled?: boolean | undefined
        businessKnowledgeRepoSearchEnabled?: boolean | undefined
        businessKnowledgeContent?: BusinessKnowledgeContent | undefined
        execSyntax: boolean
    }): string[] {
        if (!opts.docsSearchEnabled) {
            return []
        }
        const documentSearch =
            opts.businessKnowledgeSearchEnabled === true && opts.businessKnowledgeContent?.hasSources !== false
        const repoSearch =
            opts.businessKnowledgeRepoSearchEnabled === true && opts.businessKnowledgeContent?.hasRepositories !== false
        const searchLines = [
            ...(documentSearch ? [businessKnowledgeSearchLine(opts.execSyntax)] : []),
            ...(repoSearch ? [businessKnowledgeRepoSearchLine(opts.execSyntax, documentSearch)] : []),
            `- PostHog features, SDKs, setup, or pricing: ${
                opts.execSyntax ? 'run `call docs-search <json_input>`' : 'call the `docs-search` tool'
            }.`,
        ]
        return [
            formatPrompt(BUSINESS_KNOWLEDGE_FIRST, {
                search_lines: searchLines.join('\n'),
                data_request_exception: documentSearch || repoSearch ? BUSINESS_KNOWLEDGE_DATA_REQUEST_EXCEPTION : '',
            }),
        ]
    }

    /** Kept out of the exec tool description: Claude Code cuts it at 2,048 characters. */
    private inboxFirstSections(ctx: InstructionsContext, execSyntax: boolean): string[] {
        if (!ctx.inboxFirstEnabled) {
            return []
        }
        const toolRef = (name: string): string =>
            execSyntax ? `\`call ${name} <json_input>\`` : `the \`${name}\` tool`
        return [
            formatPrompt(INBOX_FIRST, {
                inbox_list: toolRef('inbox-reports-list'),
                inbox_retrieve: toolRef('inbox-reports-retrieve'),
                inbox_claim_line: ctx.inboxClaimEnabled
                    ? `- When you fix the problem, attach your pull request to the report with ${toolRef('inbox-reports-claim')} and \`pr_url\`. Its merge then resolves the report.`
                    : '',
            }),
        ]
    }

    /** Artifact-choice guidance: notebook vs dashboard vs insight, plus the
     *  SQL-and-Python-go-in-cells rules when the notebook cell tools are available, and
     *  the refresh-a-notebook rule when the run tool is. */
    private artifactSections(ctx: InstructionsContext): string[] {
        return [
            ANALYSIS_ARTIFACTS,
            ...(ctx.tools?.some(({ name }) => name === 'explain-chart')
                ? [
                      formatPrompt(EXPLAIN_CHART, {
                          explain_chart_link_line: ctx.tools.some(({ name }) => name === 'explain-chart-save')
                              ? 'Where the conversation cannot show the chart explanation, call `explain-chart-save` with the same arguments and give the person the link it returns, which opens it beside the chart in PostHog.'
                              : '',
                      }),
                  ]
                : []),
            ...(ctx.notebookCellsEnabled ? [formatPrompt(NOTEBOOK_SQL, notebookSqlVars(ctx)), NOTEBOOK_PYTHON] : []),
            ...(ctx.notebookRunEnabled ? [NOTEBOOK_RUN] : []),
        ]
    }

    private activityHistorySections(ctx: InstructionsContext): string[] {
        if (!ctx.tools?.some(({ name }) => name === 'advanced-activity-logs-list')) {
            return []
        }
        return [
            ACTIVITY_HISTORY,
            ...(ctx.tools.some(({ name }) => name === 'execute-sql') ? [ACTIVITY_HISTORY_SQL] : []),
        ]
    }

    /** Build the system prompt for tools-mode clients (each tool registered separately). */
    buildToolsInstructions(ctx: InstructionsContext): string {
        return this.compose(
            [
                PROJECT_SCOPE,
                BASIC_FUNCTIONALITY,
                ...this.knowledgeFirstSections(ctx),
                ...this.inboxFirstSections(ctx, false),
                TOOL_SEARCH,
                METRIC_DISCOVERY,
                RETRIEVING_DATA,
                SCHEMA_WORKFLOW,
                CATALOG_TRUST_DISCOVERY,
                ...this.artifactSections(ctx),
                ...this.activityHistorySections(ctx),
                ...envContextSections(ctx),
                URL_PATTERNS,
                AGENT_FEEDBACK,
                EXAMPLES,
            ],
            ctx,
            { compact: false }
        )
    }

    /** Build the compact `instructions` payload for single-exec clients. Everything
     *  but the tool-domain index lives on the exec tool's
     *  `command` parameter description (`buildExecCommandReference`), because this
     *  payload is hard-capped at {@link MCP_INSTRUCTIONS_CHAR_BUDGET} by Claude Code
     *  and the command description is not.
     *
     *  Rendered optimistically, then re-rendered against the measured overflow if it
     *  doesn't fit — the index is the only part that can shrink. Measuring the overflow
     *  rather than the surround keeps the arithmetic exact: both renders carry a
     *  non-empty index, so they share a byte-identical surround, and shrinking the index
     *  by N shrinks the payload by exactly N. (Sizing an index-less render instead
     *  overshoots, because `formatPrompt` trims the trailing separator the real payload
     *  keeps.) Enforced by the budget test in `instructions-formatter-snapshot.test.ts`. */
    buildExecInstructions(ctx: InstructionsContext): string {
        const sections = [COMPACT_INSTRUCTIONS]
        const rendered = this.compose(sections, ctx, { compact: true })
        const overflow = rendered.length - MCP_INSTRUCTIONS_CHAR_BUDGET
        if (overflow <= 0) {
            return rendered
        }
        const domains = buildToolDomainsCompact(ctx.tools ?? [])
        return this.compose(sections, ctx, {
            compact: true,
            toolDomainsMaxChars: domains.length - overflow,
        })
    }

    /** Build the top-level description of the `posthog:exec` tool. Lives in the
     *  uncapped top-level `description`, so the skills text costs no schema budget.
     *  Project clarification and the skills mandate lead the description to reach
     *  an agent before its first tool call, and agents that answer PostHog-behavior
     *  questions by cloning the public repo never make a call for the gate to catch. */
    buildExecToolDescription(
        opts: {
            skillsEnabled?: boolean | undefined
            docsSearchEnabled?: boolean | undefined
            businessKnowledgeSearchEnabled?: boolean | undefined
            businessKnowledgeRepoSearchEnabled?: boolean | undefined
            businessKnowledgeContent?: BusinessKnowledgeContent | undefined
        } = {}
    ): string {
        const knowledgeSections = this.knowledgeFirstSectionsForCapabilities({ ...opts, execSyntax: true })
        const hasMandate = opts.skillsEnabled || knowledgeSections.length > 0
        return [
            PROJECT_SCOPE,
            ...(opts.skillsEnabled ? [SKILLS_FIRST] : []),
            ...knowledgeSections,
            hasMandate ? EXEC_TOOL_BLURB_COMPACT : EXEC_TOOL_BLURB,
        ]
            .map((section) => section.trim())
            .join('\n\n')
    }

    /**
     * Build the optional guidance catalog used by Claude web/desktop. The
     * existing prompt sections remain the source of truth; only their delivery
     * moves from the advertised schema to `exec learn`.
     */
    buildClaudeExecLearnGuides(ctx: InstructionsContext): ExecLearnGuide[] {
        const entries: ExecLearnGuide[] = [
            {
                id: 'analytics',
                title: 'Analytics',
                description:
                    'Query or analyze PostHog data; governed metrics, certified tables, and verified joins live in the catalog.',
                content: this.compose(
                    [
                        METRIC_DISCOVERY,
                        RETRIEVING_DATA,
                        SCHEMA_WORKFLOW,
                        CATALOG_TRUST_DISCOVERY,
                        ...this.artifactSections(ctx),
                        ...this.activityHistorySections(ctx),
                        EXAMPLES,
                    ],
                    ctx,
                    { compact: false }
                ),
            },
        ]

        if (ctx.renderUiEnabled) {
            entries.push({
                id: 'visualizations',
                title: 'Visualizations',
                description: 'Create or render a visualization.',
                content: this.compose([CLI_RENDERING], ctx, { compact: false }),
            })
        }

        // URL rules are task-specific and load on demand instead of consuming Claude's capped input schema.
        entries.push({
            id: 'urls',
            title: 'URL patterns',
            description: 'Load before writing any PostHog app link or URL.',
            content: this.compose([URL_PATTERNS], ctx, { compact: false }),
        })

        entries.push({
            id: 'feedback',
            title: 'Feedback',
            description: 'Send feedback about PostHog.',
            content: this.compose([AGENT_FEEDBACK], ctx, { compact: false }),
        })

        return entries
    }

    /**
     * claude.ai's registry silently drops a tool whose serialized `inputSchema`
     * crosses ~16,384 chars. This reference lands in
     * `inputSchema.properties.command.description`, so keep routine tool-use
     * guidance inline and move only task-specific sections behind `learn <topic...>`.
     * Enforced by the budget test in `instructions-formatter-snapshot.test.ts`.
     */
    buildClaudeExecCommandReference(
        ctx: InstructionsContext,
        opts: { learnEnabled?: boolean; skillsEnabled?: boolean } = {}
    ): string {
        const learnEnabled = opts.learnEnabled ?? true
        const skillsEnabled = opts.skillsEnabled ?? false
        const learnGuides = this.buildClaudeExecLearnGuides(ctx)
        const learnGuideList = learnGuides.map((entry) => `- ${entry.id}: ${entry.description}`).join('\n')
        const learnSection = learnEnabled ? formatPrompt(EXEC_LEARN, { help_topics: learnGuideList }) : undefined
        const renderCtx: InstructionsContext = {
            guidelines: ctx.guidelines,
            tools: ctx.tools,
        }

        return this.compose(
            [
                CLI_SYNTAX,
                // Compact skills-first variant: this reference lives inside the
                // schema-capped `command` description (see the budget test), so the
                // content-routing paragraph is reserved for the uncapped full reference.
                ...(skillsEnabled ? [CLI_LEARN_COMPACT] : []),
                ...(learnSection ? [learnSection] : []),
                METRIC_DISCOVERY_COMPACT,
                CLI_SCHEMA_DRILLDOWN,
                CLI_DATA_DISCOVERY,
                CLI_EXAMPLES_CLAUDE,
                CLI_ERROR_HANDLING,
                BASIC_FUNCTIONALITY,
                TOOL_SEARCH,
                ...envContextSections(ctx),
                // URL patterns live behind `learn urls` to protect the schema budget;
                // with learn unavailable there is no topic to load, so stay inline.
                ...(learnSection ? [] : [URL_PATTERNS]),
                ...(learnSection ? [] : this.activityHistorySections(ctx)),
            ],
            renderCtx,
            {
                compact: false,
                compactToolDomains: true,
                toolDomainsMaxChars: MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET,
                extraCommands: learnEnabled ? LEARN_COMMAND_LINE : undefined,
            }
        )
    }

    /** Build the `command` parameter description for the exec tool. The
     *  query-tool catalog lives here: in single-exec mode `instructions` only
     *  carries the `query` tool domain.
     *
     *  Claude web/desktop uses `buildClaudeExecCommandReference` instead because
     *  its complete JSON schema has a smaller client-enforced size budget. */
    buildExecCommandReference(ctx: InstructionsContext, opts: { learnEnabled?: boolean } = {}): string {
        const sections = [
            CLI_SYNTAX,
            ...(opts.learnEnabled ? [CLI_LEARN] : []),
            ...this.inboxFirstSections(ctx, true),
            METRIC_DISCOVERY,
            CLI_SCHEMA_DRILLDOWN,
            CLI_DATA_DISCOVERY,
            CLI_EXAMPLES,
            CLI_ERROR_HANDLING,
            ...(ctx.renderUiEnabled ? [CLI_RENDERING] : []),
            BASIC_FUNCTIONALITY,
            TOOL_SEARCH,
            RETRIEVING_DATA,
            SCHEMA_WORKFLOW,
            CATALOG_TRUST_DISCOVERY,
            ...this.artifactSections(ctx),
            ...this.activityHistorySections(ctx),
            ...envContextSections(ctx),
            URL_PATTERNS,
            AGENT_FEEDBACK,
            EXAMPLES,
        ]
        const renderCtx: InstructionsContext = {
            ...ctx,
            tools: undefined,
            docsSearchEnabled: docsSearchAvailable(ctx),
            replayVisionEnabled: replayVisionAvailable(ctx),
        }
        // Tool domains are temporarily omitted from the command reference while we
        // probe claude.ai's per-tool size cap (it silently drops oversized entries);
        // agents still discover domains at runtime via the `search` command, and
        // `instructions`-honoring clients keep the compact domain index there.
        return this.compose(sections, renderCtx, { compact: false })
    }

    private compose(
        sections: string[],
        ctx: InstructionsContext,
        opts: {
            compact: boolean
            compactToolDomains?: boolean
            extraCommands?: string
            /** Character budget for the domain index; it collapses sub-families to fit. */
            toolDomainsMaxChars?: number
        }
    ): string {
        const renderToolDomains =
            opts.compact || opts.compactToolDomains
                ? (tools: ToolInfo[]) => buildToolDomainsCompact(tools, opts.toolDomainsMaxChars)
                : buildToolDomainsBlock
        // `{query_tools}` only appears in non-compact sections (the exec command
        // reference and tools-mode instructions); compact mode surfaces queries
        // via the single `query` tool domain instead.
        const vars = {
            guidelines: ctx.guidelines.trim(),
            available_tools: buildAvailableToolsBlock(ctx.renderUiEnabled),
            tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',
            query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',
            entity_schema_discovery: ENTITY_SCHEMA_DISCOVERY.trim(),
            replay_vision: replayVisionAvailable(ctx) ? REPLAY_VISION : '',
            extra_commands: opts.extraCommands ?? '',
            whats_new_check: docsSearchAvailable(ctx) ? WHATS_NEW_WITH_DOCS_SEARCH : WHATS_NEW_CHANGELOG_ONLY,
        }
        const body = sections
            .map((s) => s.trim())
            .filter((s) => s.length > 0)
            .join('\n\n')
        // An empty placeholder on its own line would otherwise leave a double blank line.
        return formatPrompt(body, vars).replace(/\n{3,}/g, '\n\n')
    }
}