Skip to content

Services

The AI Context module registers the following services in ai_context.services.yml.

Each service below is marked Status: Public or Status: Internal. Public services are safe to depend on; internal services are implementation details that may change without deprecation. Services without an explicit label are internal; see Support services. See API stability for the full policy and the public API surface.

Core services

ai_context.selection_factory

Status: Public

Interface: Drupal\ai_context\Service\AiContextSelectionFactoryInterface

Class: Drupal\ai_context\Service\AiContextSelectionFactory (@internal)

Type-hint the interface. Replace or decorate this service rather than extending the concrete class.

Builds AiContextSelection value objects from consumer config or raw parameters, runs those selections, and provides convenience methods for callers that just need rendered context.

Selection-building methods:

  • fromConsumer(string $consumerId, string $task, ...) -- builds a selection from a saved consumer config entry.
  • fromParameters(AiContextSelectionParams $params) -- builds a selection from a strongly-typed DTO (used by function call plugins and advanced consumers).
  • getResultFromSelection(AiContextSelection $selection) -- runs a built selection. This is the supported execute path.

Convenience methods (build + select in one call):

// One-liner: returns the rendered context string (empty if nothing matches).
public function getRenderedContext(
  array $scopes = [],
  ?int $maxTokens = NULL,
  ?EntityInterface $requestEntity = NULL,
  ?string $consumerId = NULL,
  ?string $selectionMode = NULL,
): string

// Full result with cache metadata, selected IDs, token usage.
public function getResult(
  array $scopes = [],
  ?int $maxTokens = NULL,
  ?EntityInterface $requestEntity = NULL,
  ?string $consumerId = NULL,
  ?string $selectionMode = NULL,
): AiContextSelectionResult

Usage examples:

/** @var \Drupal\ai_context\Service\AiContextSelectionFactoryInterface $factory */
$factory = \Drupal::service('ai_context.selection_factory');

// Get rendered context text (returns empty string if nothing matches).
$text = $factory->getRenderedContext(
  scopes: ['use_case' => ['working_with_text']],
  maxTokens: 2000,
  requestEntity: $node,
);

// Or get the full result object with cache metadata and selected item IDs.
$result = $factory->getResult(
  scopes: ['use_case' => ['working_with_text']],
  maxTokens: 2000,
  requestEntity: $node,
);
$text = $result->getRenderedText();
$cacheMetadata = $result->getCacheableMetadata();
$selectedIds = $result->getSelectedItemIds();

Parameters:

  • scopes: Scope subscriptions keyed by scope plugin ID. Pass an empty array to match all published context (subject to the token budget, the global item cap, and the selector's internal candidate bound).
  • maxTokens: Maximum tokens for rendered text. NULL defers to module settings.
  • requestEntity: The matching-environment entity for request-context scope matching, not the selection object. Named-argument callers must use requestEntity:; currentEntity: no longer works. Only its type and ID are passed on, so the default revision and translation are loaded again. Entity Types and Taxonomy Terms use it only when the current user can view that load.
  • consumerId: Canonical {type}:{instance} ID. Merges that consumer's saved configuration. Other strings are ignored. Pulls without a consumer log as none.
  • selectionMode: Optional trailing SELECTION_MODE_* override; NULL or an omitted argument defers to the site-wide default from ai_context.settings:selection_mode (Relevant unless changed).

Under the shipped relevant site default: global, always-included, exact-match, and situational-match items are considered without requiring a subscription; pass SELECTION_MODE_BROAD to additionally fill leftover budget with any published candidate that passes context filters.

Explicit scopes only affect the scope-scored group. Minimal and Relevant prefilter via the scope index; Broad scans the full published catalog for leftover fill.

On catalogs larger than 50 published items, the selector logs one watchdog warning per consumer per request when a selection scans the full catalog. That warning is expected for Broad; it does not mean selection failed. See Debugging.

Consumer config lookup:

  • fromConsumer(string $consumerId, string $task, ...) — builds a selection from a stored ai_context.consumers row plus plugin defaults.
  • isPushAllowed(string $consumerId): bool — whether automatic push is allowed (push_enabled, type enablement, and availability).
  • loadConsumerConfig(string $consumerId) — stored consumer config (AiContextConsumerStoredConfig) or NULL. Missing keys are not filled with defaults.
  • resolveConsumerConfig(string $consumerId) — effective config (AiContextConsumerResolvedConfig): stored config over plugin defaults, plus type enablement and availability.

See AiContextSelection and selection modes and AiContextSelectionResult below.

ai_context.scope_subscription_form

Status: Public

Interface: Drupal\ai_context\Service\AiContextScopeSubscriptionFormBuilderInterface

Class: Drupal\ai_context\Service\AiContextScopeSubscriptionFormBuilder (@internal)

Type-hint the interface. Replace or decorate this service rather than extending the concrete class.

Builds and processes scope subscription form widgets for consumers that need the same subscription UI as the consumer editor without depending on the internal scope plugin manager.

Methods:

  • hasSubscribableScopes(): bool — whether any enabled scope supports subscriptions.
  • getNonSubscribableScopeLabels(): string[] — human-readable labels for scopes that do not support subscriptions (for example Global).
  • buildWidgets(array $form, FormStateInterface $form_state, array $defaults = [], bool $for_subscription = TRUE): array — per-scope subscription widgets keyed by scope plugin ID. The parent form is not modified.
  • extractValues(array $submitted, array $previous = []): array — normalizes raw submitted values into nested scope values (scope_id => [value_ids]). Pass previously stored subscriptions as $previous so disabled, unavailable, and missing scopes are kept.
  • buildSummary(array $scope_subscriptions): array — summary render array for selected subscriptions.

Usage example (custom entity form with scope subscriptions):

/** @var \Drupal\ai_context\Service\AiContextScopeSubscriptionFormBuilderInterface $builder */
$builder = \Drupal::service('ai_context.scope_subscription_form');

if (!$builder->hasSubscribableScopes()) {
  return;
}

$form['my_module']['scope_subscriptions'] = [
  '#type' => 'container',
  '#tree' => TRUE,
];

foreach ($builder->buildWidgets($form, $form_state, $current_scopes) as $scope_id => $element) {
  $form['my_module']['scope_subscriptions'][$scope_id] = $element;
}

// In submit/entity builder:
$submitted = $form_state->getValue(['my_module', 'scope_subscriptions']) ?? [];
$scope_values = $builder->extractValues(
  is_array($submitted) ? $submitted : [],
  $current_scopes,
);

ai_context.selector

Status: Internal

Class: Drupal\ai_context\Service\AiContextSelector

Interface: Drupal\ai_context\Service\AiContextSelectorInterface

Orchestrates context selection: filtering, scope scoring, subcontext resolution, rendering, and dispatching stable selector pipeline events. It has zero knowledge of agents or consumer-specific configuration.

Items with inheritsParentScope() are excluded from the top-level published-item scan; they enter selection with their parent via subcontext resolution or through explicit always-include overrides. Subcontext items with custom scope remain full top-level candidates. See Parent scope.

Extension model: Contrib modules extend selection via documented selector pipeline events — not by decorating this service. Decorating or replacing ai_context.selector is unsupported; the selector and its internal pipeline may change without deprecation. See Supported extension model in Events.

Key method:

public function select(AiContextSelection $selection): AiContextSelectionResult

Drupal tokens in the rendered text are always neutralized, so every delivery path and the public selection API get the same text. See ai_context.token_neutralizer.

The AiContextSelectionResult contains the rendered text, selected item metadata, token usage, and CacheableMetadata. See AiContextSelectionResult for the full API. Pipeline event names and subscriber contracts are documented in Events.

ai_context.scope_index

Status: Internal

Class: Drupal\ai_context\Service\AiContextScopeIndexService

Maintains the denormalized ai_context_item_scope_index table — one row per (item_id, scope_id, value) triple mirroring each item's effective scope (via AiContextItem::getScopeItem()). This lets the selector prefilter candidates with SQL instead of loading every published item when scope subscriptions are present.

Key methods:

  • indexItem(AiContextItem $item) — rebuild index rows for one item (called on insert/update). For subcontext items with inheritsParentScope(), rows reflect the parent's scope values. When a parent is updated, those children are reindexed in the entity update hook.
  • deindexItem(int $item_id) — remove all rows for an item
  • getItemIdsByScopeValues(string $scopeId, array $values): int[] — items matching any of the given values for one scope
  • getItemIdsByScope(array $scope_subscriptions, array $candidate_ids = []): int[] — items with at least one matching value for any subscribed scope. Missing item values earn no subscription score. Callers add global and exact-match candidates separately
  • countPublishedGlobalItems(?AiContextItem $exclude_item = NULL): int — published items that store global on themselves (field query, not the index table, so inherited child rows are excluded)
  • hasPublishedGlobalItem(): bool — whether that count is greater than zero

The entity_item scope uses a separate DER field and is not indexed here.

ai_context.scope_cleanup

Status: Internal

Class: Drupal\ai_context\Service\AiContextScopeCleanupService

Removes stale scope values from context items and consumer subscriptions. Plugins that implement AiContextScopeStoredValueInterface decide which stored values are stale and whether a Drupal change should trigger a scrub.

When a removal would widen an item, the service unpublishes the item instead:

  • Rule. The item is unpublished when cleanup removes the last value of any stored-value scope other than Context Tags, or the last Specific Entities reference. Context Tags only rank items. Removing a tag, including the last one, leaves the item published. Items with Global stored on the item itself are never unpublished. A subcontext item whose inherit_parent_scope value is unset would resolve to its parent after it loses its last own value, so a Global parent does not keep it published. This also applies when that last value was a Context Tag: the child is unpublished when the parent it now resolves to is Global. The hard-filter rule also applies when that scope is disabled or unavailable. The scope plugin API has no flag for hard filters, so the rule is a private constant in the service, and custom stored-value scopes count as hard filters. There is no public cleanup policy API in 1.0.
  • Translations and moderation. Every published translation is unpublished with setUnpublishedWithModerationState(). On moderated sites each translation moves to an unpublished default-revision state. Archived is the state supplied by the module's workflow; custom workflows can use another suitable state. Content moderation stores the state of the saved translation only, so each other changed translation is saved on its own. All saves are one database transaction, so a failed save rolls the item back. If the workflow has no unpublished default-revision state, cleanup does not save. Other modules' save hooks do not run. The item keeps its stale value. That value is not shown on the edit form. It matches no current user, page, or content, so the item is not sent. Saving the item in the form removes the hidden value, and the published item then reaches more users, pages, or content than intended. An error is logged instead of a warning, and the status warning has one more sentence for these items. The item keeps its stale value, so a later scan in the same request finds it again. Each scope of the item is logged only once, so an item blocked for two scopes has two errors. The warning counts the item once.
  • Scheduling. The service clears publish_on, and publish_state when it exists, on every translation in the same revision, because Scheduler would otherwise publish the item later with the emptied scope. unpublish_on is kept.
  • Revision. The unpublish is saved as a new revision. The log message says that scope cleanup unpublished the item and which value it removed. The revision author is the current user, and the revision time is the request time. The save uses setSyncing(TRUE), so preSave() does not detach a child when subcontext is disabled. Cleanup sets the new revision before that flag. It also sets the changed time, because a syncing save would otherwise leave it unchanged. Content moderation still applies the moderation state. It does not change the default-revision flag during that save. The loaded item is already the default revision. On moderated multilingual sites each translation save is its own revision with the same log message, author, and time. A published item can also have a pending draft. Cleanup's revision becomes the latest. The draft is older and still stores the removed value. Reverting to that draft and saving the form can drop the value and widen the item, with no cleanup message. Save-time pruning (#3586393) will use this same rule.
  • Log and message. The service logs one warning per item it unpublishes or whose publish date it cancels, on the ai_context channel, with the item label and ID, the scope ID, and the removed values. Users with the "View site reports" permission can read these entries in Recent log messages. The current user also sees one warning. Unpublished items and cancelled publish dates are counted separately. The warning has one sentence for each count that is not zero, then the reason, for example: "1 context item was unpublished. 1 context item had its scheduled publishing cancelled. Scope cleanup removed the last value that kept them from reaching more users, pages, or content." Plural forms use the counts. One published item whose date is also cleared counts as unpublished. Cleanup can run several times in one request, so the service replaces its earlier message with the new totals. The counts and the message text are kept in ai_context.scope_cleanup_notice, so this also works across the container rebuild of a module uninstall. The message links to the context item list when the user can open it. The anonymous user sees no message: cron runs as Anonymous, and with automated cron the message would reach a visitor's session. Drush also runs as Anonymous. The log entries are written in both cases. When a save fails outside a database transaction, the message still counts the items cleaned before the failure. A content entity delete runs both cleanup passes inside one transaction. The warning waits until that transaction commits. If the delete rolls back, the counts from those passes are dropped and no warning is left for them.
  • Unpublished items. An item with no published translation and no publish_on value keeps its status. Cleanup removes the stale value but adds no revision metadata, log entry, or message. An item with a publish_on value gets a new revision with the log message "Scheduled publishing cancelled by scope cleanup: …", and it is logged. The warning counts it as a cancelled publish date.
  • Saves without a new revision. An item that cleanup does not unpublish, because the scope keeps a value or the item is already unpublished, is saved with setSyncing(TRUE). Otherwise content moderation would add a new revision that copies the previous log message, revision author, and revision time. A syncing save also keeps the changed time and skips the subcontext detach in AiContextItem::preSave().

Key methods:

  • removeScopeValues(string $scopeId, array $values) — strip values from item scope values, consumer subscriptions, and the scope index
  • scrubScope(string $scopeId) — ask one opted-in plugin which of its stored values are stale and remove them
  • scrubStaleScopeValues() — ask every opted-in plugin. Use Case is skipped because it does not implement the interface. Live settings-save cleanup uses this method.
  • scrubStaleScopeValuesForUpgrade() — conservative one-shot scrub used by post-update 0006. Skips disabled or unavailable scopes. Custom and settings-derived scopes, including Site Section, are left in place. Entity Types drops only values whose type or bundle is gone. Language, Roles, Tags, and Taxonomy use the live policy.
  • scrubScopesAfterEntityDelete(EntityInterface $entity) — scrub plugins that opt in for this delete
  • scrubScopesAfterBundleDelete(string $entityTypeId, string $bundle) — scrub plugins that opt in for this bundle delete
  • scrubScopeAfterSettingsChange(string $scopeId) — scrub one plugin after its settings config is saved
  • removeDeletedConsumerConfig(AiContextConsumerId $consumerId) — drop the stored ai_context.consumers row for a deleted instance and record it in ai_context.removed_consumer_rows
  • restoreRemovedConsumerRows() — put back the rows removed during this request, skipping rows already present. Called from hook_modules_uninstalled() so host entities deleted during an uninstall keep their overrides
  • removeEntityItemReference(string $entityTypeId, int|string $entityId) — clear DER target references when a referenced entity is deleted, and unpublish items that lose their last reference

Triggered automatically from hook_entity_delete(), hook_entity_bundle_delete(), hook_modules_uninstalled(), and AiContextScopeConfigSubscriber (see Event subscribers below). Subscription collection reads raw ai_context.consumers (no settings.php overrides) so removal writes the same storage it read. Custom scopes opt in through AiContextScopeStoredValueInterface; do not invent a second cleanup path.

ai_context.scope_resolver

Status: Internal

Class: Drupal\ai_context\Service\AiContextScopeResolver

Scores context items against scope subscriptions and applies hard context filters (e.g., language, site section). Replaces the former AiContextScopeMatcher.

ai_context.renderer

Status: Internal

Class: Drupal\ai_context\Service\AiContextRenderer

Renders selected context items into a token-limited text block for prompt injection. Truncation and assembled-output token checks use the AI module TextChunker and @ai.tokenizer, configured from the same resolved tokenizer model as ai_context.token_estimator (explicit provider_config.model, the site chat default when use_default is enabled, or gpt-4 when neither is available). Receives pre-translated entities from the selector. The renderer always neutralizes Drupal tokens in the assembled item text, and its budget checks use that text, so the rendered item text stays within the configured budget.

ai_context.token_neutralizer

Status: Internal

Class: Drupal\ai_context\Service\AiContextTokenNeutralizer

Puts a space on both sides of the colon of Drupal tokens, so Token::scan() no longer matches them. This covers every type that the token service knows (declared in hook_token_info()), and undeclared types that look like token types, such as [current_user:mail] from ECA. It also breaks root-level data paths such as [current_user.mail.value] from ECA. Times, JSON, URLs, and notes with a space after an undeclared type, such as [note: read this], are not changed. Other text that looks like a token, such as items[i:j], also gets the spaces. See Authoring trust for the exact rules and the limits. The renderer uses it on the assembled text, and the selector uses it on text that TEXT_RENDERED subscribers add and on the selected-item metadata. This covers every delivery path and the public selection API. The List tool, which does not use the renderer, uses it on its own output.

When ai_context.token_estimator reports that the tokenizer is not available, the renderer does not set the chunker model, because that would try the vocabulary download again. It trims content with mb_strcut($content, 0, $max_tokens * 4) and checks the budget with the estimator's approximate counts. If setting the chunker model throws, the renderer marks the tokenizer unavailable and uses the same trimming. If chunkText() throws during a render, the rest of that render uses the same trimming, and the estimator logs one encoding warning. The output stays inside the budget as measured by the approximate count, and still lists truncated item IDs, so the selector, the push subscribers, the agent tools, and the selection API keep returning context. For some languages (for example CJK text), the real token count can be higher than the budget.

While the tokenizer is not available, the render result has a max-age of AiContextTokenEstimator::UNAVAILABLE_CACHE_TTL (600 seconds). The selector merges it into AiContextSelectionResult, so a cached result does not keep the byte-trimmed text after the vocabulary loads. An encoding failure on one text does not limit the max-age, because a new render gives the same result.

Key methods (on the @internal AiContextRendererInterface; a decorator of this service must implement them):

  • estimateItemTokens(AiContextItem $item): int — the cost of the item's rendered block in its current translation; what preSave() stores in token_count
  • estimateBlockTokens(...) — the same figure from the raw parts, used by the backfill so stored counts and render() cannot drift

ai_context.token_estimator

Status: Internal

Class: Drupal\ai_context\Service\AiContextTokenEstimator

Estimates token counts via the AI module @ai.tokenizer service and classifies budget-relative weight tiers for context text. Used by the renderer for token budgeting, by the listing UI for token badges, and to persist token_count on context items at save time. The tokenizer is a shared service that other consumers re-point at their own model, so the configured model is re-applied before every count. The selector uses this after TEXT_RENDERED to recalculate AiContextSelectionResult::getTokensUsed() from the final rendered text.

The model name selects a tokenizer encoding; no provider is called. Resolution matches chat provider lookup: an explicit provider_config.model, else the site-wide AI chat default when use_default is enabled, else gpt-4. Models that tiktoken does not know use cl100k_base.

Vocabulary download and fallback

The AI module tokenizer (yethee/tiktoken) downloads the vocabulary file for the encoding on first use, with PHP fopen():

Encoding Models Vocabulary URL Cache file name
cl100k_base gpt-4 and models that tiktoken does not know https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken 9b5ad71b2ce5302211f9c61530b329a4922fc6a4
o200k_base gpt-4o models https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken fb374d419588a4632f3f557e76b4b70aebbca790

It caches the file in the Drupal temp directory ($settings['file_temp_path'], else the system temp directory). The file name is the SHA-1 of the vocabulary URL. The tokenizer checks the SHA-256 checksum of the cached file, and downloads the file again when the checksum does not match.

When the vocabulary cannot be loaded (no outbound HTTPS, allow_url_fopen = Off, a temp directory that is not writable, or a corrupt read when two requests download the file at the same time), the estimator does not throw:

  • estimate() returns (int) ceil(strlen($text) / 4). For ASCII text, this is characters / 4. For multibyte text, it is higher than characters / 4, but it is not an upper bound: for some languages (for example CJK text), it can be lower than the real token count.
  • The failure is remembered for the resolved model for 10 minutes, in the service and in cache.default (cache ID ai_context:tokenizer_unavailable:{model}). In that time, the estimator does not try the download again. A long-running process (a queue runner, or a long agent loop) checks again when the 10 minutes end. drush cr clears the cache entry at once. resetTokenizerModelConfiguration() clears only the memo in the service, because the cache entry is keyed by model.
  • One warning is logged to the ai_context channel in the request that fails to load the vocabulary: "Could not load the tokenizer vocabulary for model @model (@class: @message). AI Context uses an approximate token count until the vocabulary loads." Item content is never logged.
  • Item saves store the approximate count and queue one full recount (see ai_context.token_count_backfill_scheduler).

If the vocabulary loads but one text cannot be encoded (for example a PCRE error), estimate() returns the approximate count for that text only and logs one warning for each request, without the exception message. The tokenizer is not marked unavailable, because other texts still count correctly. No recount is queued, because a recount fails on the same text, so the stored count for that item stays approximate until its content changes.

Key methods:

  • estimate(string $text): int — token count, or the approximate count when the tokenizer fails; never throws for tokenizer errors
  • isTokenizerAvailable(): bool — whether the vocabulary for the configured model loaded. The first call in a request reads the memo and, when there is none, loads the vocabulary. The recount checks it, so that a missing vocabulary never replaces stored counts with approximate ones. Texts the tokenizer cannot encode still get approximate counts. AiContextItem::preSave() checks it to queue one recount after it stores an approximate count
  • markTokenizerUnavailable(\Throwable $exception): void — records a load failure that another tokenizer user found (the renderer's chunker)
  • reportEncodingFailure(\Throwable $exception): void — logs, once for each request, that one text could not be encoded
  • resetTokenizerModelConfiguration(): void — drops the model and availability remembered for the request after the model setting changes

Sites without outbound access can allow openaipublic.blob.core.windows.net, or copy the vocabulary file from the URL above into the temp directory with the cache file name above. Copy the file unchanged, and make it readable by the web server user; a changed file fails the checksum. The download needs allow_url_fopen = On, and it does not use the Drupal HTTP client proxy settings ($settings['http_client_config']). If outbound access needs a proxy, copy the file instead. TIKTOKEN_CACHE_DIR has no effect, because the AI module sets the cache directory. Sites whose temp directory is emptied on each deploy or restart can set $settings['file_temp_path'] to a persistent directory, so the download is not repeated.

When the resolved tokenizer model changes, AiContextSettingsConfigSubscriber hands the change to ai_context.token_count_backfill_scheduler. That includes ai_context.settings:provider_config and, when CCC is using the site chat default, a change to ai.settings default_providers.chat. Config saves act immediately; configuration imports record the change in state (durable across the batch requests a UI import spans) and act at ConfigEvents::IMPORT. See Recounting after a model change.

ai_context.token_count_backfill_scheduler

Status: Internal

Class: Drupal\ai_context\Service\AiContextTokenCountBackfillScheduler

Owns the chunked token_count recount shared by updates 10023 and 10032, the settings batch, and the cron queue worker, so all of them write counts identically.

How a recount runs depends on what the request can finish:

Context Mechanism
CLI (Drush config set/import, scripts) backfillAll(), synchronous
A request that processes a batch (settings form save) Batch, draining the queue
Any other web request (programmatic save, UI config import) Queue only, drained by cron

Non-CLI scheduling always enqueues first, because a request that never processes a batch would otherwise drop the recount silently. The batch consumes the same queue, so a form save recounts immediately and leaves cron nothing to repeat.

Chunks write only the token_count column of the exact revision each count was read from, keyed on ID, revision ID, and langcode. A concurrent editorial save creates a newer revision, so the update matches no rows and the editor's own preSave() count stands — the recount can never overwrite content changes.

When the tokenizer cannot load its vocabulary, a recount writes nothing, so approximate counts never replace stored ones. backfillChunk() checks isTokenizerAvailable() before it recounts a chunk and again before it writes, and throws AiContextTokenizerUnavailableException (@internal) when the tokenizer is not available. Each caller defers to cron instead of failing:

Caller When the tokenizer is not available
Cron queue worker Throws SuspendQueueException. Cron releases the item and tries the queue again on the next run
Settings form batch Releases the queue item, finishes, and shows a warning that cron recalculates the counts
CLI backfillAll() (Drush config set/import) Logs a warning, queues a full recount for cron, and returns
Update 10023 Logs a warning, queues a full recount for cron, and finishes

An item save that stored an approximate count calls queueDeferredRecount(). The state flag ai_context.token_count_deferred_recount keeps one waiting full recount in the queue. backfillChunk() clears the flag when a recount starts at the first item. A recount that is already running can be past the saved item, so a save after that point queues a new full recount.

Key methods:

  • scheduleIfTokenizerModelChanged(mixed $old, mixed $new): void — no-op when the resolved model is unchanged or no items exist
  • schedule(): void — queue or run a recount after the resolved model changed (including a site chat default change)
  • backfillChunk(int $last_id): array{last_id: int, processed: int} — recount one chunk; a processed of 0 means the catalog is exhausted
  • backfillAll(): int — recount everything, blocking; defers to cron when the tokenizer is not available
  • processQueuedChunk(): array / drainQueue(): int — consume queued cursors; processQueuedChunk() returns deferred: TRUE when it released the item for cron
  • queueDeferredRecount(): void — queue one full recount unless one waits that has not started
  • deferRecount(): void — log a warning and call queueDeferredRecount()
  • writeTokenCounts(int $id, int $revision_id, array $counts): void — write one revision's counts keyed by langcode; postSave() uses it so a new item is counted once it has an ID

ai_context.subscription_budget

Status: Internal

Class: Drupal\ai_context\Service\AiContextSubscriptionBudgetCalculator

Calculates subscribed context token totals for the consumer settings form budget summary. Returns AiContextSubscriptionBudgetSummary, an internal value object consumed by AiContextConsumerForm.

Totals sum each item's stored token_count, which since update 10032 is the cost of the item's rendered block: the id, label and purpose header plus the indented guidance. The sum is not the runtime figure. The blank lines between blocks can add a token or so, truncation at render time can make the rendered text smaller than the sum, and the context prefix and delimiters that wrap the whole block are counted in neither. Compare with AiContextSelectionResult::getTokensUsed(), the rendered block after selection.

Candidate narrowing mirrors AiContextSelector so the summary counts what runtime selection would actually inject:

  • Items are counted in the detected content language, matching the translation the selector injects.
  • Always-include items bypass scope handling; never-include items are dropped; inaccessible items are dropped; inheriting children are only counted through their parent.
  • Hard context filters (filterByRequestContext()) apply to everything else, on every selection mode — not only MINIMAL without subscriptions.
  • max_global_items caps globals (higher Priority first, then shorter content, then highest ID). Other groups use the selector's internal per-group candidate bound. Groups merge in this order: global, always-included, exact-match, scope-scored, situational-match (Relevant and Broad), and broad-fill.
  • Relevant (the shipped site-wide default when selection_mode is omitted) includes situational-match items from scopes declaring supportsSituationalMatch() — Languages, Site Sections, Entity Types, and Taxonomy Terms by default. Minimal does not.
  • Subscription scoring runs before situational-match so a Minimal match cannot be dropped when the situational-match group hits its internal cap. Situational-match classification remains as a fallback for candidates displaced from the final scope-scored group. Overflow situational-match items still feed broad-fill.
  • Final scope-scored duplicates are removed before the broad-fill group is pruned, so they cannot consume its candidate allowance.
  • Relevant and Broad stream published IDs and load entities in 200-item chunks. Each group is pruned and memory-cache entries introduced by the scan are released after every chunk. Broad-fill still runs when subscriptions exist.

Results are cached per consumer configuration, module settings, scope-plugin configuration, effective permissions, and request context (scope context values, target entity, content language, and request path) for one hour. Cache tags include ai_context_item_list, config:ai_context.settings, config:ai_context.consumers, and each config:ai_context.scope_settings.* object, plus metadata supplied by the user.permissions cache context. The consumer settings lazy builder varies by target entity, detected content language, permissions, and request path (url.path and ai_context.request_path).

Key methods:

  • summarize(array $consumer_config): AiContextSubscriptionBudgetSummary — within-budget, conditional-range, or over-budget totals for one consumer config entry

ai_context.subcontext_resolver

Status: Internal

Class: Drupal\ai_context\Service\AiContextSubcontextResolver

Resolves child (subcontext) items for selected parent items. When conditional AI decisions are enabled, filters conditional children via the configured provider/model. The nested decision asks for a fenced JSON array of child IDs so the reply decodes on AI core 1.5.x; without a provider or on failure, conditional children for that parent are skipped. When conditional AI decisions are disabled, conditional children are excluded from normal subcontext resolution. Skipped entirely when subcontext_enabled is FALSE in module settings. This service assumes saved parent-child relationships already satisfy the entity integrity rules.

Before any conditional decision, the resolver drops a child when its delivered translation is not published or the current account cannot view it. A child with its own scope must also pass the hard filters, unless it is in the $always_include list. A child that uses the parent's scope is not hard-filtered again. The access results are added to the cacheability that the caller passes to resolve().

See Subcontext for when to use parent/child items.

ai_context.request_info_resolver

Status: Internal

Class: Drupal\ai_context\Service\AiContextRequestInfoResolver

Resolves request information used for matching: the entity (when there is one) and the effective page path. Used by Entity Type, Specific Entity, and Site Section scopes. Site builders should start with Page and entity context.

Entity sources, in order:

  1. Request attributes ai_context_entity_type and ai_context_entity_id (set by setEntity(), applyRequestInfo(), or a caller)
  2. Route parameters (any loaded content entity; config entities such as an Editor on an API-proxy route are ignored)
  3. Request body values (entity_type / entity_id in POST or JSON; content entity types only, so a body naming an Editor or another config entity is ignored)

Entity type and bundle (getEntityType(), used by Entity Types): the loaded entity's type:bundle when one of the sources above loads and the current user can view it (loadContentEntity()), otherwise the bundle hint in request attribute ai_context_entity_bundle (set by setEntityBundle() or applyRequestInfo() with entity_type plus bundle). The hint covers unsaved entities such as a node add form. Unknown types, config entity types, and unknown bundles are ignored. An entity the user cannot view gives the same result as an ID that does not exist. The loaded entity and the getEntityType() result are cached until the entity, the hint, the current request, or the account changes. An account switch in a queue worker or a new route in a nested request therefore checks access again. getContentEntityAccessResult() returns the access result behind loadContentEntity(), allowed or not, or NULL when no entity loads. The selector always adds its cacheability to the selection result, also when Entity Types and Taxonomy Terms are disabled.

Effective page path sources, in order:

  1. Request attribute ai_context_path (set by setPath(), applyRequestInfo(), or a caller)
  2. Request body values (path in POST or JSON)
  3. A same-site Referer path, only on XMLHttpRequest or JSON requests (the base path is removed)
  4. $request->getPathInfo()

applyRequestInfo() copies untrusted path and entity values onto the request. The usual source is a BuildSystemPromptEvent payload (getTokens() means those keys, not LLM token counts). A route content entity wins over an array content entity. A route entity saved for an earlier request does not. Config entity objects in the payload are ignored. A path-like path or route value is stored and preferred over getPathInfo(). Route names are ignored.

Values applied through applyRequestInfo() (agent path) and applyRequestHints() (generic chat path, from entity_context metadata) are scoped to one AI call. One HTTP request can run several AI calls, so the next routed call starts by dropping whatever the previous call applied (resetRequestInfo()); the route entity and getPathInfo() win again once a caller stops supplying a value. Only keys this service actually wrote are dropped: a value another module set for the whole request through setPath(), setEntity() or setEntityBundle() survives, and setPath() and setEntityBundle() return FALSE for a rejected value so it is never recorded as applied.

Entity and path resolution deliberately invert each other. A route entity wins over a caller-supplied entity, because the route is usually the page being viewed. A caller-supplied path wins over getPathInfo(), because on API-proxy routes getPathInfo() is the proxy endpoint, not the viewed page. Making the two rules identical would either reopen this issue (path never overrides) or let a payload replace the entity you are actually on (entity always overrides).

Callers that run on API-proxy routes (for example a chatbot endpoint) should supply the viewed page path. Site Sections matches that hint instead of the proxy path. Without a hint, an asynchronous browser call falls back to its same-site Referer. A supplied path is an untrusted context hint used for string matching only. It is not used to load files, follow redirects, or grant access. Absolute URLs are reduced to their path, with the site base path removed, so a hint such as window.location.href on a subdirectory install compares with getPathInfo().

A supplied path that is longer than 2,048 characters (AiContextRequestInfoResolver::MAX_PATH_LENGTH) is ignored. The query string and the fragment are removed before the check. The limit counts characters, not bytes. setPath() returns FALSE for a path that is too long. getPath() then uses the next source in the list above. The request path (getPathInfo()) has no limit.

/** @var \Drupal\ai_context\Service\AiContextRequestInfoResolver $resolver */
$resolver = \Drupal::service('ai_context.request_info_resolver');

$request = \Drupal::request();
$request->attributes->set(
  AiContextRequestInfoResolver::PATH,
  '/node/1',
);
// Or:
$resolver->setPath('/node/1');

ai_context.usage_tracker

Status: Internal

Class: Drupal\ai_context\Service\AiContextUsageTracker

Records usage data when context items are selected. Tracks which items were used, by which consumer, on which route, and which entities were involved. recordUsage() requires a canonical consumer ID. The runner ID and entity item are optional so non-agent consumers can record usage.

Each usage record keeps only the last 20 paths (AiContextUsage::MAX_ROUTES), oldest first. A path that is longer than 255 characters (AiContextUsage::MAX_ROUTE_LENGTH) is cut and ends with "…". AiContextUsage::setRoutes() applies these limits, and addRoute() uses it, so a path that is used again moves to the end. When attachEntity() merges an older record into the record of the run, the older paths go first, so the limit removes them first. A record that was saved before these limits is cut the next time a path is added to it.

Performance notes:

  • recordUsage() batches the existing-record lookup with a single entity query using context_item_id IN (...).
  • attachEntity() batches duplicate checks for entity-specific records.
  • recordToolUsed() buffers tool IDs in memory; call flushToolsUsed() once per agent run (handled automatically by AiContextAgentFinishedSubscriber on AgentFinishedExecutionEvent).
  • Lookup indexes on runner_id, changed, (entity_item_type, entity_item_id), and (context_item_id, consumer_id) are managed by _ai_context_ensure_usage_indexes() in ai_context.install.

Tracking is controlled by the usage_tracking_enabled setting (disabled by default). When disabled, all tracker methods return immediately without database access.

ai_context.children

Status: Internal

Class: Drupal\ai_context\Service\AiContextChildrenService

Provides parent/child hierarchy queries for context items and supports cleanup of child references when a parent item is deleted. Revision view pages use loadChildrenForParentAtTime() so Nav panel siblings match the child list at the viewed revision timestamp.

ai_context.item_view_builder

Status: Internal

Class: Drupal\ai_context\Service\AiContextItemViewBuilder

Builds template variables for the ai_context_item theme hook. AiContextThemeHooks::preprocessAiContextItem() delegates to preprocess() on this service. Only the full view mode (canonical and revision routes) receives sidebar and header variables; other view modes get content field render arrays only.

Key methods:

  • preprocess(array &$variables) -- for full view mode, populates title, parent link, subcontext row, status badge, scope rows, author, nav items, and content field render arrays; bubbles cache metadata onto $variables (the top-level preprocess array ThemeManager reads). Non-full view modes only expose content.
  • buildStatus(AiContextItem $entity) -- published/moderation status label and CSS modifier, including "Published (Draft available)" when Content Moderation is enabled.
  • buildScopeRows(AiContextItem $entity, ?CacheableMetadata $cacheability = NULL) -- sidebar scope rows. Global items show only the global row (Enabled). When at least one non-global scope has values, every enabled scope row is included (global first as Disabled, empty scopes show None); otherwise returns an empty array. When a collector is passed, Specific Entities, Context Tags, and Taxonomy Terms labels use getSelectedValueLabelsWithCacheability() so access results and term cache tags bubble.
  • buildScopeSection(AiContextItem $entity, ?CacheableMetadata $cacheability = NULL) -- empty-state SCOPE heading and message when global is disabled and no non-global scopes are in use. Full-view preprocess computes rows and section in one pass so labels are not formatted three times. The builders themselves stay independent (no memo) for kernel tests. View-specific label formatting (custom site section paths, collapsed entity type labels) is applied in buildScopeRows().
  • addScopeViewCacheMetadata(CacheableMetadata $cacheability, AiContextItem $entity) -- adds each scope plugin's config tag (including disabled plugins, since enabled is stored in ai_context.scope_settings.*). Also adds the languages:language_interface context so translated plugin labels, "None", and language names vary by UI language. Tag term tags and Specific Entities access cacheability are collected while building scope rows, not reconstructed here.

ai_context.item_validator

Status: Internal

Class: Drupal\ai_context\Service\AiContextItemValidator

Validates persistence-level invariants for context items. For subcontexts, it prevents self-parenting, nested subcontexts, and converting an item with children into a subcontext. It also requires subcontext_type when a parent is selected. The published-global limit uses AiContextScopeIndexService::countPublishedGlobalItems().

ai_context.scheduler_defaults

Status: Internal

Class: Drupal\ai_context\Service\AiContextSchedulerDefaults

Applies default moderation states when Scheduler publish/unpublish dates are set on context items without an explicit publish_state or unpublish_state. Used during entity save so editors only need to set schedule dates when Content Moderation and Scheduler are enabled.

Key method:

  • applyScheduledModerationStates(ContentEntityInterface $entity) — sets published when publish_on is set and unpublished when unpublish_on is set, if the corresponding state field is empty.

Selection and result value objects

AiContextSelectionParams

Status: Public

Class: Drupal\ai_context\Model\AiContextSelectionParams

Immutable DTO passed to AiContextSelectionFactoryInterface::fromParameters(). Centralizes validation and normalization of raw selection parameters before an AiContextSelection is built. Use AiContextSelectionParams::fromArray() when constructing from plugin context, form values, or other untyped input. consumer_id merges canonical {type}:{instance} config. Non-canonical or non-string consumer_id and entity_type values are dropped. Unrecognized string selection_mode values are dropped to NULL and logged at debug so the factory inherits the consumer mode or the site-wide default. Non-string selection_mode values are dropped without logging. Pulls without a consumer log as none.

AiContextConsumerStoredConfig and AiContextConsumerResolvedConfig

Status: Public

loadConsumerConfig() returns AiContextConsumerStoredConfig or NULL. Omitted overrides stay NULL or empty; they are not filled with defaults. isPushEnabled() on stored config is TRUE, FALSE, or NULL when the config inherits the type default. A null stored flag is the same as omitted.

resolveConsumerConfig() returns AiContextConsumerResolvedConfig. That object is stored config over plugin defaults, plus isTypeEnabled() and isTypeAvailable(). isPushEnabled() on the resolved object is always a bool. isPushAllowed() ANDs the push gates with that flag. getSettings() is the type-specific instance bag: stored keys replace getInstanceDefaults()['settings']; extra stored keys are kept. Stored getSettings() is the saved map or empty; it is not filled with defaults. Agent isLoopAware() reads settings.loop_aware from the resolved bag. Limits that are still NULL inherit the site default when a selection is built.

Exported ai_context.consumers rows store always_include and never_include as context item UUIDs. The stored and resolved config objects expose those values as-is. The selection factory resolves them to local entity IDs when building an AiContextSelection. Legacy numeric IDs are still accepted at runtime. Scope subscriptions in the same object are still raw scope value IDs. Context Tags and Taxonomy Terms subscriptions store term UUIDs and are portable with the terms. See Consumer configuration — Export and import.

See AiContextSelection for the fields carried into the resulting selection.

AiContextSelection and selection modes

Status: Public

Class: Drupal\ai_context\Model\AiContextSelection

Immutable value object built by AiContextSelectionFactoryInterface::fromConsumer() or fromParameters(). Callers should obtain results through ai_context.selection_factory (getResult(), getRenderedContext(), or fromParameters() / fromConsumer() then getResultFromSelection()), not by injecting ai_context.selector directly.

Constructor fields:

Field Description
task Task description or user prompt (used for conditional subcontext)
scopeSubscriptions Scope values keyed by scope plugin ID
alwaysInclude / neverInclude Local item IDs to force in or out after the factory resolves stored UUIDs (legacy numeric IDs still work)
consumerId Canonical consumer ID after merge, or NULL
entityType / entityId Optional target for entity/bundle matching
maxGlobalItems / maxTokens Per-request limits; NULL falls back to module settings
selectionMode minimal, relevant, or broad

Selection modes (constant SELECTION_MODE_* on the class) are a nested ladder: each mode is a strict superset of the one before it, and hard filters apply in every mode.

  • minimal: only global items, exact-match (Specific Entities matches), always/never overrides, and strict scope subscription matches are considered. An item with no values for a subscribed scope no longer earns automatic credit for that scope.
  • relevant (default for fromConsumer(), fromParameters(), getResult(), and getRenderedContext()): Minimal, plus items that scopes declaring supportsSituationalMatch() (Languages, Site Sections, Entity Types, and Taxonomy Terms by default) positively match against the request context (matchesRequestContext() returns TRUE), even without a subscription to that scope.
  • broad: Relevant, plus any remaining published candidate that passes hard context filters, ordered by Priority, appended after the scope-scored bucket to fill leftover token budget. It supplements, never replaces, the scope-scored bucket.

There is no runtime alias for the removed match_all mode; update 10028 rewrites match_all to broad for rows it migrates out of the legacy ai_context.agents config (any other unrecognized legacy mode is dropped with a logged notice, so the row inherits the site default). fromArray() drops an unrecognized mode to NULL so the factory inherits the same way. Constructing AiContextSelectionParams with a non-NULL invalid string and passing it to fromParameters(), getResult(), or getRenderedContext() still throws \InvalidArgumentException. Values read back from stored consumer config are handled more defensively: an unrecognized stored value is logged and replaced with the site default from ai_context.settings. That fallback is Relevant only when the site default is empty or also invalid, so a single corrupted consumer entry cannot break every selection.

Function call plugins expose selection_mode explicitly on get_relevant_ai_context_items. See Function calls for the stable plugin IDs (ai_context:list_ai_context_items, ai_context:load_ai_context_items, ai_context:get_relevant_ai_context_items) and agent tool workflow. ai_context:load_ai_context_item_by_id is a deprecated alias of ai_context:load_ai_context_items and is removed in 2.0.0.

AiContextSelectionResult

Status: Public

Class: Drupal\ai_context\Model\AiContextSelectionResult

Immutable result from context selection via ai_context.selection_factory. Implements CacheableDependencyInterface.

Methods:

Method Returns
getRenderedText(): string Token-limited context block for prompt injection. Drupal tokens are neutralized
getSelectedItemIds(): string[] IDs of selected items
getSelectedItems(bool $fullData = FALSE): array Item metadata keyed by ID. Default is label and purpose. $fullData is the selector full payload (see below).
getTokensUsed(): int Approximate tokens consumed by the final rendered text (recalculated after selector pipeline events)
getMaxTokens(): int Max token cap applied during rendering
getSelectionMode(): string Resolved ladder rung that ran (minimal, relevant, or broad). Never NULL.
getTruncatedItemIds(): string[] IDs of items omitted or trimmed because the token budget was insufficient
getCacheableMetadata(): CacheableMetadata Clone of the cache metadata. Mutating it does not change the result.
getCacheTags() / getCacheContexts() / getCacheMaxAge() CacheableDependencyInterface delegates
getOmittedItemIds(): string[] IDs of selected items that produced no block in the rendered text, so they never reached the model
getDeliveredItemIds(): string[] getSelectedItemIds() without getOmittedItemIds(). A shortened item counts as delivered

When $fullData is TRUE, each item uses these keys. Adding a key later is not a break. Removing or renaming a key is a break.

Key Type Notes
label string Item label
purpose string Item purpose
is_global bool Effective global flag
parent_id int|null NULL when subcontext is disabled or there is no parent
subcontext_type string|null NULL when subcontext is disabled
scope array Effective scope values keyed by plugin ID. Context Tags is the tag scope; tag UUIDs live under scope['tag']. There is no separate tag-ID key
has_entity_items bool Whether the item references entities
content_snippet string First 200 characters of item content

Example:

$result = \Drupal::service('ai_context.selection_factory')->getResult(
  scopes: ['language' => ['en']],
  maxTokens: 20000,
);

$text = $result->getRenderedText();
$ids = $result->getSelectedItemIds();
$mode = $result->getSelectionMode();
$metadata = $result->getCacheableMetadata();

Plugin managers

plugin.manager.ai_context_scope

Status: Internal

Class: Drupal\ai_context\AiContextScopeManager

Plugin manager for scope plugins. Handles discovery, instantiation, and ordering of AiContextScope plugins. getScopePlugins() returns all plugins in ascending display_weight order, with plugin ID used to break ties. Core and custom plugins are interleaved according to their declared display_weight. The scoring_weight attribute is separate and controls subscription scoring influence independently of display order; values below 1 are treated as 1 during scoring.

Support services

Status: Internal — All services in this section and the sections below (event subscribers, route subscribers, access checks, and other support services) are internal. They are not labeled individually; see API stability.

ai_context.markdown_renderer

Class: Drupal\ai_context\Markdown\MarkdownRenderer

Converts GitHub Flavored Markdown content to HTML for display (including tables).

ai_context.provider_request_context_factory

Class: Drupal\ai_context\Service\AiContextProviderRequestContextFactory

Builds an immutable AiContextProviderRequestContext from a PreGenerateResponseEvent. Copies tags, conversation text, and structured metadata only. Live chat and file objects are not retained. Builder in this module is reserved for UI list/view/form builders. The snapshot and its nested message/file types are public; this factory service is @internal.

logger.channel.ai_context

Standard Drupal logger channel for ai_context log messages.

Event subscribers (registered as services)

ai_context.build_system_prompt_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextBuildSystemPromptSubscriber

Listens for BuildSystemPromptEvent and AgentStartedExecutionEvent. See Events.

ai_context.pre_generate_response_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextPreGenerateResponseSubscriber

Listens for PreGenerateResponseEvent at priority -100. See Events.

ai_context.agent_tool_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextAgentToolSubscriber

Listens for AgentToolPreExecuteEvent and AgentToolFinishedExecutionEvent. A non-empty non-canonical consumer_id is logged at debug before it is replaced with agent:{running agent}. See Events.

ai_context.scope_config_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextScopeConfigSubscriber

When any ai_context.scope_settings.{plugin_id} config is saved, asks that plugin whether to scrub stored values. Skips the scrub while config is being imported so plugins do not compare stored values to a half-imported environment. Bundle-delete hooks still run during import. See ai_context.scope_cleanup.

ai_context.settings_config_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextSettingsConfigSubscriber

When main_menu_enabled changes, or main_menu_title changes while the item is on, marks the router for a deferred rebuild. Core also rebuilds menu links then, updating the optional derived link after a form save, Drush change or configuration import. The general settings form runs that rebuild before it redirects, so the next page shows the change. The subscriber continues to schedule token count backfills when the tokenizer model changes. See Main menu link deriver.

Route subscribers

ai_context.route_subscriber

Class: Drupal\ai_context\Routing\AiContextRouteSubscriber

Alters routes for the module.

ai_context.scope_route_subscriber

Class: Drupal\ai_context\Routing\AiContextScopeRouteSubscriber

Dynamically generates routes for per-scope settings forms based on discovered scope plugins.

Access checks

ai_context.access_check.overview_page

Class: Drupal\ai_context\Access\AiContextOverviewAccessCheck

Controls access to the overview page based on the show_overview_page setting.

ai_context.access_check.usage_page

Class: Drupal\ai_context\Access\AiContextUsageAccessCheck

Controls access to the usage tracking page based on whether tracking is enabled.

Other services

ai_context.uninstall_validator

Class: Drupal\ai_context\AiContextUninstallValidator

Runs during module uninstall validation with higher priority than core's content validator. For an ai_context uninstall, it installs missing content entity schemas before core queries entity tables. This prevents fatal errors on sites where entity tables were never created (for example config-sync installs without entity updates).

For a Dynamic Entity Reference uninstall, it blocks removal while any context item has Specific Entities values on its default revision or a pending draft, including a pending translation. The reason identifies the affected items. If the values cannot be checked, it blocks the uninstall and logs the error. Historical revisions alone do not block the uninstall; their references are captured before field removal and written to revision logs only after the uninstall succeeds. See ai_context.dynamic_entity_reference_setup below.

The AI Context Tags vocabulary (ai_context_tags) is not checked here: its config declares an enforced dependency on ai_context, so Drupal will remove the vocabulary and any terms automatically on uninstall. For older sites that installed ai_context before this dependency was added, update hook ai_context_update_10012() backfills the enforced dependency on active config.

ai_context.removed_consumer_rows

Status: Internal

Class: Drupal\ai_context\Service\AiContextRemovedConsumerRows

Holds the ai_context.consumers rows that ai_context.scope_cleanup removed during this request, so hook_modules_uninstalled() can restore the ones removed during a module uninstall. Tagged persist so the rows survive the container rebuilds during an uninstall. It has no dependencies on purpose: a persisted instance would otherwise keep the old container's services. Recording the same consumer ID again keeps the first row, matching how a duplicated ID resolves everywhere else.

ai_context.scope_cleanup_notice

Status: Internal

Class: Drupal\ai_context\Service\AiContextScopeCleanupNotice

Holds how many items ai_context.scope_cleanup unpublished during this request, how many had scheduled publishing cancelled, the published items that it could not unpublish with the scopes it could not empty, and the warning text it last added to the messenger. During a module uninstall, core deletes bundles and config entities before it rebuilds the container, and it invokes hook_modules_uninstalled() after the rebuild, so cleanup can run in two instances of the cleanup service. Tagged persist so the user sees one warning with the totals. It has no dependencies, for the same reason as ai_context.removed_consumer_rows.

Drupal\ai_context\Hook\DiffHooks

Class: Drupal\ai_context\Hook\DiffHooks

Autowired service for Diff module integration hooks.

Drupal\ai_context\Hook\DynamicEntityReferenceHooks

Class: Drupal\ai_context\Hook\DynamicEntityReferenceHooks

Autowired service for Dynamic Entity Reference module integration hooks.

ai_context.dynamic_entity_reference_setup

Class: Drupal\ai_context\Service\AiContextDynamicEntityReferenceSetup

Installs the Specific Entities field storage when Dynamic Entity Reference is enabled on an existing site. During uninstall, counts current and pending values for the validator, captures historical references before field removal, and annotates revision logs after success. A failed post-uninstall write leaves confirmed notes in State for cron to retry.