Skip to content

Subcontext hierarchies

Subcontext lets you organize related context items as a parent with one or more child items (one level deep). When a parent is selected for a consumer, its children can be included automatically — either always or only when relevant to the current task.

Subcontext hierarchy is enabled by default. Site builders can turn it off at Context item settings (/admin/config/ai/context/settings/items).

When to use subcontext

  • Large topics — split broad context (for example, "Product catalog") into focused child items ("Electronics", "Clothing", "Home goods").
  • Editorial grouping — keep related detail together under one parent in the admin UI and in consumer configuration.
  • Token-focused workflows — use conditional children so detail is included only when the task warrants it (see Token and selection tradeoffs).

When to skip it

  • You have a small, flat set of context items and scopes already narrow selection enough.
  • Your team wants the simplest editorial model first — every item top-level, no parent/child concepts.
  • You are not ready to configure an AI provider for conditional subcontext (required subcontext still works without a provider).

Required vs conditional children

Each child has a subcontext type:

Type Behavior
Required Selected when the parent is selected and the child passes the checks in How children get selected. Rendering can still shorten or omit its content at the token limit.
Conditional Included only when Enable conditional subcontext AI decisions is on and the configured AI provider/model decides the child is relevant to the current task. Requires an AI provider/model in general settings.

If Enable conditional subcontext AI decisions is off, conditional children are excluded from normal context selection (no AI call). They may still be included when selected by other paths — for example, a consumer's Always include list, custom scope, or exact-match rules. Required children are still included when their parent is selected and they pass the child checks.

If conditional AI decisions are enabled but no AI provider/model is configured, conditional subcontext is unavailable in the item form and existing conditional children are ignored at runtime until a provider is configured. If provider selection fails at runtime, conditional children are skipped rather than included by default. The same fail-closed behavior applies when the decision cap is exhausted, the response is invalid, the provider does not support chat, or the provider throws an exception. Required children remain selected in these cases. The cap applies to each context resolution call: a page request or agent run can make several resolution calls, for example one when the system prompt is built and one for each call of the Load AI Context Items tool or its deprecated alias. See Debugging for warning categories.

Configure the provider at General settings.

The current task

The conditional decision compares the Purpose of each child with the current task. The current task depends on how CCC gets the request:

Path Current task
Automatic context for an AI agent The user request: the latest user message of the agent chat input. An agent that another agent calls as a tool has no chat input. For this agent, the current task is the task that the caller gave it. When the caller gives only a chat history, the current task is the latest user message of this history.
Automatic context for other AI chat requests The latest user message.
Load AI Context Items tool The task value of the tool call. This value is optional.
Get Relevant AI Context Items tool The task value of the tool call.

The agent system prompt is never the current task. It describes the agent, not the request. When the request has no user text, the current task is empty. CCC reads the request of an agent when the agent run starts, and keeps it for all loops of the run. See Events.

In 1.0.0-rc2 and earlier, the current task on agents was the agent system prompt. See API stability: Upgrade from 1.0.0-rc2.

What the decision provider receives

The decision prompt contains the first 500 characters of the current task. The provider in AI Provider/Model on General settings receives this prompt. This provider can be different from the provider of your agents.

The user request can contain personal data. If you do not want to send the user request to the decision provider, do one of these:

When conditional AI is disabled

When Enable conditional subcontext AI decisions is off:

  • Conditional children are excluded during normal subcontext resolution.
  • Required children are still included with their parent when they pass the child checks.
  • Conditional children can still appear via agent Always include, custom scope, or other non-subcontext selection paths.

The admin UI helps editors understand this state:

  • On the context items listing, conditional child rows are visually de-emphasized (ghosted) and expose status text plus a link to Context item settings.
  • Editing a conditional child shows a warning that the item is excluded from normal selection until the toggle is re-enabled.

Use the ?fieldset= query parameter to open a settings fieldset directly — for example, /admin/config/ai/context/settings/items?fieldset=subcontext. See Settings deep links.

Writing Purpose for conditional children

When Conditional subcontext AI is enabled, the provider receives each candidate child's ID and Purpose (plus a snippet of parent Content and the current task). Purpose is the primary editorial control for inclusion decisions — not the child label, description, or full content.

Good Purpose examples

Write concrete, task-oriented criteria:

  • Include for returns, refunds, exchanges, and cancellation-policy questions.
  • Include for delivery timing, shipping methods, fulfillment, and delivery-location questions.
  • Include for image selection, photography style, and brand imagery questions.

Anti-patterns to avoid

Problem Example Why it fails
Vague Useful supporting information. Matches too many unrelated tasks.
Overlapping siblings Pricing: purchasing-cost questions. Shipping: delivery charges. Shared wording can cause false positives when both children are candidates.
Too broad Include for product page work. Selects on weak intent instead of a specific need.

Prefer distinct, non-overlapping Purpose text across sibling conditional children. Optional routing rules in parent Content can help edge cases, but clear Purpose values should be the default approach.

Creating subcontext items

From the context items listing (/admin/config/ai/context/items):

  1. Create or edit a parent (top-level) item.
  2. Use Add subcontext on the parent row to create a child with the parent pre-filled.
  3. Choose Required or Conditional in the subcontext settings fieldset.
  4. In the Context Scope section, leave Same as parent checked to use the parent's scope, or uncheck it to customize scope for this child (see Parent scope).

See Context items for field descriptions. Persistence rules (one level deep, validation on save) are summarized there.

Token and selection tradeoffs

Required-only subcontext: When a parent is selected, all required children are selected. That can use more tokens than a smaller parent alone, but the token limit can still shorten or omit their rendered content.

Conditional subcontext: Adds an LLM step to choose which conditional children match the current task. That step has latency and API cost, but may reduce tokens compared to always injecting all child content. Results depend on your provider, prompts, item sizes, and task patterns — there is no guaranteed cost or token savings. Evaluate with your own content and usage tracking.

In all cases, rendering is still capped by Max tokens for injection in general settings; content may be truncated if the budget is exceeded.

Limits interaction

General settings define Max global context items and Max tokens for injection:

  1. Max global context items limits only the Global priority group.
  2. Parent items and their required or selected conditional children are merged without a total item-count limit.
  3. Max tokens applies to the final rendered output for all parent and child items together.

See Configuration for the global-item and token-budget settings.

Parent scope

Subcontext items can use the parent's scope instead of storing their own scope values. On the item form, the Same as parent checkbox (enabled by default for new children) controls this behavior.

Parent scope Stored scope on child Effective scope at runtime
Uses parent Cleared on save (empty scope, no entity items) Parent's scope values
Custom Saved on the child Child's own scope values

The effective scope is resolved through AiContextItem::getScopeItem(). Scope plugins, the scope index, global detection, and entity item matching all use this resolved scope — not the child's empty stored values while parent scope is active (inherit_parent_scope / inheritsParentScope()).

Specific Entities scope

Specific Entities scope is stored in the Entity items field (dynamic entity references), not in the scope field. When parent scope is active:

  • The child uses the parent's entity items for matching and selection.
  • Any entity items previously stored on the child are cleared on save.
  • The edit form shows scope and entity item fields only when Same as parent is unchecked; the summary reflects values stored on the child, not the parent's values.

When parent scope is off, the child uses its own entity items like any top-level item.

Scope index and parent updates

The scope index stores effective scope values per item ID. For children with parent scope active, indexed rows mirror the parent's scope values (language, use case, tag, and so on).

When a parent item is updated, those children are reindexed automatically so SQL prefiltering and admin listings stay aligned with the parent's current scope. Custom-scope children are reindexed from their own stored values only.

Entity item references are not stored in the scope index table; Specific Entities behavior for parent-scope children is evaluated at runtime from the parent's DER field.

Selection behavior

Children with parent scope active are not top-level selection candidates. The selector skips items with inheritsParentScope() during the main published-item scan, so a child cannot appear as a global item, score against consumer subscriptions, or enter via match-all because it mirrors the parent's scope.

Those children are included only when:

  • Their parent is selected and subcontext resolution adds them (required or conditional), or
  • They are listed in the agent's Always include overrides.

Custom-scope children (inherit_parent_scope disabled) remain eligible as top-level candidates. For example, a child that sets its own Global scope can be selected independently of its parent. Prefer leaving Same as parent checked unless the child needs distinct scope rules.

Deleting a parent

When a parent item is deleted, its children are detached: their parent, subcontext_type, and inherit_parent_scope fields are cleared so they become top-level items.

  • Children that used the parent's scope had no scope of their own, so once detached they would match every consumer. To avoid silently widening selection, those children are unpublished on parent deletion (a warning is logged). The parent and the scope are shared by all translations, so every published translation is unpublished, and a pending Publish on date is cleared. On moderated sites the moderation state is moved to an unpublished state (archived in the module's ai_context_editorial workflow) so content_moderation does not revert the change. Content moderation stores the state of one translation per save, so each other translation is saved in its own revision. Restore them after giving them their own scope if you still need them.
  • If the workflow of such a child has no unpublished default-revision state (for example, no Archived state), CCC cannot unpublish it: content moderation would publish it again. The child is detached but stays published, so it can match every consumer, and an error is logged. Add an unpublished default-revision state to the workflow and save the child again, or give the child a scope of its own.
  • Custom-scope children keep their own scope and remain published; they simply become independent top-level items.

If a child's parent reference becomes dangling (for example, a syncing import that references a parent that does not exist), the child is treated as inheriting but has no loadable parent. It is excluded from selection (never match-all) — including when it is listed in a consumer's Always include overrides — and a warning is logged until the parent is restored or the reference cleared.

How children get selected

Primary path: A parent is selected (by scope, global rules, always include, or exact-match). Subcontext resolution then loads and filters its children.

Subcontext resolution applies these checks on the selector path and when the Load tool returns a parent with its children:

  • Every child is checked on the translation that will be delivered. That translation must be published, and the current user must have view access to it. A child whose source is a draft is delivered only in languages that have a published translation of it. In every other language, including the source language, the child is not delivered, even to users who can view unpublished items.
  • A child with custom scope must also pass the hard filters (Roles, Languages, Site Sections, Entity Types, Taxonomy Terms, and Specific Entities) for the current request.
  • A child that uses the parent's scope is not hard-filtered again. This also applies when the parent was added through Always include or loaded by ID with the Load tool, although these paths do not hard-filter the parent.
  • On the selector path, a child that is also in the consumer's Always include list skips hard filters, like any Always include item, but still needs view access. The Load tool has no Always include list, so it hard-filters every child of a loaded parent that has its own scope. A child loaded by its own ID is treated like any item requested by ID.
  • Filtering runs before the conditional AI decision. A child that fails these checks is never sent to the AI provider.

Always include: A child ID in a consumer's Always include list is loaded directly, even when parent scope is active on the child. It is loaded like any other Always include item, so it skips hard filters but still needs view access. When the child's parent is also selected, the child is placed immediately after its parent in the rendered output; when the parent is not selected, the child appears at its own always-include position.

Custom scope only: A child with custom scope can also enter selection through the normal top-level paths (global cap, scope subscriptions, exact-match such as entity items, or broad-fill) without its parent being selected. This is intentional for items that define their own scope.

Subcontext items with parent scope active are designed to ride along with their parent; attach detail as subcontext rather than giving children independent scopes unless you mean to.

Children appear nested under their parent in consumer context settings.

Disabling subcontext hierarchy

When Enable subcontext hierarchy is turned off in context item settings:

  • Parent and subcontext type fields are hidden on item forms.
  • Subcontext resolution is skipped at runtime (children are not resolved) with parents).
  • Warning: Saving any context item clears its parent and subcontext_type values. This is not reversible from the UI. Children that used the parent's scope have no scope of their own, so they are also unpublished on that save (the same protection as parent deletion, including the moderation-state move on moderated sites) to keep them from matching every consumer; a warning is logged. Saving one translation unpublishes every published translation of the item. On moderated sites the other translations are then saved in their own revisions, in the same database transaction. When Content Moderation keeps the save as a pending draft, the published default revision is checked separately. If that revision also relies on its parent's scope, its published translations are archived in new revisions based on the draft, so the latest revision keeps the editor's text. A default revision with its own scope stays published and the draft stays pending. When the workflow has no unpublished default-revision state, such as Archived, the item stays published and an error is logged.
  • Syncing saves (configuration import, migrations, and update-hook backfills such as ai_context_update_10011()) never trigger the strip: only a normal editorial re-save detaches an item, so running database updates with the feature disabled does not purge stored hierarchy.

Re-enable the feature before editing items if you need to preserve hierarchy data.

Planned: tooling to analyze large context items and suggest logical subcontext splits for editorial review (see drupal.org issue #3574929). That complements manual subcontext hierarchy; it does not replace it.

Context item tokens

The token [ai_context:item:TOKEN_NAME] of a parent gives the parent and its required children. Conditional children are left out, because the token has no task for the AI decision. See Token name.

See also