<!-- markdownlint-disable MD024 -->

# HK: Hooks and developer docs

Track HK (owner decision, 2026-11-14). This document is HK-1: every extension point in the code today, which ones are public, the risky ones, the names to clean up, the few new hooks, what kimaai.com has, the page format and its check, the tests, and the item plan. The owner delegated the recommendations (2026-11-14); the track goes on with them. Two later owner decisions (2026-11-16) shape the plan: the HK items run one after another, not in parallel, and the kimaai.com side (the sync of the pages into BetterDocs, the index per area, the redirects) is built in this track too, in the website repository, after the pages exist.

## Decisions taken in this research (owner delegated, my recommendation, 2026-11-16)

- **72 public, 46 internal.** Of the 118 extension points (116 PHP hooks, 2 JS hooks), 72 get a page and a test; 46 carry `@internal` and get neither. Public means a developer outside KimaAI has a concrete use for it, it fires in production and it passes no internal class. Everything else is internal: test seams, wiring between KimaAI's own classes, the pre-WD theme, dormant integrations and the admin assistant's tool and renderable contract.
- **The licence filters go.** `kimaai_is_premium` and `kimaai_can_use_premium_code` stop being filters. The e2e suite gets premium through a test-site check that a shipped plugin cannot pass.
- **Six renames or deprecations, one removal, one direct rename.** `kimaai_chatbot_theme` and `kimaai_stream_tool_call` are deprecated in favour of `kimaai_chatbot_theme_vars` and `kimaai_chatbot_tool_call`. The four `kimaai_assistant_*` filters become `kimaai_chat_*`, with deprecated aliases. `kimaai_chatbot_allowed`, deprecated since 1.3.0, is removed. `kimaai_pdf_max_bytes` is unreleased and becomes `kimaai_embedding_pdf_max_bytes` without an alias.
- **Two new extension points.** A `kimaai_lead_validate` filter and a `kimaai:chatbot` browser event. Four existing hooks change instead of new ones being added: two fire on the streaming path too, one gets the ticket, one gets the field key.
- **Renderables are not an extension API yet.** The widget renders only the types built into it (`src/chatbot/renderables/defaultRegistry.js`), so the renderables guide the roadmap lists is dropped from HK. A registration API for the widget goes to "Later".
- **The roadmap's premise about the three old pages does not hold.** `kimaai_chatbot_after_response`, `kimaai_chatbot_error` and `kimaai_chatbot_response_payload` still exist (`app/ChatBot/ChatbotNormalRequestRunner.php:57-83`). They fire only when an answer does not stream, and streaming is on by default (`app/Admin/config/chatbot.php:1282`, `'default' => true`). They stay public; the first two are fixed to fire on the streaming path, and the third's page says when it runs. kimaai.com has 11 hook pages, not six.
- **`since` for new hooks is `next`** until the release that ships them, as FS does for features. The release-pr skill writes the version into the docblock and the page in the same commit.

## How the inventory was made

Commands run on `track/HK-hooks` at `18920d99` (2026-11-16). The PHP scripts are scratch tools of this research; HK-3 turns the first into `scripts/hooks-inventory.php`.

| What                            | Command                                                                                                                                                                                   | Result                                                                                                                                                                                                                                                   |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PHP hook call sites             | A PHP `token_get_all()` walk over every `.php` file outside `vendor`, `node_modules`, `tests`, `build` and `app/Generated`, matching the six hook functions and splitting their arguments | 134 call sites: 108 `apply_filters`, 25 `do_action`, 1 `apply_filters_deprecated`; no `apply_filters_ref_array`, `do_action_ref_array` or `do_action_deprecated`                                                                                         |
| Other plugins' hooks among them | Same, names without `kimaai`                                                                                                                                                              | 15: `the_content` (5), WPML (8), `gform_form_theme_slug` (2)                                                                                                                                                                                             |
| KimaAI call sites               | Same, names with `kimaai` or the dynamic prefix                                                                                                                                           | 119 (94 `apply_filters`, 1 `apply_filters_deprecated`, 24 `do_action`) in 56 files, 41 of them in `premium/`                                                                                                                                             |
| Distinct PHP hooks              | Unique literal names, plus the names the two dynamic call sites build                                                                                                                     | 112 literal + 4 dynamic = 116: 92 filters, 24 actions                                                                                                                                                                                                    |
| Dynamic names                   | Call sites whose first argument is not one string                                                                                                                                         | 2, both in `app/ChatBot/Tools/ChatbotToolRegistry.php` (lines 53 and 68): `$hook_prefix . '_allowed_tools'` and `'_tools_registry'`, with the prefixes `kimaai_chatbot` (default) and `kimaai_admin_assistant` (`AdminAssistantRequestPreparer.php:148`) |
| JS hooks                        | `grep -rnE "applyFilters\|doAction\|addFilter\|addAction" src`                                                                                                                            | 2: `kimaai.admin.fieldComponents` (filter) and `kimaai_trigger_button_click` (action), both in the admin; the chatbot widget has none                                                                                                                    |
| Docblocks                       | The comment block directly above each of the 119 call sites                                                                                                                               | 61 have no comment at all; 41 have `@param` tags                                                                                                                                                                                                         |
| Shipped in 1.5.13               | `git grep -w <name> origin/master` (1.5.13, `d56cab2b`)                                                                                                                                   | 103 of the 116 are released; 13 are not                                                                                                                                                                                                                  |
| First release with the name     | `git grep -F <name> <tag> -- '*.php' ':!tests' ':!vendor'` over the 54 tags in version order                                                                                              | The "First tag" column below; it is the first tag whose PHP code contains the name, which can be a listener rather than the call                                                                                                                         |
| Hooks a test file names         | `grep -rlw <name>` in `tests/unit`, `tests/integration`, `tests/e2e`, `tests/cli`, `tests/js`                                                                                             | 82 of 116 appear in at least one test file, 34 in none. Appearing is not the same as testing the hook as an extension point                                                                                                                              |
| KimaAI's own listeners          | `grep -rnoE "(add\|remove\|has)_(filter\|action)\(\s*'kimaai_..."` over `app/`, `premium/app/`                                                                                            | The "Hooked by KimaAI" column                                                                                                                                                                                                                            |

The roadmap's count of 2026-11-14 (98 hooks, 77 filters and 21 actions in 49 files) was made with a method that is not recorded, so the difference to the 116 here is not broken down.

**Scheduled jobs** fire through WP-Cron or Action Scheduler, not through a call in the code, and are internal by nature: `kimaai_db_update_runner`, `kimaai_insights_close_sessions`, `kimaai_chatbot_session_retention_cleanup`, `kimaai_lead_retention_cleanup`, `kimaai_log_retention_cleanup`, `kimaai_insights_assign_topics`, `kimaai_insights_label_topics`, `kimaai_lead_sync`, `kimaai/pinned_answers/warm_cache`, `kimaai/embedding/reconcile`, `kimaai/embedding/backfill-access`, `kimaai/embedding/process_page`, `kimaai/embedding/process_post`, `kimaai/eval/scheduled_run` and `kimaai/eval/run_batch` (`grep -rnE "const (HOOK|[A-Z_]*_HOOK|HOOK_[A-Z]+)\s*="`). They get no page and no tag; the check ignores them.

**A listener without a hook:** `premium/app/Embedding/Embedding.php:79` adds a `kimaai_chatbot_vector_search` filter that no code applies (only `tests/unit/Embedding/EmbeddingAccessTest.php:129` does). HK-4 removes it and moves the test to the retrieval path that is used.

**Browser events.** The admin and the widget also send `CustomEvent`s on `window` (`kimaai:ask-ai`, `kimaai:fieldComponentsChanged`, `kimaai:admin-assistant-*`, `kimaai/gravityform/rendered`). They wire KimaAI's own components together and are internal, except `kimaai:fieldComponentsChanged`, which `registerFieldComponent()` sends and the field-components guide mentions.

## Inventory

Every extension point, by the roadmap's areas. "Where" is the file and line of each call. "Feature" is the FS registry id (`app/Features/Features.php`), `none` for plugin-wide hooks. "Tier": free when the call is in `app/` or `src/`, premium when it is in `premium/`.

**Hidden features.** Today only `voice` is hidden, and it has no hooks, so no hook belongs to a hidden feature. For the beta features: the hooks of `lead-capture`, `lead-score`, `customer-tools` and `search-answer` stop firing when their feature is hidden, because their classes are in `Loader::FEATURE_CLASSES` (`app/Loader.php:21`) or behind `Features::isEnabled()` (the Leads submenu, `AdminInit.php:103`). Three keep firing by design (FS: privacy and access keep running): `kimaai_lead_erased` (`LeadPrivacy` is not gated) and `kimaai_content_access_tokens` and `kimaai_user_access_tokens` (`AccessResolver` serves the access filter). `kimaai_chatbot_prompt` and the gate fire for the chatbot in any case; their second call site in `SearchAnswer.php` stops with `search-answer`.

### Chatbot (38)

| Hook                                              | Type                | Where                                                                       | Parameters                                                                                                                       | Returns                                        | Feature              | Tier    | First tag  | Hooked by KimaAI                                                                                                                         | Class    | Reason                                                                                      |
| ------------------------------------------------- | ------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | -------------------- | ------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------- |
| `kimaai_chatbot_prompt`                           | filter              | app/ChatBot/ChatbotRequestPreparer.php:96, app/ChatBot/SearchAnswer.php:130 | `mixed $prompt` (string from the request), `array $data`, `WP_REST_Request $request`                                             | the prompt                                     | `chatbot`            | free    | 1.3.5      | -                                                                                                                                        | public   | Rewrite or clean the visitor's message (page on kimaai.com)                                 |
| `kimaai_chatbot_gate`                             | filter              | app/ChatBot/ChatbotRequestPreparer.php:200                                  | `true\|string\|WP_Error $allowed`, `string $prompt`, `array $payload`, `array $data`, `WP_REST_Request $request`                 | `true`, or a message or `WP_Error` that blocks | `chatbot`            | free    | 1.3.5      | Security                                                                                                                                 | public   | Block a message by own rules; can only block, never open a check (page)                     |
| `kimaai_chatbot_allowed`                          | filter (deprecated) | app/ChatBot/ChatbotRequestPreparer.php:201                                  | `true $allowed`, `string $prompt`, `array $data`                                                                                 | as the gate                                    | `chatbot`            | free    | 1.2.5      | -                                                                                                                                        | internal | Deprecated alias of the gate since 1.3.0                                                    |
| `kimaai_chatbot_blocked`                          | action              | app/ChatBot/ChatbotRequestPreparer.php:224                                  | `string $error_message`, `array $payload`, `array $data`, `WP_REST_Request $request`                                             | -                                              | `chatbot`            | free    | 1.3.5      | -                                                                                                                                        | public   | Log or alert on blocked messages (page)                                                     |
| `kimaai_chatbot_daily_message_limit`              | filter              | app/ChatBot/ChatbotRequestPreparer.php:251                                  | `int $max_messages`, `array $payload`, `string $user_ip`                                                                         | int                                            | `chatbot`            | free    | 1.5.4      | KimaAICLI, EvalRunner, AskChatbotTool                                                                                                    | public   | Different limits per role or logged-in visitors                                             |
| `kimaai_chatbot_rate_limited`                     | action              | app/ChatBot/ChatbotRequestPreparer.php:266                                  | `string $user_ip`, `int $today_message_count`, `int $max_messages`, `array $payload`, `array $chatbot_settings`                  | -                                              | `chatbot`            | free    | 1.3.5      | -                                                                                                                                        | public   | Alert when visitors hit the limit (page)                                                    |
| `kimaai_chatbot_ai_payload`                       | filter              | app/ChatBot/ChatbotRequestPreparer.php:157                                  | `array $ai_payload`, `array $payload`, `array $chatbot_settings`                                                                 | array                                          | `chatbot`            | free    | 1.3.5      | PinnedAnswers                                                                                                                            | public   | Change the request to the provider (page)                                                   |
| `kimaai_chatbot_before_request`                   | action              | app/ChatBot/ChatbotRequestPreparer.php:159                                  | `array $ai_payload`, `array $payload`, `array $chatbot_settings`                                                                 | -                                              | `chatbot`            | free    | 1.3.5      | AnswerQuality                                                                                                                            | public   | Timing and logging (page)                                                                   |
| `kimaai_chatbot_response_payload`                 | filter              | app/ChatBot/ChatbotNormalRequestRunner.php:75                               | `array $response`, `array $ai_payload`, `array $payload`, `array $chatbot_settings`                                              | array                                          | `chatbot`            | free    | 1.3.5      | -                                                                                                                                        | public   | Add fields to the JSON answer (page)                                                        |
| `kimaai_chatbot_after_response`                   | action              | app/ChatBot/ChatbotNormalRequestRunner.php:83                               | `array $response`, `array $ai_payload`, `array $payload`, `array $chatbot_settings`                                              | -                                              | `chatbot`            | free    | 1.3.5      | -                                                                                                                                        | public   | Analytics after an answer (page)                                                            |
| `kimaai_chatbot_error`                            | action              | app/ChatBot/ChatbotNormalRequestRunner.php:57                               | `string $code`, `string $message`, `array $context` (exception, ai_payload, payload, normalized_error)                           | -                                              | `chatbot`            | free    | 1.3.5      | -                                                                                                                                        | public   | Alert on provider errors (page)                                                             |
| `kimaai_chatbot_streaming_eligible`               | filter              | app/ChatBot/ChatbotStreamingRequestRunner.php:131                           | `bool $eligible`, `ChatbotPreparedRequest $prepared`                                                                             | bool                                           | `chatbot`            | free    | 1.5.4      | OutputGuardrails                                                                                                                         | internal | Passes ChatbotPreparedRequest, an internal class; used by the guardrails                    |
| `kimaai_chatbot_final_message`                    | filter              | app/Ai/AiService.php:368                                                    | `string $ai_response`, `array $payload`, `string $provider`                                                                      | string                                         | `chatbot`            | free    | 1.5.4      | OutputGuardrails, AnswerQuality                                                                                                          | public   | Post-process the answer text on both paths (used by guardrails and sources)                 |
| `kimaai_chat_response_saved`                      | action              | app/Ai/AiService.php:434                                                    | `string $provider`, `array $payload`, `array $response`                                                                          | -                                              | `chatbot`            | free    | 1.5.4      | UsageTracker, ChatbotRateLimiter, SessionRecorder, HumanHandoff, AskChatbotTool                                                          | public   | The one completion point on both paths: usage, cost, analytics                              |
| `kimaai_chatbot_instructions`                     | filter              | app/Helper.php:715                                                          | `string $instructions`, `array $chatbot_settings`, `int $post_id`, `string $post_section`                                        | string                                         | `chatbot`            | free    | 1.2.5      | ChatbotContentAwareness, WooCommerceIntegrationPro                                                                                       | public   | Add site or page specific instructions                                                      |
| `kimaai_chatbot_content_awareness_post_types`     | filter              | app/ChatBot/ChatbotContentAwareness.php:80                                  | `array $post_types` (slug => label), `int $post_id`, `WP_Post $post`, `string $instructions`                                     | array                                          | `content-awareness`  | free    | 1.5.0      | -                                                                                                                                        | public   | Allow a custom post type the setting does not list                                          |
| `kimaai_chatbot_should_load`                      | filter              | app/ChatBot/ChatbotAssets.php:718                                           | `bool $enabled`                                                                                                                  | bool                                           | `chatbot`            | free    | 1.4.2      | -                                                                                                                                        | public   | Switch the floating chat off on chosen pages                                                |
| `kimaai_chatbot_frontend_settings`                | filter              | app/ChatBot/ChatbotAssets.php:654                                           | `array $frontend_settings`, `array $chatbot_settings`                                                                            | array                                          | `chatbot`            | free    | unreleased | VisitorHandoff, WhiteLabel                                                                                                               | internal | The widget's private settings contract; changes with every design track                     |
| `kimaai_chatbot_theme_vars`                       | filter              | app/ChatBot/ChatbotAssets.php:440                                           | `array $vars`, `array $theme`, `array $appearance`, `array $look`, `string $scheme`                                              | array                                          | `chatbot-appearance` | free    | 1.4.9      | -                                                                                                                                        | public   | Brand colours by code, per colour mode (the WD-3 contract)                                  |
| `kimaai_chatbot_theme`                            | filter              | app/ChatBot/ChatbotAssets.php:451                                           | `array $theme` (six colour keys)                                                                                                 | array                                          | `chatbot-appearance` | free    | 1.3.5      | -                                                                                                                                        | public   | Six pre-WD colour keys; the page exists, so it is deprecated, not dropped                   |
| `kimaai_chatbot_color_presets`                    | filter              | app/ChatBot/ChatbotTheme.php:78                                             | `array $presets`                                                                                                                 | array                                          | `chatbot-appearance` | free    | 1.4.9      | -                                                                                                                                        | internal | Feeds only the pre-WD theme and its carry-over; the Appearance page no longer shows presets |
| `kimaai_chatbot_theme_styles`                     | filter              | app/ChatBot/ChatbotTheme.php:141                                            | `array $styles`                                                                                                                  | array                                          | `chatbot-appearance` | free    | 1.4.9      | -                                                                                                                                        | internal | Feeds only the pre-WD theme and its carry-over; the new styles are not filterable           |
| `kimaai_chatbot_quick_actions_payload`            | filter              | app/ChatBot/ChatBot.php:222                                                 | `array $quick_actions` (start, byMessageId), `array $messages`, `string $session_id`, `int $post_id`, `array $quick_action_rows` | array                                          | `quick-actions`      | free    | 1.4.0      | ChatbotPremium                                                                                                                           | internal | Wiring for the premium quick actions; the per-placement filter is the API                   |
| `kimaai_chatbot_quick_actions`                    | filter              | premium/app/Features/ChatbotPremium.php:65, :88                             | `array $actions`, `array $context` (placement, sessionId, postId, messageId, message, messages)                                  | array                                          | `quick-actions`      | premium | 1.4.0      | -                                                                                                                                        | public   | Quick actions per page or after a matching answer                                           |
| `kimaai_chatbot_message_feedback_saved`           | action              | app/ChatBot/ChatbotFeedback.php:200                                         | `string $session_id`, `string $message_id`, `int $rating`, `string $comment`                                                     | -                                              | `feedback`           | free    | 1.5.4      | SessionOutcomeJob, HumanHandoff                                                                                                          | public   | Send ratings to an own system                                                               |
| `kimaai_chatbot_csat_saved`                       | action              | app/ChatBot/ChatbotFeedback.php:257                                         | `string $session_id`, `int $rating`, `string $comment`                                                                           | -                                              | `feedback`           | free    | unreleased | SessionOutcomeJob                                                                                                                        | public   | Send satisfaction ratings to an own system                                                  |
| `kimaai_chatbot_guardrails_violation`             | action              | app/ChatBot/OutputGuardrails.php:103                                        | `string[] $violations`, `string $message`, `array $payload`                                                                      | -                                              | `guardrails`         | free    | 1.5.4      | -                                                                                                                                        | public   | Alert when an answer used a banned term                                                     |
| `kimaai_chatbot_session_retention_days`           | filter              | app/ChatBot/ChatbotSessionRetention.php:162                                 | `int $days`, `array $chatbot_settings`, `string $mode`                                                                           | int                                            | `chat-history`       | free    | 1.4.9      | -                                                                                                                                        | public   | Retention by own policy                                                                     |
| `kimaai_chatbot_session_retention_should_run`     | filter              | app/ChatBot/ChatbotSessionRetention.php:296                                 | `bool $should_run`, `array $context`                                                                                             | bool                                           | `chat-history`       | free    | 1.4.9      | -                                                                                                                                        | public   | Pause the cleanup, for example during an export                                             |
| `kimaai_chatbot_session_retention_before_cleanup` | action              | app/ChatBot/ChatbotSessionRetention.php:312                                 | `array $context`                                                                                                                 | -                                              | `chat-history`       | free    | 1.4.9      | -                                                                                                                                        | public   | Archive before deletion                                                                     |
| `kimaai_chatbot_session_retention_after_cleanup`  | action              | app/ChatBot/ChatbotSessionRetention.php:353                                 | `array $after_context`                                                                                                           | -                                              | `chat-history`       | free    | 1.4.9      | -                                                                                                                                        | public   | Report what was deleted                                                                     |
| `kimaai_chatbot_session_retention_batch_size`     | filter              | app/ChatBot/ChatbotSessionRetention.php:547                                 | `int $batch_size`, `array $context`                                                                                              | int                                            | `chat-history`       | free    | 1.4.9      | -                                                                                                                                        | internal | Implementation detail of the cleanup job                                                    |
| `kimaai_chatbot_ungrounded_answer`                | action              | premium/app/ChatBot/AnswerQuality.php:95                                    | `string $message`, `string $reason`, `array $payload`                                                                            | -                                              | `knowledge-base`     | premium | 1.5.4      | SessionRecorder, HumanHandoff, GroundednessLogger                                                                                        | public   | Alert on answers the sources do not support                                                 |
| `kimaai_chatbot_handoff`                          | action              | premium/app/ChatBot/HumanHandoff.php:383                                    | `string $session_id`, `string $reason`, `string $transcript`                                                                     | -                                              | `human-handoff`      | premium | 1.5.4      | SessionRecorder                                                                                                                          | public   | Notify a team or tool when a conversation goes to a person                                  |
| `kimaai_trusted_proxies`                          | filter              | app/Ai/Security.php:172                                                     | `string[] $proxies`                                                                                                              | string[]                                       | `chatbot`            | free    | unreleased | -                                                                                                                                        | public   | Sites behind a CDN or proxy; no setting yet (Later)                                         |
| `kimaai_pinned_answer_embed_model`                | filter              | premium/app/ChatBot/PinnedAnswers.php:338                                   | `string $model`                                                                                                                  | string                                         | `pinned-answers`     | premium | 1.5.4      | -                                                                                                                                        | internal | Tuning of an internal matcher                                                               |
| `kimaai_chatbot_persisted_renderables`            | filter              | app/Assistant/AssistantRenderables.php:30                                   | `array $renderables`, `string $provider`, `array $payload`, `array $response`                                                    | array                                          | `chatbot`            | free    | 1.4.8      | LeadTriggers, AnswerQuality, VisitorHandoff, ContactForm7Integration, GravityFormsIntegration, WooCommerceIntegrationPro, MeetingBooking | internal | The widget renders only its own types, so other code cannot add one                         |
| `kimaai_chatbot_hydrated_renderables`             | filter              | app/Assistant/AssistantRenderables.php:65                                   | `array $renderables`, `array $stored`, `array $response`, `array $input`, `array $row`                                           | array                                          | `chatbot`            | free    | 1.4.8      | LeadForm, VisitorHandoff, ContactForm7Integration, GravityFormsIntegration, WooCommerceIntegrationPro, MeetingBooking                    | internal | As above                                                                                    |

### Embedding and search (26)

| Hook                                               | Type   | Where                                                                 | Parameters                                                                                                                      | Returns  | Feature          | Tier    | First tag  | Hooked by KimaAI  | Class    | Reason                                                          |
| -------------------------------------------------- | ------ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------- | ------- | ---------- | ----------------- | -------- | --------------------------------------------------------------- |
| `kimaai_embedding_render_mode`                     | filter | premium/app/Embedding/ContentProcessor.php:67                         | `string $mode` ('the_content' or raw), `?WP_Post $post`, `string $raw`                                                          | string   | `embeddings`     | premium | 1.4.2      | -                 | public   | Raw content for builders whose output breaks the index          |
| `kimaai_embedding_shortcode_blocklist`             | filter | premium/app/Embedding/ContentProcessor.php:69                         | `string[] $shortcodes`, `?WP_Post $post`                                                                                        | string[] | `embeddings`     | premium | 1.3.1      | -                 | public   | Keep a shortcode's output out of the index                      |
| `kimaai_embedding_min_text_length_before_fallback` | filter | premium/app/Embedding/ContentProcessor.php:136                        | `int $min_length`, `WP_Post $post`                                                                                              | int      | `embeddings`     | premium | 1.4.2      | -                 | internal | Internal threshold of the extractor                             |
| `kimaai_embedding_extra_text`                      | filter | premium/app/Embedding/ContentProcessor.php:145                        | `string $text`, `WP_Post $post`                                                                                                 | string   | `embeddings`     | premium | 1.4.2      | TemplateFlattener | public   | Index custom fields (ACF, product data)                         |
| `kimaai_embedding_skip_block_names`                | filter | premium/app/Embedding/ContentProcessor.php:185                        | `string[] $block_names`, `WP_Post $post`                                                                                        | string[] | `embeddings`     | premium | 1.4.2      | -                 | public   | Keep a block's output out of the index                          |
| `kimaai_embedding_remove_node_class_sets`          | filter | premium/app/Embedding/ContentProcessor.php:555                        | `array $class_sets` (lists of class names)                                                                                      | array    | `embeddings`     | premium | 1.4.2      | -                 | public   | Strip theme boxes (related posts, banners) from the index       |
| `kimaai_embedding_token_count`                     | filter | premium/app/Embedding/ContentProcessor.php:1112                       | `?int $count`, `string $text`                                                                                                   | ?int     | `embeddings`     | premium | 1.4.9      | -                 | internal | Internal estimate; an exact tokenizer changes chunking silently |
| `kimaai_embedding_remove_tags`                     | filter | premium/app/Embedding/ContentSanitizer.php:52                         | `string[] $tags`                                                                                                                | string[] | `embeddings`     | premium | 1.4.2      | -                 | internal | Defaults tuned for retrieval; changing them hurts quality       |
| `kimaai_embedding_chunk_text`                      | filter | premium/app/Embedding/Embedding.php:422, :480                         | `string $text`, `WP_Post $post`, `array $chunk`, `array $clean`                                                                 | string   | `embeddings`     | premium | 1.4.2      | -                 | public   | Prefix or clean a chunk before it is embedded                   |
| `kimaai_embedding_vector_before_upsert`            | filter | premium/app/Embedding/Embedding.php:510                               | `float[] $vector`, `WP_Post $post`, `array $chunk`, `array $clean`, `string $env_id`, `string $collection`, `string $namespace` | float[]  | `embeddings`     | premium | 1.4.2      | -                 | internal | Changing vectors breaks retrieval; no use case                  |
| `kimaai_embedding_store_vector_locally`            | filter | premium/app/Embedding/Embedding.php:531                               | `bool $store`, then the six context arguments above                                                                             | bool     | `embeddings`     | premium | 1.4.2      | -                 | internal | Storage detail                                                  |
| `kimaai_embedding_vector_metadata`                 | filter | premium/app/Embedding/Embedding.php:561                               | `array $meta`, `WP_Post $post`, `array $chunk`, `array $clean`                                                                  | array    | `embeddings`     | premium | 1.4.2      | -                 | public   | Add own metadata to stored chunks                               |
| `kimaai_embedding_index_changed`                   | action | premium/app/Embedding/Embedding.php:1181                              | none                                                                                                                            | -        | `embeddings`     | premium | unreleased | SearchAnswerCache | public   | Clear own caches when the knowledge base changes                |
| `kimaai_embedding_pdf_file_path`                   | filter | premium/app/Embedding/PdfTextExtractor.php:35                         | `string $path`, `WP_Post $attachment`                                                                                           | string   | `embeddings`     | premium | 1.4.9      | -                 | internal | Storage detail of the extractor                                 |
| `kimaai_pdf_max_bytes`                             | filter | premium/app/Embedding/PdfTextExtractor.php:50                         | `int $max_bytes`, `WP_Post $attachment`                                                                                         | int      | `embeddings`     | premium | unreleased | -                 | public   | Allow larger PDFs                                               |
| `kimaai_embedding_pdf_extracted_text`              | filter | premium/app/Embedding/PdfTextExtractor.php:97                         | `string $text`, `WP_Post $attachment`, `string $path`                                                                           | string   | `embeddings`     | premium | 1.4.9      | -                 | public   | Add OCR text for scanned PDFs                                   |
| `kimaai_embedding_list_posts_query_args`           | filter | premium/app/Embedding/RestApi.php:796                                 | `array $args`, `WP_REST_Request $request`                                                                                       | array    | `embeddings`     | premium | 1.4.2      | -                 | internal | Admin list query only                                           |
| `kimaai_embedding_supported_sources`               | filter | premium/app/Embedding/SourceHelper.php:47                             | `array $sources`                                                                                                                | array    | `embeddings`     | premium | 1.4.9      | -                 | public   | Add a content source to the knowledge base                      |
| `kimaai_embedding_attachment_mime_types`           | filter | premium/app/Embedding/SourceHelper.php:79                             | `string[] $mime_types`                                                                                                          | string[] | `embeddings`     | premium | 1.4.9      | -                 | internal | Only PDF has an extractor; another type indexes nothing         |
| `kimaai_embedding_fetch_query_args`                | filter | premium/app/Embedding/SourceHelper.php:172                            | `array $query_args`, `array $args`                                                                                              | array    | `embeddings`     | premium | 1.5.4      | DocumentLibrary   | public   | Leave posts out of a bulk index                                 |
| `kimaai_embedding_source_title`                    | filter | premium/app/Embedding/SourceHelper.php:203                            | `string $title`, `WP_Post $post`                                                                                                | string   | `embeddings`     | premium | 1.4.9      | -                 | public   | Title shown in sources                                          |
| `kimaai_kb_search_meta_filter`                     | filter | premium/app/FunctionCall/ToolRouter.php:634                           | `array $meta_filter`, `array $args`, `array $payload`                                                                           | array    | `knowledge-base` | premium | 1.5.4      | -                 | public   | Narrow retrieval by own metadata                                |
| `kimaai_keyword_search_query_args`                 | filter | premium/app/FunctionCall/KeywordSearch/AbstractWpQueryProvider.php:58 | `array $args`, `string $provider_id`                                                                                            | array    | `knowledge-base` | premium | 1.5.4      | -                 | public   | Tune the keyword leg of hybrid search                           |
| `kimaai_keyword_search_providers`                  | filter | premium/app/FunctionCall/KeywordSearch/KeywordSearchManager.php:50    | `KeywordSearchProviderInterface[] $providers`                                                                                   | array    | `knowledge-base` | premium | 1.5.4      | -                 | public   | Plug in an own search engine                                    |
| `kimaai_vector_service_call`                       | filter | premium/app/Embedding/VectorService.php:385                           | `?array $stub`, `string $operation`, `array $args`, `VectorService $service`                                                    | ?array   | `embeddings`     | premium | 1.5.8      | -                 | internal | Test seam, only with KIMAAI_E2E_TESTING                         |
| `kimaai_eval_regression`                           | action | premium/app/Eval/EvalScheduler.php:240                                | `array $summary`, `array $failures`, `int $threshold`                                                                           | -        | `eval`           | premium | 1.5.4      | -                 | public   | Alert when answer quality drops                                 |

### Leads and customer centre (7)

| Hook                            | Type   | Where                                | Parameters                                           | Returns  | Feature                  | Tier    | First tag  | Hooked by KimaAI                                       | Class  | Reason                                                  |
| ------------------------------- | ------ | ------------------------------------ | ---------------------------------------------------- | -------- | ------------------------ | ------- | ---------- | ------------------------------------------------------ | ------ | ------------------------------------------------------- |
| `kimaai_lead_saved`             | action | app/Leads/LeadForm.php:289           | `int $lead_id`, `array $lead`                        | -        | `lead-capture`           | free    | unreleased | LeadsAdmin, FormAttribution, LeadScorer, LeadSyncQueue | public | Send leads to a CRM KimaAI does not support             |
| `kimaai_lead_event`             | action | app/Leads/LeadForm.php:211           | `int $lead_id`, `string $event`                      | -        | `lead-capture`           | free    | unreleased | FormAttribution, LeadScorer, LeadSyncQueue             | public | React to a booked meeting                               |
| `kimaai_lead_erased`            | action | app/Leads/LeadPrivacy.php:201        | `int $lead_id`                                       | -        | `lead-capture`           | free    | unreleased | InsightsPrivacy, LeadSyncQueue                         | public | Erase the lead in own systems too (GDPR)                |
| `kimaai_leads_capability`       | filter | app/Leads/LeadsAdmin.php:61          | `string $capability`                                 | string   | `lead-capture`           | free    | unreleased | -                                                      | public | Let a sales role see leads without admin rights         |
| `kimaai_lead_free_mail_domains` | filter | premium/app/Leads/LeadScorer.php:187 | `string[] $domains`                                  | string[] | `lead-score`             | premium | unreleased | -                                                      | public | Local free-mail providers in the score                  |
| `kimaai_content_access_tokens`  | filter | app/Access/AccessResolver.php:89     | `string[] $tokens`, `int $post_id`, `?WP_Post $post` | string[] | `members-only-knowledge` | free    | unreleased | -                                                      | public | Membership plugins decide who may see a post in answers |
| `kimaai_user_access_tokens`     | filter | app/Access/AccessResolver.php:126    | `string[] $tokens`, `int $user_id`                   | string[] | `members-only-knowledge` | free    | unreleased | -                                                      | public | Membership plugins decide which tokens a user holds     |

### Admin assistant (19)

| Hook                                               | Type             | Where                                                     | Parameters                                                                                                       | Returns             | Feature           | Tier | First tag | Hooked by KimaAI | Class    | Reason                                                                           |
| -------------------------------------------------- | ---------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------- | ----------------- | ---- | --------- | ---------------- | -------- | -------------------------------------------------------------------------------- |
| `kimaai_admin_assistant_prompt`                    | filter           | app/AdminAssistant/AdminAssistantRequestPreparer.php:71   | `mixed $prompt`, `array $data`, `WP_REST_Request $request`                                                       | the prompt          | `admin-assistant` | free | 1.5.0     | -                | public   | Same role as the chatbot prompt filter                                           |
| `kimaai_admin_assistant_gate`                      | filter           | app/AdminAssistant/AdminAssistantRequestPreparer.php:73   | `true\|string\|WP_Error $allowed`, `string $prompt`, `array $payload`, `array $data`, `WP_REST_Request $request` | as the chatbot gate | `admin-assistant` | free | 1.5.0     | -                | public   | Restrict the assistant by role or content                                        |
| `kimaai_admin_assistant_blocked`                   | action           | app/AdminAssistant/AdminAssistantRequestPreparer.php:85   | `string $error_message`, `array $payload`, `array $data`, `WP_REST_Request $request`                             | -                   | `admin-assistant` | free | 1.5.0     | -                | public   | Audit blocked requests                                                           |
| `kimaai_admin_assistant_ai_payload`                | filter           | app/AdminAssistant/AdminAssistantRequestPreparer.php:167  | `array $ai_payload`, `array $payload`, `array $settings`                                                         | array               | `admin-assistant` | free | 1.5.0     | -                | public   | Change the request to the provider                                               |
| `kimaai_admin_assistant_before_request`            | action           | app/AdminAssistant/AdminAssistantRequestPreparer.php:169  | `array $ai_payload`, `array $payload`, `array $settings`                                                         | -                   | `admin-assistant` | free | 1.5.0     | -                | public   | Audit assistant use                                                              |
| `kimaai_admin_assistant_rate_limited`              | action           | app/AdminAssistant/AdminAssistantRequestPreparer.php:208  | `int $user_id`, `int $today_message_count`, `int $max_messages`, `array $settings`                               | -                   | `admin-assistant` | free | 1.5.0     | -                | public   | Alert on the limit                                                               |
| `kimaai_admin_assistant_instructions`              | filter           | app/Helper.php:702                                        | `string $instructions`, `array $settings`, `int $post_id`                                                        | string              | `admin-assistant` | free | 1.5.0     | -                | public   | Site specific rules for the assistant                                            |
| `kimaai_admin_assistant_config`                    | filter           | app/AdminAssistant/AdminAssistantConfigProvider.php:22    | `array $config`                                                                                                  | array               | `admin-assistant` | free | 1.5.0     | -                | internal | Workflow config, changes with the assistant                                      |
| `kimaai_admin_assistant_settings_overrides`        | filter           | app/AdminAssistant/SettingsCatalog.php:853                | `array $overrides`                                                                                               | array               | `admin-assistant` | free | 1.5.0     | -                | internal | Catalogue aliases, internal                                                      |
| `kimaai_admin_assistant_current_hook`              | filter           | app/AdminAssistant/AdminAssistant.php:229                 | `string $hook_suffix`                                                                                            | string              | `admin-assistant` | free | 1.5.0     | -                | internal | Screen detection fallback, internal                                              |
| `kimaai_admin_assistant_embedding_test_connection` | filter           | app/AdminAssistant/AdminAssistantWorkflowManager.php:2012 | `?array $result`, `array $payload`                                                                               | ?array              | `admin-assistant` | free | 1.5.0     | -                | internal | Test seam                                                                        |
| `kimaai_admin_assistant_persisted_renderables`     | filter           | app/Assistant/AssistantRenderables.php:27                 | `array $renderables`, `string $provider`, `array $payload`, `array $response`                                    | array               | `admin-assistant` | free | 1.5.0     | -                | internal | The assistant's renderable contract is not designed for other code               |
| `kimaai_admin_assistant_hydrated_renderables`      | filter           | app/Assistant/AssistantRenderables.php:55                 | `array $renderables`, `array $stored`, `array $response`, `array $input`, `array $row`                           | array               | `admin-assistant` | free | 1.5.0     | -                | internal | As above                                                                         |
| `kimaai_admin_assistant_tools_registry`            | filter (dynamic) | app/ChatBot/Tools/ChatbotToolRegistry.php:68              | `array $tools`, `array $payload`, `array $settings`                                                              | array               | `admin-assistant` | free | 1.5.0     | -                | internal | Assistant tools carry confirmations and renderables; not designed for other code |
| `kimaai_admin_assistant_allowed_tools`             | filter (dynamic) | app/ChatBot/Tools/ChatbotToolRegistry.php:53              | `string[] $tool_names`                                                                                           | string[]            | `admin-assistant` | free | 1.5.0     | -                | internal | As above                                                                         |
| `kimaai_assistant_history_model`                   | filter           | app/Ai/AiService.php:471                                  | `AssistantHistoryModelInterface $model`, `array $payload`                                                        | object              | `admin-assistant` | free | 1.5.0     | AdminAssistant   | internal | Swaps the history store (an internal interface)                                  |
| `kimaai_assistant_history_context`                 | filter           | app/Ai/AiService.php:494                                  | `array $context`, `array $payload`                                                                               | array               | `admin-assistant` | free | 1.5.0     | -                | internal | History scoping, internal                                                        |
| `kimaai_assistant_persisted_renderables`           | filter           | app/Assistant/AssistantRenderables.php:33                 | `array $renderables`, `string $surface`, `string $provider`, `array $payload`, `array $response`                 | array               | `chatbot`         | free | 1.5.0     | -                | internal | Both surfaces; renderables are not an extension API (section 4)                  |
| `kimaai_assistant_hydrated_renderables`            | filter           | app/Assistant/AssistantRenderables.php:75                 | `array $renderables`, `string $surface`, `array $stored`, `array $response`, `array $input`, `array $row`        | array               | `chatbot`         | free | 1.5.0     | -                | internal | As above                                                                         |

### Settings and admin (9)

| Hook                            | Type      | Where                                     | Parameters                                         | Returns  | Feature        | Tier    | First tag  | Hooked by KimaAI | Class    | Reason                                                        |
| ------------------------------- | --------- | ----------------------------------------- | -------------------------------------------------- | -------- | -------------- | ------- | ---------- | ---------------- | -------- | ------------------------------------------------------------- |
| `kimaai_settings_schema_files`  | filter    | app/Admin/Settings.php:352                | `string[] $files`                                  | string[] | `none`         | free    | 1.2.2      | WhiteLabel       | public   | Add-ons add their own settings pages                          |
| `kimaai_settings_ui_config`     | filter    | app/Admin/SettingsUiConfigProvider.php:49 | `array $config`                                    | array    | `none`         | free    | 1.5.0      | -                | internal | Admin shell config, changes with the design                   |
| `kimaai_wizard_config`          | filter    | app/Admin/Wizard/Wizard.php:145           | `array $config`                                    | array    | `setup-wizard` | free    | 1.4.0      | -                | internal | Wizard steps, changes with the design                         |
| `kimaai_log_level`              | filter    | app/Logger.php:90                         | `string $level`                                    | string   | `logs`         | free    | 1.3.5      | -                | internal | A setting exists                                              |
| `kimaai_log_retention_days`     | filter    | app/Logging/LogCleanupScheduler.php:102   | `int $days`, `array $log_settings`, `string $mode` | int      | `logs`         | free    | 1.5.0      | -                | internal | A setting exists                                              |
| `kimaai_mcp_log_retention_days` | filter    | premium/app/Mcp/McpModule.php:84          | `int $days`                                        | int      | `mcp-server`   | premium | 1.5.8      | -                | public   | Retention policy for MCP logs, which hold prompts; no setting |
| `kimaai_feature_status`         | filter    | app/Features/Features.php:351             | `string $status`, `string $id`                     | string   | `none`         | free    | unreleased | -                | internal | For tests and development (CONTRIBUTING, "Feature status")    |
| `kimaai.admin.fieldComponents`  | JS filter | src/admin/fieldComponentsRegistry.js:36   | `Object $components` (key => React component)      | Object   | `none`         | free    | n/a        | -                | public   | Add-ons render their own setting fields                       |
| `kimaai_trigger_button_click`   | JS action | src/admin/components/TriggerButton.jsx:18 | `Event event`, `Object {text, variant}`            | -        | `none`         | free    | n/a        | -                | public   | Add-ons react to their own settings button                    |

### Tools and addons (19)

| Hook                                           | Type             | Where                                                                                       | Parameters                                                                         | Returns                          | Feature          | Tier    | First tag | Hooked by KimaAI                                                                                                                         | Class    | Reason                                                             |
| ---------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------- | ---------------- | ------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------ |
| `kimaai_register_addons`                       | action           | app/KimaAI.php:94                                                                           | `AddonManager $manager`, `Main $main`, `ClassesSurface $classes`                   | -                                | `none`           | free    | 1.3.7     | KimaAI                                                                                                                                   | public   | Register an add-on                                                 |
| `kimaai_loaded`                                | action           | app/KimaAI.php:105                                                                          | `Main $main`, `ClassesSurface $classes`, `AddonManager $manager`                   | -                                | `none`           | free    | 1.3.7     | -                                                                                                                                        | public   | Run code once KimaAI is ready                                      |
| `kimaai_fs_loaded`                             | action           | kimaai.php:95                                                                               | none                                                                               | -                                | `none`           | free    | 1.2.3     | -                                                                                                                                        | internal | Freemius SDK convention; no use case outside Freemius              |
| `kimaai_is_premium`                            | filter           | app/Main.php:68                                                                             | `bool $is_premium`                                                                 | bool                             | `none`           | free    | 1.5.8     | -                                                                                                                                        | internal | Licence check                                                      |
| `kimaai_can_use_premium_code`                  | filter           | app/KimaAI.php:74                                                                           | `bool $can_use_premium`                                                            | bool                             | `none`           | free    | 1.5.8     | -                                                                                                                                        | internal | Licence check                                                      |
| `kimaai_ai_http_client`                        | filter           | app/Ai/AiService.php:770                                                                    | `?HttpClientInterface $client`, `string $provider`, `string $generation_type`      | ?object                          | `none`           | free    | 1.5.8     | -                                                                                                                                        | internal | Test seam, only with KIMAAI_E2E_TESTING                            |
| `kimaai_tools_registry`                        | filter           | app/Ai/ToolRegistry.php:232                                                                 | `array $tools` (name => label, description, parameters, sensitive, callback)       | array                            | `function-tools` | free    | 1.4.0     | VisitorHandoff, CustomerTools, ContactForm7Integration, GravityFormsIntegration, WooCommerceIntegrationPro                               | public   | Define a custom tool (it then shows in the tool setting)           |
| `kimaai_chatbot_tools_registry`                | filter (dynamic) | app/ChatBot/Tools/ChatbotToolRegistry.php:68                                                | `array $tools`, `array $payload`, `array $chatbot_settings`                        | array                            | `function-tools` | free    | 1.3.5     | LeadTriggers, ToolRouter, UserTools, MeetingBooking                                                                                      | public   | Offer a tool per request (page)                                    |
| `kimaai_chatbot_allowed_tools`                 | filter (dynamic) | app/ChatBot/Tools/ChatbotToolRegistry.php:53                                                | `string[] $tool_names`                                                             | string[]                         | `function-tools` | free    | 1.4.8     | LeadTriggers, VisitorHandoff, CustomerTools, ContactForm7Integration, GravityFormsIntegration, WooCommerceIntegrationPro, MeetingBooking | public   | Enable a tool by code                                              |
| `kimaai_chatbot_tool_call`                     | filter           | app/ChatBot/Tools/ToolCallOrchestrator.php:369                                              | `mixed $result` (null), `string $name`, `array $args`, `array $payload`            | result or null                   | `function-tools` | free    | 1.4.9     | AdminAssistantSettingsTools, LeadTriggers, VisitorHandoff, CustomerTools, ToolRouter, MeetingBooking                                     | public   | Run a custom tool                                                  |
| `kimaai_stream_tool_call`                      | filter           | app/ChatBot/Tools/ToolCallOrchestrator.php:375                                              | as `kimaai_chatbot_tool_call`                                                      | result or null                   | `function-tools` | free    | 1.4.1     | AdminAssistantSettingsTools, ToolRouter                                                                                                  | public   | Fires right after kimaai_chatbot_tool_call with the same arguments |
| `kimaai_tool_call_allowed`                     | filter           | premium/app/FunctionCall/ToolRouter.php:76, premium/app/CustomerTools/CustomerTools.php:115 | `true\|string $allow`, `string $name`, `array $args`                               | `true`, or a message that blocks | `function-tools` | premium | 1.3.3     | -                                                                                                                                        | public   | Block or audit tool calls                                          |
| `kimaai_tool_execute`                          | filter           | premium/app/FunctionCall/ToolRouter.php:99                                                  | `mixed $result` (null), `string $name`, `array $args`, `?array $def`               | result or null                   | `function-tools` | premium | 1.4.0     | -                                                                                                                                        | internal | A third way to run a tool; the guide documents one                 |
| `kimaai_chatbot_default_tools`                 | filter           | premium/app/FunctionCall/ToolRouter.php:672                                                 | `array $tools`                                                                     | array                            | `function-tools` | premium | 1.3.5     | -                                                                                                                                        | internal | Duplicate of the tools registry                                    |
| `kimaai_chatbot_max_tool_rounds`               | filter           | app/ChatBot/Tools/ToolCallOrchestrator.php:76                                               | `int $max_rounds`, `array $payload`                                                | int                              | `function-tools` | free    | 1.5.4     | -                                                                                                                                        | public   | Allow more rounds for chained tools                                |
| `kimaai_chatbot_command_callbacks`             | filter           | app/ChatBot/Tools/ToolCommandHandler.php:111                                                | `array $callbacks` (name => callable), `array $payload`, `array $chatbot_settings` | array                            | `chatbot`        | free    | 1.4.0     | AdminAssistantWorkflowManager, VisitorHandoff                                                                                            | internal | Callbacks of built-in renderables                                  |
| `kimaai_ai_chat_response`                      | filter           | app/Ai/AiService.php:259                                                                    | `array $response`, `string $provider`, `array $payload`, `object $ai_provider`     | array                            | `chatbot`        | free    | 1.3.7     | ToolCallOrchestrator                                                                                                                     | internal | Provider-specific response shapes; runs the tool loop              |
| `kimaai_chatbot_gravityforms_preload_form_ids` | filter           | premium/app/Integrations/GravityFormsIntegration.php:221                                    | `int[] $form_ids` (default `[189, 115]`)                                           | int[]                            | `none`           | premium | 1.4.8     | -                                                                                                                                        | internal | Dormant integration with hard-coded form ids                       |
| `kimaai_chatbot_gravityforms_action_url`       | filter           | premium/app/Integrations/GravityFormsIntegration.php:391, :395                              | `string $url`, `int $form_id`                                                      | string                           | `none`           | premium | 1.4.8     | -                                                                                                                                        | internal | Dormant integration                                                |

## Public or internal

The roadmap's rule: public hooks are documented and kept stable; internal ones carry `@internal`, get no page and may change. The class and the reason for each hook are in the inventory above. Counted from it (`awk` over the classification):

| Area                      | Public | Of these premium |
| ------------------------- | ------ | ---------------- |
| Chatbot                   | 28     | 4                |
| Embedding and search      | 17     | 17               |
| Leads and customer centre | 7      | 1                |
| Admin assistant           | 7      | 0                |
| Settings and admin        | 4      | 1                |
| Tools and addons          | 9      | 1                |
| **Total**                 | **72** | **24**           |

46 hooks are internal, 14 of them premium. The public count includes the two deprecated hooks, whose pages stay until the alias goes.

What makes a hook internal, in order of how often it applies:

- **Wiring between KimaAI's own classes** (`kimaai_chatbot_quick_actions_payload`, `kimaai_chatbot_command_callbacks`, `kimaai_ai_chat_response`, `kimaai_chatbot_default_tools`, the renderable and history filters). The public hook is the one a developer would reach for; the wiring changes with the code.
- **The admin assistant's tool, renderable and workflow contract** (`kimaai_admin_assistant_tools_registry`, `_allowed_tools`, `_persisted_renderables`, `_hydrated_renderables`, `_config`, `_settings_overrides`, `_current_hook`). Its tools ask for confirmation and return renderables the assistant's own screens draw; it was not designed for other code. The request hooks of the assistant (prompt, gate, blocked, AI payload, before request, rate limited, instructions) are public, as the chatbot's are.
- **Test seams**: `kimaai_ai_http_client`, `kimaai_vector_service_call`, `kimaai_admin_assistant_embedding_test_connection`, `kimaai_feature_status`.
- **Hooks that pass an internal class**: `kimaai_chatbot_streaming_eligible` (`ChatbotPreparedRequest`).
- **The pre-WD theme**: `kimaai_chatbot_color_presets` and `kimaai_chatbot_theme_styles` reach only `ChatbotTheme::normalize()`, whose result feeds the legacy `$theme` argument of `kimaai_chatbot_theme_vars` and the carry-over of old sites (`LookCarryOver.php:98`). The Appearance page of WD no longer shows presets or those styles.
- **Settings that already exist** (`kimaai_log_level`, `kimaai_log_retention_days`) and **implementation details** (`kimaai_embedding_token_count`, `kimaai_embedding_remove_tags`, `kimaai_embedding_vector_before_upsert`, the retention batch size).
- **Dormant code**: the two Gravity Forms filters. `GravityFormsIntegration` is not registered (`app/Admin/Integrations/IntegrationManager.php:27` is a comment), and `kimaai_chatbot_gravityforms_preload_form_ids` defaults to the hard-coded form ids `[189, 115]`. The roadmap's "Later" already asks whether these integrations ship again (QA-1).
- **`kimaai_fs_loaded`**: Freemius' naming convention for its add-ons; KimaAI has none. Internal, name kept.

### Surfaces share hooks

`ChatbotNormalRequestRunner` serves the chatbot, the admin assistant and the search answer (`AdminAssistant.php:44`, `SearchAnswer.php:49`), and `AiService::saveChatResponse()` serves every surface. So `kimaai_chatbot_response_payload`, `kimaai_chatbot_after_response`, `kimaai_chatbot_error`, `kimaai_chatbot_final_message`, `kimaai_chat_response_saved` and `kimaai_chatbot_tool_call` also fire for admin assistant requests, and `kimaai_chatbot_prompt`, `kimaai_chatbot_gate` and `kimaai_chatbot_blocked` also for search answers (`SearchAnswer.php:130`). Renaming public hooks for this would break the pages that exist; instead each page says which surfaces it fires for and that `$payload['assistantSurface']` (`chatbot`, `admin_assistant` or `search`) tells them apart.

## Risky hooks

A hook only runs code a site already runs, so no hook gives a visitor rights by itself. The risk is code that unlocks something the site did not pay for or did not choose: the licence, a check that protects visitors' data, or a limit. Each hook of that kind, and what HK-4 does with it:

| Hook                                                                                                                                                                                                 | Risk                                                                                                                                                                                                                                                                                                                                                               | Proposal                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_is_premium` (`Main.php:68`), `kimaai_can_use_premium_code` (`KimaAI.php:74`)                                                                                                                 | Licence. Both are applied only when `KIMAAI_E2E_TESTING` is defined (also in 1.5.13). Any plugin that loads first, an mu-plugin for example, can define the constant and add the filter, so a premium build with an expired licence loads its premium code                                                                                                         | **Stop being filters.** Both read one helper, `Helper::isTestSite()`: `KIMAAI_E2E_TESTING`, `WP_DEBUG` and the file `tests/e2e/playground.json` inside the plugin, plus the existing option `kimaai_e2e_force_premium`, as `Helper::isPremium()` does (`Helper.php:920`). Neither zip contains `tests/` (`scripts/zip-utils.mjs`, `EXCLUDE_DIR_NAMES`; `.distignore`), so a shipped plugin passes the check only if its own files are changed, which no hook can prevent. `Helper::isPremium()` and `AdminAssistantWorkflowManager::isPremiumEnabled()` use the same helper. The e2e mu-plugin in `tests/e2e/playground.json` stops hooking the two filters; the e2e and WP-CLI suites keep working through the option. HK-4 checks that the free-build suite still runs without `tests/` |
| `kimaai_ai_http_client` (`AiService.php:770`), `kimaai_vector_service_call` (`VectorService.php:385`), `kimaai_admin_assistant_embedding_test_connection` (`AdminAssistantWorkflowManager.php:2012`) | Test seams. They replace provider answers, vector results or a connection test; no licence or permission, but no production use either. The first two have the same constant gate as above; the third has none                                                                                                                                                     | Internal, behind `Helper::isTestSite()`. HK-4 checks that the integration bootstrap (`tests/bootstrap-integration.php`) meets it, or keeps the third ungated and internal if it cannot                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `kimaai_trusted_proxies` (`Security.php:172`)                                                                                                                                                        | The client IP behind the daily limit and the banned IPs. A range that covers every address makes `X-Forwarded-For`, which any visitor can send, the client IP                                                                                                                                                                                                      | Public, with a guard: entries that are not an IP address or a CIDR range are ignored, and so are ranges with prefix length 0. The page says what trusting a proxy means. A setting stays in "Later" (QA-6)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `kimaai_settings_schema_files` (`Settings.php:352`)                                                                                                                                                  | Stored settings and the secrets masking of AD-13. A filter that drops a core file makes `Settings::register()` prune the stored values of its keys (FS research: "`register()` prunes stored values whose keys leave the schema"), and drops the `isSensitive` markers `SettingsSecrets` reads (`SettingsSecrets.php:278`), so stored keys would reach the browser | Public, with a guard: the core files are added back after the filter, so add-ons can add files but never remove one. A key counts as secret when any schema file marks it. HK-4 tests both: a filter that removes a core file, and an added file that defines a secret field again without `isSensitive`; the key still reads as saved, never as its value                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `kimaai_leads_capability` (`LeadsAdmin.php:61`)                                                                                                                                                      | Who may see, export and delete leads (personal data)                                                                                                                                                                                                                                                                                                               | Public, with a guard: an empty or non-string result falls back to `manage_options`. The page says that the capability opens personal data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `kimaai_chatbot_daily_message_limit` (`ChatbotRequestPreparer.php:251`)                                                                                                                              | The per-IP limit that caps provider cost. KimaAI raises it itself for eval, MCP and WP-CLI runs (`EvalRunner.php:76`, `AskChatbotTool.php:99`, `KimaAICLI.php:190`)                                                                                                                                                                                                | Public, with a guard: the result is cast to an integer of at least 0. The page names the cost risk                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `kimaai_tool_call_allowed` (`ToolRouter.php:76`, `CustomerTools.php:115`)                                                                                                                            | Not a bypass: it can only block. But it misses tools: the lead, handoff and meeting tools answer `kimaai_chatbot_tool_call` at priority 5 (`LeadTriggers.php:50`, `VisitorHandoff.php:76`, `MeetingBooking.php:56`) and the admin assistant's settings tools at 10 without it, so an audit built on it sees only some calls                                        | Public; applied once in `ToolCallOrchestrator::executeTool()` before `kimaai_chatbot_tool_call`, so every tool call passes it. It becomes free. `CustomerTools` keeps its own audit row                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

Checked and not risky:

- **The gates** (`kimaai_chatbot_gate`, `kimaai_admin_assistant_gate`) block on anything but `true`; they cannot open a check.
- **The admin assistant's permission** (`AdminAssistant::canUseAssistant()`, `AdminAssistant.php:209`) asks `current_user_can('manage_options')` first. `kimaai_admin_assistant_current_hook` and `kimaai_admin_assistant_config` only choose the screens among admins.
- **Members-only content.** `kimaai_content_access_tokens` and `kimaai_user_access_tokens` are the access model on purpose: membership plugins decide with them. `kimaai_embedding_vector_metadata` can change a chunk's stored `access`, and `kimaai_kb_search_meta_filter` the retrieval filter, but the access filter is merged after the filter (`ToolRouter.php:510`) and every hit passes `canView()` before it is used (`ToolRouter.php:531`, `KeywordSearchManager.php:83`, `SearchAnswer.php:158`, `ChatbotContentAwareness.php:91`, `Embedding.php:107`).
- **Nonces.** No KimaAI hook decides a nonce check (3 nonce checks in `app/` and `premium/app/`, none behind a filter).
- **The secrets masking itself** hooks core's `rest_pre_get_setting` and `rest_dispatch_request` (`SettingsSecrets.php:59`) and has no hook of its own; only the schema files reach it.

The licence check outside hooks, for context: in 1.5.13, `Helper::isPremium()` treated a site as premium with `WP_DEBUG` and the option `kimaai_e2e_force_premium`, without the e2e constant (`git show 1.5.13:app/Helper.php`, line 805). `development` has fixed it (QA-8, `0a464fa5`); the fix ships with the next release.

## Naming

| Issue                                                                                                                                                                                                                                                                                                                                              | Plan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_assistant_*` next to `kimaai_admin_assistant_*`. In the code, "assistant" means any surface (the `KimaAI\Assistant` namespace serves the chatbot and the admin assistant), "admin assistant" the admin surface, and "chatbot" the front end. The four `kimaai_assistant_*` filters read as admin-assistant hooks but run for every surface | Surface-neutral hooks are named `kimaai_chat_*`, as `kimaai_chat_response_saved` already is: `kimaai_assistant_history_model` → `kimaai_chat_history_model`, `kimaai_assistant_history_context` → `kimaai_chat_history_context`, `kimaai_assistant_persisted_renderables` → `kimaai_chat_persisted_renderables`, `kimaai_assistant_hydrated_renderables` → `kimaai_chat_hydrated_renderables`. They are internal, but released in 1.5.0, so each old name stays as an `apply_filters_deprecated` alias for two minor releases |
| `kimaai_stream_tool_call` fires right after `kimaai_chatbot_tool_call` with the same arguments (`ToolCallOrchestrator.php:369-375`); the name suggests a streaming-only hook, which it no longer is                                                                                                                                                | Deprecated, replacement `kimaai_chatbot_tool_call`                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `kimaai_chatbot_theme` filters six colour keys of the theme before WD and writes override properties                                                                                                                                                                                                                                               | Deprecated, replacement `kimaai_chatbot_theme_vars`. Its kimaai.com page becomes "Deprecated since" with the replacement                                                                                                                                                                                                                                                                                                                                                                                                      |
| `kimaai_chatbot_allowed` is deprecated since 1.3.0 (`ChatbotRequestPreparer.php:201`); 1.4 and 1.5 have shipped since                                                                                                                                                                                                                              | Removed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `kimaai_pdf_max_bytes` lacks the `embedding` part every other indexing hook has                                                                                                                                                                                                                                                                    | `kimaai_embedding_pdf_max_bytes`. Unreleased (not in 1.5.13), so renamed without an alias                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `kimaai_admin_assistant_instructions` says `@since 1.8.2` (`Helper.php:700`); there is no such release, and the name first appears in 1.5.0                                                                                                                                                                                                        | `@since 1.5.0`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `kimaai_chatbot_should_load` controls only the floating chat on every page (`ChatbotAssets::isEnableGlobally()`); the block and the shortcode load anyway                                                                                                                                                                                          | Name kept (released since 1.4.2); the page says what it controls                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `kimaai_tools_registry` and `kimaai_chatbot_tools_registry` sound alike. The first is the catalogue (the tool setting lists it, and it holds `sensitive` and `callback`); the second offers tools per request                                                                                                                                      | Names kept; the custom-tools guide explains the pair                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| JS names: `kimaai.admin.fieldComponents` uses dots, `kimaai_trigger_button_click` underscores                                                                                                                                                                                                                                                      | Kept: two hooks, both public, and `@wordpress/hooks` accepts both. New JS names use the dotted form                                                                                                                                                                                                                                                                                                                                                                                                                           |

**How a rename works.** The new name is the hook; right after it, the old name runs through `apply_filters_deprecated()` or `do_action_deprecated()` with the version of the release and the new name, so old callbacks keep working and WordPress reports the deprecation under `WP_DEBUG`. The old name's page stays, with `deprecated: {since, replacement, removal}` in its frontmatter and "Deprecated since x.y.z. Use ..." at the top. After two minor releases (deprecated in 1.6 means removed in 1.8) the alias and the page go, and the website redirects the page to its replacement. Deprecations count as "next" until their release, like `since`.

## New hooks

Only where a concrete use case has no hook today.

| Extension point                  | Use case                                                                                                                                                                                   | Where it fires                                                                                           | Parameters                                                                                                                                                                                                           | Tier and feature     |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `kimaai_lead_validate` (filter)  | Refuse an address before it is stored and sent on: disposable or free-mail addresses on a B2B site, a competitor's domain. Today only `kimaai_lead_saved` exists, after the lead is stored | `LeadForm.php`, after the consent checks and before `$this->lead_model->save($lead)` (line 276)          | `true\|WP_Error $valid`, `array $lead`, `WP_REST_Request $request`; a `WP_Error` returns its message to the form with status 400. It cannot change the lead, so the consent text stays the one the visitor agreed to | free, `lead-capture` |
| `kimaai:chatbot` (browser event) | Chat engagement in analytics or Google Tag Manager: chat opened, message sent, answer shown, rating, lead sent. The PHP hooks run on the server and never see an open                      | Sent by the widget on `window`, outside its shadow root, from the widget's controllers in `src/chatbot/` | `event.detail`: `type` (`open`, `close`, `message`, `answer`, `feedback`, `lead`), `sessionId`, and for `feedback` the rating. No message text, so no personal data reaches analytics                                | free, `chatbot`      |

Existing hooks that change instead of new ones:

- `kimaai_chatbot_error` and `kimaai_chatbot_after_response` fire on the streaming path too: from `ChatbotStreamingRequestRunner::emitNormalizedError()` and its `catch` (lines 77 and 442; the stream loop catches at 377), and after `saveChatResponse()` (line 288). `kimaai_chatbot_response_payload` stays non-streaming: a streamed answer has no response body to filter.
- `kimaai_chatbot_handoff` gets a fourth argument, `array $ticket` (`channel`, `reference`, `url` of the `TicketRef` that `HumanHandoff::finalize()` already has), so a team can post "ticket 123 opened in Zendesk" to its chat.
- `kimaai_trigger_button_click` passes the field's key in its second argument, so an add-on with two buttons knows which one was clicked.
- `kimaai_tool_call_allowed` runs for every tool (see "Risky hooks").

Considered and not added:

- **Leave one post out of the knowledge base:** covered. `kimaai_content_access_tokens` returning `['deny']` keeps the post out of the index (`Embedding::isIndexable()`, line 732) and out of every answer.
- **A custom helpdesk on handoff:** covered by the webhook channel of the handoff and by `kimaai_chatbot_handoff`.
- **A custom CRM:** covered by `kimaai_lead_saved`.
- **A hook when a conversation ends** (Insights closes sessions in `SessionOutcomeJob`): no concrete request; `kimaai_chat_response_saved` and the lead hooks cover the known cases.
- **Per-page widget settings** (`kimaai_chatbot_frontend_settings` as public): it is the widget's private contract and changes with every design track; per-page switching off is `kimaai_chatbot_should_load`.
- **Admin assistant tools for add-ons, and renderables in the widget:** both need an API designed for other code first (confirmations, the widget's shadow root and React). To "Later".

## What kimaai.com has today

Read on 2026-11-16 from the live site (`https://kimaai.com/docs-category/developers/` and each page, fetched with `curl`). The pages live in the production database as BetterDocs posts (post type `docs`, taxonomy `doc_category`), not in the website repository. All 11 are dated 22 February 2026.

The roadmap counts six hook pages; the site has 11, five actions and six filters. The six may be the five of the docs navigation story (`wp-content/plugins/custom/blocks/docs-layout/docs-layout.stories.js:23-30`) plus `kimaai_chatbot_prompt`; the count's source is not recorded.

| Page (URL under `kimaai.com/docs/`) | Hook in the code                                                                | Matches the code?                                                                                                                                                                 | What changes                                                                                                         |
| ----------------------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `kimaai-chatbot-after-response/`    | `kimaai_chatbot_after_response`, action, `ChatbotNormalRequestRunner.php:83`    | Signature yes (4 arguments). It says the hook fires after every successful answer; it fires only when the answer does not stream, and also for admin assistant and search answers | HK-5 makes it fire on the streaming path; the new page says which surfaces                                           |
| `kimaai-chatbot-error/`             | `kimaai_chatbot_error`, action, `ChatbotNormalRequestRunner.php:57`             | Signature yes; the context also has `normalized_error`, which the page does not name. Fires only without streaming                                                                | HK-5 makes it fire on the streaming path                                                                             |
| `kimaai-chatbot-response-payload/`  | `kimaai_chatbot_response_payload`, filter, `ChatbotNormalRequestRunner.php:75`  | Signature yes. Runs only without streaming; the page does not say so                                                                                                              | Stays non-streaming; the page says so and points to `kimaai_chatbot_final_message` for the answer text on both paths |
| `kimaai-chatbot-before-request/`    | `kimaai_chatbot_before_request`, action, `ChatbotRequestPreparer.php:159`       | Yes                                                                                                                                                                               | Rewritten in the new format                                                                                          |
| `kimaai-chatbot-rate-limited/`      | `kimaai_chatbot_rate_limited`, action, `ChatbotRequestPreparer.php:266`         | Yes (5 arguments)                                                                                                                                                                 | Same                                                                                                                 |
| `kimaai-chatbot-blocked/`           | `kimaai_chatbot_blocked`, action, `ChatbotRequestPreparer.php:224`              | Yes (4 arguments); also fires for search answers                                                                                                                                  | Same                                                                                                                 |
| `kimaai-chatbot-ai-payload/`        | `kimaai_chatbot_ai_payload`, filter, `ChatbotRequestPreparer.php:157`           | Yes                                                                                                                                                                               | Same                                                                                                                 |
| `kimaai-chatbot-tools-registry/`    | `kimaai_chatbot_tools_registry`, filter (dynamic), `ChatbotToolRegistry.php:68` | Yes (3 arguments; its sample docblock calls the second `$data`, the code `$payload`). It does not name `kimaai_chatbot_allowed_tools`, which enables a tool without the setting   | Part of the custom-tools guide                                                                                       |
| `kimaai-chatbot-gate/`              | `kimaai_chatbot_gate`, filter, `ChatbotRequestPreparer.php:200`                 | Yes (5 arguments)                                                                                                                                                                 | Rewritten in the new format                                                                                          |
| `kimaai-chatbot-promp/`             | `kimaai_chatbot_prompt`, filter, `ChatbotRequestPreparer.php:96`                | Text yes; the title and the address lack the final "t". The website roadmap holds the fix as FU-1 (a manual `wp post update 1204`)                                                | The synced page has the right address; FU-1 is no longer needed                                                      |
| `kimaai-chatbot-theme/`             | `kimaai_chatbot_theme`, filter, `ChatbotAssets.php:451`                         | The six keys yes. It says the variables are written on `:root` through `wp_add_inline_style()`; since WD they are written per colour mode on the widget's mount                   | Deprecated, replacement `kimaai_chatbot_theme_vars`                                                                  |

So none of the 11 describes a hook the code no longer has. The three pages the roadmap names describe hooks that run only when an answer does not stream; two are fixed, and the third's page says when it runs. The website's redirects cover the move of all 11 to `kimaai.com/docs/hooks/<name>/` (below), not removed hooks.

## The page format

### Files

- One page per public hook: `docs/hooks/<name>.md`, the hook's name as the file name (`docs/hooks/kimaai_chatbot_gate.md`, `docs/hooks/kimaai.admin.fieldComponents.md`). A browser event's file uses `-` for the `:` (`kimaai:chatbot` is `docs/hooks/kimaai-chatbot.md`, with `name: 'kimaai:chatbot'`).
- `docs/hooks/index.json`: generated by the check script (`--write`), never edited by hand, and compared by the check like the generated files of the website (`storybook/styles/tokens.css`). It lists per page the name, type, area, feature, the feature's status from the registry, tier, `since`, the deprecation and the summary, so the website's sync reads one file and never parses PHP.
- The page template lives outside `docs/hooks/`, in `docs/hook-page-template.md`, so the check does not take it for a page.

### Frontmatter

```yaml
---
name: kimaai_chatbot_gate # the hook's name, equal to the file name (browser events: see above)
type: filter # filter | action | js-filter | js-action | js-event
since: 1.3.5 # first release, or "next" until the release that ships it
tier: free # free | premium
feature: chatbot # an id of app/Features/Features.php, or "none" for plugin-wide hooks
area: chatbot # chatbot | embedding-search | leads-customer-centre | admin-assistant | settings-admin | tools-addons
summary: Blocks a visitor's message before anything is sent to the AI provider. # one sentence, for the index
parameters: # in call order; empty list for none
  - name: allowed
    type: true|string|WP_Error
    description: True to answer. A message or a WP_Error blocks the request and is shown to the visitor.
  - name: prompt
    type: string
    description: The visitor's message after the prompt filter and masking.
returns: # filters only
  type: true|string|WP_Error
  description: The decision.
surfaces: [chatbot, search] # optional: chatbot | admin_assistant | search, where the hook fires
deprecated: # optional
  since: 1.6.0
  replacement: kimaai_chatbot_theme_vars
  removal: 1.8.0
---
```

`area` is not in the roadmap's list; it is needed for the index per area, because a feature id does not say which area a hook belongs to (`chatbot` hooks sit in two areas). Types use PHP's notation for PHP hooks and JSDoc's for JS ones.

### Body

Sections in this order, in sentence case:

1. `## When it fires`: the request or job it belongs to, the surfaces, what ran before it.
2. `## Example`: one fenced `php` (or `js`) block, complete and runnable on its own: the test runs this block. Nothing else may come before it in the section.
3. `## More examples` (optional).
4. `## Related`: the hooks that pair with it.

Parameters are not repeated in the body; the website renders them from the frontmatter.

### Docblock

A public hook, at every call site (the full form once, at the first site in file order; further sites carry only the tag):

```php
/**
 * Filters whether the chatbot may answer a message.
 *
 * @kimaai-hook kimaai_chatbot_gate
 * @since 1.3.5
 * @see https://kimaai.com/docs/hooks/kimaai_chatbot_gate/
 *
 * @param true|string|WP_Error $allowed True to answer; a message or WP_Error blocks.
 * @param string $prompt The visitor's message.
 * @param array $payload The normalised payload.
 * @param array $data The request's JSON body.
 * @param WP_REST_Request $request The request.
 * @return true|string|WP_Error
 */
$allowed = apply_filters('kimaai_chatbot_gate', true, $payload['prompt'], $payload, $data, $request);
```

An internal hook:

```php
/**
 * Filters the tools the admin assistant offers.
 *
 * @internal Not a public hook: no page, and it may change without notice.
 */
```

A dynamic name lists every name it builds, each as public or internal:

```php
/**
 * @kimaai-hook kimaai_chatbot_tools_registry
 * @internal kimaai_admin_assistant_tools_registry
 */
$tools = apply_filters($hook_prefix . '_tools_registry', $registry_seed, $payload, $chatbot_settings);
```

A deprecated alias:

```php
/**
 * @kimaai-hook kimaai_stream_tool_call
 * @deprecated next Use kimaai_chatbot_tool_call.
 */
$result = apply_filters_deprecated('kimaai_stream_tool_call', [null, $name, $args, $payload], 'next', 'kimaai_chatbot_tool_call');
```

JS hooks and the browser event use the same tags in a JSDoc block above `applyFilters()`, `doAction()` or `dispatchEvent()`.

## The check

`npm run check` gets a step "Hook pages" after "Brand tokens": `node scripts/check-hooks.mjs`. It fails when the code and the pages disagree and prints each difference with its file and line.

**How it finds hooks:**

- **PHP:** `scripts/hooks-inventory.php` (the tokenizer walk of this research) prints every call of the six hook functions in `app/`, `premium/app/` and `kimaai.php` as JSON: the name or, for a non-literal name, the expression; the type; file and line; the number of arguments; and the tags of the docblock directly above. Names without the `kimaai` prefix (`the_content`, WPML, Gravity Forms) are skipped.
- **Dynamic names:** a call whose first argument is not one string must list its names with `@kimaai-hook` or `@internal <name>`, and each listed name must end with the expression's last string part (`_tools_registry`). A dynamic call without such a list fails.
- **JS:** the Node script scans `src/**/*.{js,jsx}` for `applyFilters(`, `doAction(` and `new CustomEvent(` with a first argument that starts with `kimaai`, and reads the JSDoc above. A non-literal first argument fails.
- **Pages:** `docs/hooks/*.md`, frontmatter read with the `yaml` package (in `node_modules` today only as a transitive dependency; HK-3 adds it to `devDependencies`).
- **Features:** the ids, statuses and `requires` of the map in `app/Features/Features.php`, read by `hooks-inventory.php` with the same tokenizer, so the check keeps no copy of the list.

**What it compares:**

1. Every hook has `@kimaai-hook` or `@internal` at every call site.
2. Every `@kimaai-hook` hook has a page, and every page a hook in the code (or `deprecated.removal` reached, when the website redirects it).
3. `type` matches the call (`apply_filters*` is a filter, `do_action*` an action).
4. The parameters: names and types equal the docblock's `@param` list, and their number equals the arguments at every call site.
5. `since` equals `@since`; `tier` follows the call sites (premium when all are in `premium/`); `feature` is a registered id or `none`; `@see` is `https://kimaai.com/docs/hooks/<name>/`.
6. A deprecated page has `deprecated.since` and `replacement`, and the code calls `apply_filters_deprecated` or `do_action_deprecated` with the same version and replacement.
7. The page has an `## Example` block, and a test names the page (`HookPage::example('<name>')`, see "Tests").
8. `docs/hooks/index.json` equals what `--write` would write.
9. `@internal` hooks have no page.
10. The body uses only the Markdown the website converts: headings, paragraphs, lists, tables, fenced code, inline code and links.

**Until every area is done**, the script holds a list of public hooks without a page yet (`PENDING`), filled in HK-4 when the tags go in, and every area item removes its names. A hook that is neither tagged, internal nor pending fails from HK-4 on.

**`ci/test-map.mjs`.** The first matching rule wins, and the rule for text (`**/*.md`, `docs/**`) selects nothing, so two rules go before it:

```js
// The example of a hook page runs inside its test.
{area: 'Hook pages', paths: ['docs/hooks/**', 'docs/hook-page-template.md'], select: {unit: 'one', jest: JS_HOOK_TESTS, cli: ['hooks']}},
// The check itself.
{area: 'Hook check', paths: ['scripts/check-hooks.mjs', 'scripts/hooks-inventory.php'], select: {eslint: true, jest: ['tests/js/hooks/checkHooks.test.js'], unit: 'one'}},
```

The second goes before "Developer scripts". The check's own Jest test lives in `tests/js/hooks/`, not `tests/js/scripts/`, because the rule "Related-test tooling" claims `tests/js/scripts/**` and selects only the test-plan test. `cli: ['hooks']` needs a new group `hooks` in `CLI_GROUPS` with the WP-CLI hook tests (below). `JS_HOOK_TESTS` is the list of the JS hook tests in `tests/js/hooks/`, a constant next to `E2E_GROUPS`, because `--findRelatedTests` cannot follow a Markdown file.

## Tests

Every public hook gets a test that hooks in and checks the effect; the page's example is the code that hooks in.

**The helper.** `tests/support/HookPage.php` (HK-3) reads `docs/hooks/<name>.md`, takes the block under `## Example`, writes it to a temporary file and `require`s it, so the test runs the page's code exactly. The test then drives the code path and asserts the effect, and removes its callbacks afterwards. A JS twin in `tests/js/hooks/hookPage.js` does the same for JS pages.

**Where the tests live.**

| Suite                  | Where                                                        | Runs                                         | For                                                                                                                                                                                                                                                                                                                                                 |
| ---------------------- | ------------------------------------------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PHP unit               | `tests/unit/Hooks/<Area>/<Hook>Test.php`, one class per hook | In `npm run check`, on every commit          | Most hooks. The unit bootstrap emulates `add_filter`, `apply_filters`, `do_action` and `apply_filters_deprecated` (`tests/bootstrap-provider-sdk.php:184-240` and `:760-801`); HK-3 adds `do_action_deprecated` where it is missing                                                                                                                 |
| WP-CLI, real WordPress | `tests/cli/HooksTest.php`, group `hooks`                     | On the AI box (`check:related`, `check:all`) | Hooks that need WordPress to boot, REST permissions or enqueued output: `kimaai_register_addons`, `kimaai_loaded`, `kimaai_settings_schema_files` (with the secrets masking through `/wp/v2/settings`), `kimaai_leads_capability`, `kimaai_chatbot_should_load`, `kimaai_chatbot_theme_vars`. `CliTestCase::php()` runs the example as an mu-plugin |
| Jest                   | `tests/js/hooks/`                                            | In `npm run check`                           | `kimaai.admin.fieldComponents`, `kimaai_trigger_button_click`, `kimaai:chatbot`                                                                                                                                                                                                                                                                     |

Integration tests (`tests/integration`) stay for flows across classes; a hook test does not need a provider, so none of them costs money.

**The public hooks by area**, for the items HK-5 to HK-10 (from the classification; new hooks in italics):

| Area                              | Public hooks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chatbot (28 + 1)                  | `kimaai_chatbot_prompt`, `kimaai_chatbot_gate`, `kimaai_chatbot_blocked`, `kimaai_chatbot_daily_message_limit`, `kimaai_chatbot_rate_limited`, `kimaai_chatbot_ai_payload`, `kimaai_chatbot_before_request`, `kimaai_chatbot_response_payload`, `kimaai_chatbot_after_response`, `kimaai_chatbot_error`, `kimaai_chatbot_final_message`, `kimaai_chat_response_saved`, `kimaai_chatbot_instructions`, `kimaai_chatbot_content_awareness_post_types`, `kimaai_chatbot_should_load`, `kimaai_chatbot_theme_vars`, `kimaai_chatbot_theme`, `kimaai_chatbot_quick_actions`, `kimaai_chatbot_message_feedback_saved`, `kimaai_chatbot_csat_saved`, `kimaai_chatbot_guardrails_violation`, `kimaai_chatbot_session_retention_days`, `kimaai_chatbot_session_retention_should_run`, `kimaai_chatbot_session_retention_before_cleanup`, `kimaai_chatbot_session_retention_after_cleanup`, `kimaai_chatbot_ungrounded_answer`, `kimaai_chatbot_handoff`, `kimaai_trusted_proxies`, _`kimaai:chatbot`_ |
| Embedding and search (17)         | `kimaai_embedding_render_mode`, `kimaai_embedding_shortcode_blocklist`, `kimaai_embedding_extra_text`, `kimaai_embedding_skip_block_names`, `kimaai_embedding_remove_node_class_sets`, `kimaai_embedding_chunk_text`, `kimaai_embedding_vector_metadata`, `kimaai_embedding_index_changed`, `kimaai_embedding_pdf_max_bytes`, `kimaai_embedding_pdf_extracted_text`, `kimaai_embedding_supported_sources`, `kimaai_embedding_fetch_query_args`, `kimaai_embedding_source_title`, `kimaai_kb_search_meta_filter`, `kimaai_keyword_search_query_args`, `kimaai_keyword_search_providers`, `kimaai_eval_regression`                                                                                                                                                                                                                                                                                                                                                                             |
| Leads and customer centre (7 + 1) | `kimaai_lead_saved`, `kimaai_lead_event`, `kimaai_lead_erased`, `kimaai_leads_capability`, `kimaai_lead_free_mail_domains`, `kimaai_content_access_tokens`, `kimaai_user_access_tokens`, _`kimaai_lead_validate`_                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| Admin assistant (7)               | `kimaai_admin_assistant_prompt`, `kimaai_admin_assistant_gate`, `kimaai_admin_assistant_blocked`, `kimaai_admin_assistant_ai_payload`, `kimaai_admin_assistant_before_request`, `kimaai_admin_assistant_rate_limited`, `kimaai_admin_assistant_instructions`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Settings and admin (4)            | `kimaai_settings_schema_files`, `kimaai_mcp_log_retention_days`, `kimaai.admin.fieldComponents`, `kimaai_trigger_button_click`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| Tools and addons (9)              | `kimaai_register_addons`, `kimaai_loaded`, `kimaai_tools_registry`, `kimaai_chatbot_tools_registry`, `kimaai_chatbot_allowed_tools`, `kimaai_chatbot_tool_call`, `kimaai_stream_tool_call`, `kimaai_tool_call_allowed`, `kimaai_chatbot_max_tool_rounds`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

## The kimaai.com side

Built in this track (owner, 2026-11-16), in the website repository (`navidabdi/kimaai-website`), after the pages exist. Read for this research, not changed: its `CLAUDE.md`, `docs/ARCHITECTURE.md`, `docs/ROADMAP.md`, `docs/CONTRIBUTING.md`, `bin/check.sh`, the site code in `wp-content/plugins/custom/src/` and the plugin `github-changelog-sync`.

**What exists there.**

- Docs are BetterDocs posts (`docs`, `doc_category`); `KimaAI\Custom\Docs` (`wp-content/plugins/custom/src/Docs.php`) reads them in BetterDocs' order for the docs blocks and gives headings ids for "On this page". Every doc is written by hand in WordPress; nothing imports docs today.
- The one import is the changelog: the own plugin `github-changelog-sync` (a git submodule) fetches a file from GitHub's contents API on a WP-Cron schedule, with an optional token in its settings, stores it in an option, and `KimaAI\Custom\Changelog` parses it.
- Production has no WP-CLI (`docs/ARCHITECTURE.md`, "Backups and undo"), Composer is for development tools only (`composer.json`), and the previews load a nightly copy of the production database without users.
- The plugin repository is private (`gh repo view navidabdi/kimaai`), and `docs/` is not in the plugin zips (`scripts/zip-utils.mjs` copies an allow-list), so the site's bundled `kimaai-pro` (1.5.10 today) has no pages.

**The proposal.**

- **Where:** a class `KimaAI\Custom\HookDocs` in the site code (`wp-content/plugins/custom/src/HookDocs.php`), not in the changelog plugin, which is a single-purpose submodule.
- **Source:** the latest release tag of `navidabdi/kimaai` (the highest version tag; tags are what a release creates), read through GitHub's contents API: `docs/hooks/index.json` first, then each page whose blob SHA differs from the one stored on its post (`_kimaai_hook_sha`). The ref is a setting so that the track can test against `development`; production uses the latest tag.
- **Token:** a fine-grained, read-only token for that one repository (Contents: read), as the constant `KIMAAI_DOCS_GITHUB_TOKEN` from the server's environment. Not an option, because options travel into the local copies and the previews with the database.
- **When:** daily through WP-Cron, and a "Sync now" button for administrators (with a nonce), as the changelog sync has. A WP-CLI command for local runs.
- **Pages:** one `docs` post per hook, found by the meta `_kimaai_hook` (the name). New names create a post, changed ones update it, a name whose feature is hidden (`index.json`) is not published or goes back to draft, a name no longer in the index goes to draft and redirects to its `replacement` when it has one. English only.
- **Content:** the Markdown becomes core blocks (heading, paragraph, list, table, code), so the theme styles it and the content rule (no hand-set classes, website rule 6) holds. A small converter for the subset the pages use, instead of a Markdown library at runtime, because Composer there is for tools only; the plugin's check keeps the pages inside that subset. The parameters render from the frontmatter as a table; a deprecated hook shows a notice with its replacement at the top. The notice is a visual element, so it is designed as a story first (website rule 8).
- **Index per area:** a `doc_category` "Hooks" under "Developers" with one child per area (the six areas); BetterDocs' category pages are the index. The two categories of today ("Hooks · Actions", "Hooks · Filters") are retired.
- **URLs:** `kimaai.com/docs/hooks/<name>/` through a rewrite rule and a `post_type_link` filter for posts with `_kimaai_hook`. The 11 existing posts are adopted (their `_kimaai_hook` is set on the first sync, so ids and reactions stay), and their old addresses (`/docs/kimaai-chatbot-*/`, including `kimaai-chatbot-promp`) answer with a 301 to the new ones. FU-1 in the website roadmap closes without the manual update.
- **Checks:** the website has no PHP test suite (`bin/check.sh`: PHP syntax, PHPCS, shell, tokens, icons, content classes, lints, build). The item adds a fixture check to it: the converter turns a stored sample page into blocks and the result is compared with stored markup.
- **Process there:** the website's rules (its `CLAUDE.md`): an issue that tracks it, a track branch from its `development`, items as pull requests into it with its `npm run check`, and production only on the owner's word. UD reuses the sync for feature pages and guides.

## Item plan

The items run one after another (owner, 2026-11-16), each on `track/HK-hooks` except the website items, which run in the website repository as described above.

| Item  | Title                                                                                                                                                                                                                                                                                                                                                                                                                                    | Needs |
| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| HK-1  | This research                                                                                                                                                                                                                                                                                                                                                                                                                            |       |
| HK-2  | Conventions: the docblock tags, the frontmatter and body of a page, `docs/hook-page-template.md`, `since: next`, the rule in `CONTRIBUTING.md`, `CLAUDE.md` and `AGENTS.md` that a hook change updates its page in the same commit, and the release-pr skill's step that replaces `next`                                                                                                                                                 | HK-1  |
| HK-3  | The check: `scripts/hooks-inventory.php`, `scripts/check-hooks.mjs` with `--write` and `index.json`, the step in `scripts/check.mjs`, `yaml` as a dev dependency, the two `ci/test-map.mjs` rules, the `hooks` WP-CLI group, `tests/support/HookPage.php` and its JS twin, `do_action_deprecated` in the unit bootstrap, the check's own Jest test                                                                                       | HK-2  |
| HK-4  | Lock and mark: the licence filters replaced by `Helper::isTestSite()`, the test seams behind it, the four guards, `@internal` on the 46 internal hooks, `@kimaai-hook` on the public ones (all in `PENDING`), the four `kimaai_chat_*` renames and the two deprecations with their aliases, `kimaai_chatbot_allowed` removed, `kimaai_embedding_pdf_max_bytes`, the dead `kimaai_chatbot_vector_search` listener removed, `@since 1.5.0` | HK-3  |
| HK-5  | Chatbot: tests and pages for its 28 public hooks; `kimaai_chatbot_error` and `kimaai_chatbot_after_response` on the streaming path; the ticket in `kimaai_chatbot_handoff`; the new `kimaai:chatbot` event                                                                                                                                                                                                                               | HK-4  |
| HK-6  | Embedding and search: tests and pages for its 17                                                                                                                                                                                                                                                                                                                                                                                         | HK-5  |
| HK-7  | Leads and customer centre: tests and pages for its 7; the new `kimaai_lead_validate`                                                                                                                                                                                                                                                                                                                                                     | HK-6  |
| HK-8  | Admin assistant: tests and pages for its 7                                                                                                                                                                                                                                                                                                                                                                                               | HK-7  |
| HK-9  | Settings and admin: tests and pages for its 4 (two JS); the field key in `kimaai_trigger_button_click`; the field-components guide                                                                                                                                                                                                                                                                                                       | HK-8  |
| HK-10 | Tools and addons: tests and pages for its 9; `kimaai_tool_call_allowed` for every tool; the guides for add-ons and custom tools. `PENDING` is empty after it                                                                                                                                                                                                                                                                             | HK-9  |
| HK-11 | Reference pages: the REST routes (78 `register_rest_route()` calls in 20 files), the WP-CLI command (`wp kimaai`, one `WP_CLI::add_command()` with its subcommands) and the MCP tools (16 tool classes in `premium/app/Mcp/Tools/`), in `docs/reference/`, with their own format and check proposed in the item                                                                                                                          | HK-10 |
| HK-12 | The issue in `navidabdi/kimaai-website` for the sync: the format, `index.json`, the URLs and redirects, the token                                                                                                                                                                                                                                                                                                                        | HK-10 |
| HK-13 | Website: `HookDocs`, the import, the converter and its fixture check, the token constant, the schedule and the button                                                                                                                                                                                                                                                                                                                    | HK-12 |
| HK-14 | Website: `/docs/hooks/<name>/`, the area categories, the deprecation notice (story first), the 301s of the 11 old pages                                                                                                                                                                                                                                                                                                                  | HK-13 |

The track's pull request into `development` follows HK-11 (the plugin side), with the review and `check:related` as for every track; HK-12 to HK-14 follow the website's own review and merge rules. The pages appear on kimaai.com with the first release that contains them, because the sync reads the latest tag.

Compared with the roadmap's table: "JS hooks and the guides" and "The new hooks" are folded into the area items, so a hook's file is touched once; the renderables guide is dropped (renderables are not an extension API yet); the page format and the sync request become HK-12, and the website build becomes HK-13 and HK-14.

## Open points

- **The six pages of the roadmap:** the site has 11; the source of "six" is not recorded.
- **The roadmap's count of 98 hooks:** its method is not recorded, so it is not reconciled with the 116 here.
- **`since` of the released hooks:** the "First tag" column is the first tag whose PHP contains the name, which can be a listener rather than the call. HK-4 confirms it per public hook with `git log -S` before the pages take it.
- **The integration bootstrap and `Helper::isTestSite()`:** whether `tests/bootstrap-integration.php` meets the check is settled in HK-4 (see "Risky hooks").
- **Website token:** creating the fine-grained token and setting it on the server is the owner's step; HK-13 names it.

## HK-2 and HK-3 (build notes)

Built 2026-11-16 on `track/HK-hooks`. HK-2: `CONTRIBUTING.md` ("Hooks"), `docs/hook-page-template.md`, the rule in `CLAUDE.md` and `AGENTS.md`, step 3 of the `release-pr` skill (`.claude/skills/release-pr/` and its Codex copy). HK-3: `scripts/hooks-inventory.php`, `scripts/check-hooks.mjs` (`--write`), `docs/hooks/index.json`, the "Hook pages" step in `scripts/check.mjs`, the two `ci/test-map.mjs` rules and the `hooks` WP-CLI group, `tests/support/HookPage.php`, `tests/js/hooks/hookPage.js`, `do_action_deprecated()` in the unit bootstrap, and the tests (`tests/js/hooks/checkHooks.test.js`, `tests/js/hooks/hookPage.test.js`, `tests/unit/Hooks/HookPageTest.php`, `tests/cli/HooksTest.php`).

The inventory finds what the research counted: 119 call sites in 56 files (94 `apply_filters`, 24 `do_action`, 1 `apply_filters_deprecated`), 112 literal names and 2 built ones; with the 4 names those build, the 2 JS hooks and 8 browser events the check knows 126 hooks.

### Where the build differs from the plan

- **The page starts with its title** (`# <name>`). The Markdown lint of `npm run check` (MD041) asks for a first-level heading first, and the frontmatter has no `title` key that would count instead. The website's converter drops it, since the post title is the name. The check asks for it.
- **The example has no `<?php` tag.** It is meant for a `functions.php` or a plugin file; `HookPage` adds the tag before it runs the block.
- **A deprecation that no release has shipped** has `deprecated.since: next` and no `removal`; the release step writes the version and adds `removal` two minor releases on. The check accepts no other combination.
- **Two lists besides `PENDING`.** The plan has the tags arrive in HK-4, so in HK-3 no call site has one, and the check could not tell an old untagged hook from a new one. `UNTAGGED` lists every hook that has no tag yet (the 118 of the inventory and the 8 browser events) and `UNTAGGED_DYNAMIC` the names the untagged built calls produce (the two in `ChatbotToolRegistry.php` and six events named by a constant). HK-4 tags them and empties both; a name in `UNTAGGED` whose call sites are tagged fails, so the list cannot go stale. `PENDING` holds the 72 public hooks by area, with the current name `kimaai_pdf_max_bytes` until HK-4 renames it. Untagged hooks count as public when they are in `PENDING`, else as internal.
- **Browser events are hooks for the check.** The scan of `new CustomEvent(` the research plans finds the 8 internal events of "Browser events" above; they are not among the 46 internal hooks, so HK-4 tags them `@internal` as well. A JS call whose first argument is not a string literal (the admin assistant's events use constants) lists its names like a built PHP name.
- **The feature registry is read with `Features::all()`**, the class required with `ABSPATH` defined, not with the tokenizer: the same data in fewer lines, and the file runs nothing when it loads. A feature counts as hidden when a feature it requires is hidden, as in `Features::status()`.
- **One docblock parser**, in `check-hooks.mjs`, for PHP and JSDoc; the inventory prints the docblock's text. A docblock belongs to a call when no `;`, `{` or `}` stands between them, in PHP and in JS.
- **WP-CLI tests name the page with `HookPage::page('<name>')`**, since they install the example as an mu-plugin instead of running it in the test's process; the check accepts that, `HookPage::example()` and `hookPage.example()`. `tests/support/HookPage.php` is in the "Hook pages" rule of the test map, which selects the `hooks` group; otherwise the rule "PHPUnit unit" would claim it. `JS_HOOK_TESTS` is empty until HK-9 writes the JS hook tests.
- **More in the check than the ten points:** the return type (`@return` and `returns.type`), the title, the order of the sections and the example block, and stale entries in the three lists. `index.json` also names each page's `file`, so the website's sync needs no rule for the browser event's file name; `featureStatus` is `null` for `none`.
- **`yaml` as a dev dependency:** ESLint fails the import without it (`import/no-extraneous-dependencies`), so the research's reasoning holds. `^1.10.2` matches the 1.10.3 already installed, so `npm ci` needs nothing new. The npm cache had no metadata for an offline `npm install`, so `package.json` and the root entry of `package-lock.json` were edited by hand; `npm install --offline --package-lock-only` reports them up to date.
- **The check's Jest test needs PHP** for the inventory. The Node container of the AI box has none, so there the suite is skipped; on the Mac, where `npm run check` runs it, it runs.
- **`tests/cli/HooksTest.php`** has one test, that the template's example runs as an mu-plugin in WordPress. It runs on the AI box only, so it has not run yet; `check:related` runs it before the merge.

### The check fails on purpose

Run on this tree with a change each, then reverted (and in `checkHooks.test.js` on trees of its own):

| Change                                                                                                                           | Output of `node scripts/check-hooks.mjs` (exit 1)                                                                                                                                                                                                                                                                                                     |
| -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A page without a hook: the template as `docs/hooks/kimaai_not_in_code.md`                                                        | `docs/hooks/kimaai_not_in_code.md: kimaai_not_in_code has a page but no hook in the code`                                                                                                                                                                                                                                                             |
| An undeclared new hook: `apply_filters('kimaai_chatbot_brand_new', true)` in `ChatbotRequestPreparer.php`                        | `app/ChatBot/ChatbotRequestPreparer.php:200: kimaai_chatbot_brand_new is a new hook without a tag: add @kimaai-hook (public, with a page and a test) or @internal`                                                                                                                                                                                    |
| A hook without a page, not pending: the full docblock on `kimaai_chatbot_gate`, the name out of `UNTAGGED` and `PENDING`         | `app/ChatBot/ChatbotRequestPreparer.php:214: kimaai_chatbot_gate is public and has no page docs/hooks/kimaai_chatbot_gate.md (and is not PENDING)`                                                                                                                                                                                                    |
| A parameter mismatch: then the template's page (two parameters) as `docs/hooks/kimaai_chatbot_gate.md`, and a test that names it | `parameters are (string value, array payload), the docblock at app/ChatBot/ChatbotRequestPreparer.php:214 has (true\|string\|WP_Error allowed, string prompt, array payload, array data, WP_REST_Request request)`, `kimaai_chatbot_gate passes 5 argument(s), its page lists 2`, and the return type, the template's deprecation and the stale index |

Without a change: `Hook pages: 126 hooks, 0 pages, 72 pending, 126 untagged; 0 problems`, exit 0.

## HK-4 (build notes)

Built 2026-11-16 on `track/HK-hooks` in four commits: the licence and the test seams (`bfba8109`), the guards (`fa5a0328`), the renames and removals (`abac1bd0`), the tags (`2304c8e5`). The check now reads `Hook pages: 127 hooks, 0 pages, 72 pending, 0 untagged; 0 problems`: 116 PHP hooks before, minus the two licence filters and `kimaai_chatbot_allowed`, plus the four `kimaai_chat_*` names, with the 2 JS hooks and 8 browser events.

### What changed per risky hook

| Hook                                               | Now                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_is_premium`, `kimaai_can_use_premium_code` | Gone. `Helper::isTestSite()` is true with `KIMAAI_E2E_TESTING`, `WP_DEBUG` and `tests/e2e/playground.json` inside the plugin (`dirname(__DIR__)` of `app/Helper.php`). `Helper::canUsePremiumCode()` is the licence or, on a test site, the option `kimaai_e2e_force_premium`; `KimaAI::pluginsLoaded()` and `Main::getContainer()` call it, and `Helper::isPremium()` and `AdminAssistantWorkflowManager::isPremiumEnabled()` use the same test switch. The e2e mu-plugin no longer hooks the two filters |
| The three test seams                               | `@internal`, applied only when `Helper::isTestSite()`; `kimaai_admin_assistant_embedding_test_connection` had no gate before and has one now                                                                                                                                                                                                                                                                                                                                                               |
| `kimaai_trusted_proxies`                           | Only strings that are an IP address or `<address>/<digits>` with a prefix length above 0 count; anything else is ignored. The range check also needs the address and the range of the same family, and an IPv6 prefix length that is not a multiple of 8 keeps its last bits (a `/4` matched every address before)                                                                                                                                                                                         |
| `kimaai_settings_schema_files`                     | The core files are added back after the filter (a non-array answer counts as none, non-strings are dropped), so add-ons add files and never remove one. A key is secret when any file marks it: the secret paths (through `properties` and `items`) of every section are marked again on the final schema, so a file that defines a section again cannot unmask a stored key                                                                                                                               |
| `kimaai_leads_capability`                          | A non-string or blank answer falls back to `manage_options`                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `kimaai_chatbot_daily_message_limit`               | `max(0, (int) ...)`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |

Tests: `tests/unit/Runtime/E2ePremiumSwitchTest.php` (an expired licence with the old filters, with the old constant, and with the constant, `WP_DEBUG`, the option and the filters in a copy of the plugin without `tests/` loads no premium; a test site with the option does, for all three checks), `SecurityTest`, `SettingsSchemaFilesTest` (a filter that removes `aiServices.php` or answers `null`, an add-on file still added, an add-on `integrations.php` that defines the HubSpot token again without `isSensitive`: it reads as saved), `LeadsAdminTest`, `ChatbotRequestPreparerTest`, and `AiServiceTest` (the HTTP client seam is ignored outside a test site). Each guard's test fails on the code before it.

### The test setups (the open point of "Risky hooks")

- **Zips:** both scripts copy an allow-list without `tests/` (`FREE_INCLUDE_PATHS`, the premium script's `INCLUDE_PATHS`) and then prune every directory named `tests` (`zip-utils.mjs`, `EXCLUDE_DIR_NAMES`); the Freemius deploy builds with `npm run premium-plugin-zip`. So no zip passes `Helper::isTestSite()`.
- **Integration:** `tests/bootstrap-integration.php` defines `KIMAAI_E2E_TESTING` and `WP_DEBUG`, and runs from the checkout, which has `tests/e2e/playground.json` (on the AI box too: `ci/remote-check.sh` mounts the checkout). So it is a test site, and the third seam is gated like the other two instead of staying ungated. The whole suite ran on the Mac: 98 tests, 15 skipped (paid providers), among them the 17 of `AdminAssistantWorkflowManagerTest`, which use the seam and the premium option.
- **WP-CLI:** `CliTestCase::setUpSite()` writes the constants of `tests/e2e/playground.json` into `wp-config.php` (`KIMAAI_E2E_TESTING`, `WP_DEBUG`), the plugin is the mounted checkout (`ci/docker-compose.yml`, `PLUGIN_DIR=$DIR`) and it sets the option, so premium stays on. The suite runs only on the AI box and has not run here; `check:related` runs it before the merge. `SmokeTest`'s free-build test installs the staged free plugin, which has no `tests/`, so it stays free, as the test expects.
- **E2E:** the Playground mounts the checkout (`global-setup.ts`), so it is a test site. On the Mac, with 2 workers and the free plugin staged by `ci/stage-free-plugin.mjs` (no `tests/`, no `premium/`): `embedding-auto-sync`, `embedding-knowledge-search`, `chatbot-request`, `chatbot-customer-orders`, `chatbot-meeting-booking`, `chatbot-settings`, `chatbot-members-only`, `chatbot-lead-capture`, `white-label`, `mcp-admin`, `admin-settings`, `admin-settings-transfer` and `free-build`: 74 of 75 passed. The one failure was `free-build`'s nine-page walk reaching the 30-second timeout on its last page, which already showed the upgrade card; run alone, both `free-build` tests pass (29.9 s). So premium is on in the Playground through the option, the seams answer there, and the staged free build stays free with the option set.
- **Unit:** the unit bootstrap defines `WP_DEBUG` as false and constants cannot be undone in a process. `AiServiceTest` now answers the provider through the bootstrap's `wp_remote_request()` instead of the seam. `EmbeddingAccessTest` (whole class in separate processes) needs the vector seam: a class sets `KIMAAI_UNIT_TEST_SITE=1` in `setUpBeforeClass()`, the child processes inherit it, and only there the bootstrap defines `KIMAAI_E2E_TESTING` and `WP_DEBUG` true. The premium checks run in `e2e-premium-probe.php`, a process of its own, as before.

### Renames and removals

- `kimaai_assistant_history_model`, `_history_context`, `_persisted_renderables`, `_hydrated_renderables` are `kimaai_chat_*`; each old name runs right after the new one through `apply_filters_deprecated(..., 'next', <new name>)`, with what the new one returned. KimaAI's own listener (`AdminAssistant`) hooks the new name, so a site without old callbacks gets no notice.
- `kimaai_chatbot_theme` is called through `apply_filters_deprecated()` (replacement `kimaai_chatbot_theme_vars`; the arguments differ, so it is a deprecation, not an alias). `kimaai_stream_tool_call` too (replacement `kimaai_chatbot_tool_call`), still only when `kimaai_chatbot_tool_call` left the result `null`. `AdminAssistantSettingsTools` and `ToolRouter` answered both names with the same handler; they keep only `kimaai_chatbot_tool_call` (`ToolRouter::handleStreamToolCall()` is gone), so KimaAI itself never triggers the notice.
- `kimaai_chatbot_allowed` is removed. Its notice said 1.3.0, but the deprecation shipped in 1.3.5: 1.3.0 to 1.3.4 still apply it as the filter, and the CHANGELOG's 1.3.5 "Developer" section adds `kimaai_chatbot_gate` and deprecates it. 1.4 and 1.5 have shipped since, so the two minor releases of the rule are over. The release notes should name the removal.
- `kimaai_pdf_max_bytes` is `kimaai_embedding_pdf_max_bytes`, without an alias (unreleased).
- The dead `kimaai_chatbot_vector_search` listener is gone with `Embedding::registerHooks()` and its `registerIntegration` call. Its test is removed rather than moved: `ToolRouterTest::testKnowledgeSearchOnlyFindsWhatTheVisitorMaySee` and `testAFilterCannotWidenTheAccessScope` already make the same assertions on the retrieval path in use.
- The unit bootstrap's `apply_filters_deprecated()` and `do_action_deprecated()` now behave as WordPress's (they run, and give the notice, only with a callback) and record the notices; `ChatHookRenamesTest`, `ChatbotAssetsTest` and `ToolCallOrchestratorTest` check that the old names still work and give their notice, and that the new names give none.

### Tags and `since`

- Every PHP call site has `@kimaai-hook` or `@internal`; the first call site in file order of each of the 72 public hooks has `@since` and `@see`. Existing descriptions and `@param` lists stay; the area items complete the docblocks with their pages. Where a call had no docblock, it got a one-line summary. A filter docblock in `ChatbotToolRegistry.php` stood above the statement before the call, so the check could not see it; it moved to the call.
- `since` was confirmed per public hook on the call, not a listener: for each release tag in order, the PHP files (without `tests/` and vendors) that contain the name are searched for a call, multi-line calls included (`apply_filters(` or `do_action(` and their `_deprecated` and `_ref_array` forms, then the name; for the two built names also `$hook_prefix . '<suffix>'`). `git log -S` alone did not work: the release tags are not on `development`'s history, so `git tag --contains` finds no tag for most commits. All 70 PHP hooks match the "First tag" column. The one correction: `kimaai_admin_assistant_instructions` said `@since 1.8.2` and is `1.5.0`. The two JS hooks, `n/a` in the inventory, are `kimaai.admin.fieldComponents` 1.3.8 and `kimaai_trigger_button_click` 1.2.2. Unreleased, so `next`: `kimaai_chatbot_csat_saved`, `kimaai_trusted_proxies`, `kimaai_embedding_index_changed`, `kimaai_embedding_pdf_max_bytes` and the seven lead and access hooks.
- The first call site of `kimaai_tool_call_allowed` in file order is `CustomerTools.php`, so its full docblock is there; HK-10 moves the call into `ToolCallOrchestrator`.
- **ESLint** rejected the tags in JSDoc (`jsdoc/check-tag-names` for `@kimaai-hook`, `jsdoc/empty-tags` and `jsdoc/valid-types` for `@internal <name>`). `.eslintrc.js` now defines `kimaai-hook`, lets `@internal` carry text and turns `jsdoc/empty-tags` off (it cannot exempt one tag).
- **`kimaai:fieldComponentsChanged`** is tagged `@internal` with the other seven events, as HK-3 listed them. "Browser events" above calls it the one exception the field-components guide mentions; if HK-9's guide documents it, it needs a page and a test there.

## HK-5 (build notes)

Built 2026-11-16 on `track/HK-hooks`: 29 pages (the 28 public Chatbot hooks and the browser event `kimaai:chatbot`), a test per page that runs its example, the Chatbot area out of `PENDING`. The check reads `Hook pages: 128 hooks, 29 pages, 44 pending, 0 untagged; 0 problems`: one hook more than after HK-4, the new event.

### Behaviour changes

| Hook                              | Now                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_chatbot_after_response`   | Fires on the streaming path too, in `ChatbotStreamingRequestRunner::consumeStream()`, with the arguments of the other path: the saved answer (`saveChatResponse()`'s return, the same as `AiService::run()` returns) with `sessionId`, then `ai_payload`, `payload` and `chatbot_settings` of the prepared request. It runs after the `done` event went out and before `[DONE]` (and the process's `exit`), so the visitor is not kept waiting: the widget finishes on `done`                                 |
| `kimaai_chatbot_error`            | Fires on the streaming path too, from `emitNormalizedError()` (every error the stream emits) and from the catch around the environment's resolution in `handle()`, with the same three arguments. `$code` is `ai_exception` when a Throwable was caught (as on the other path) and the new `ai_stream_error` for an error the provider reported in the stream, a stream that ended without an answer and a provider that cannot stream; `$context['exception']` is null then. The context's keys are the same |
| `kimaai_chatbot_response_payload` | Unchanged, without streams; its page says so and points to `kimaai_chatbot_final_message` for both paths                                                                                                                                                                                                                                                                                                                                                                                                      |
| `kimaai_chatbot_handoff`          | A fourth argument, `array $ticket` with `channel`, `reference` and `url` of the `TicketRef` in `finalize()`. Callbacks with three parameters keep working. `url` is empty with the four helpdesk adapters KimaAI ships (none sets it)                                                                                                                                                                                                                                                                         |
| `kimaai:chatbot` (new)            | `src/chatbot/core/utils/chatbotEvent.js`, see below                                                                                                                                                                                                                                                                                                                                                                                                                                                           |

Two changes in the streaming runner serve these: the client is created in a new `protected createClient(array $env)` (the test's runner overrides it with a fake HTTP client, so the stream runs end to end in a unit test), and the branch for a client that cannot stream goes through `emitNormalizedError()`, which emits exactly what the branch emitted by hand, so it fires the action too.

### The browser event

- **Where it is sent.** On the chat root, the shadow host (`#kimaai-chatbot`, `[data-kimaai-chatbot]`), with `bubbles` and `composed`. The research said "on `window`"; an event dispatched on `window` never reaches a listener on `document`, which is where Google Tag Manager setups usually listen. From the host it reaches both, `event.target` tells which chat it was, and `composed` keeps it crossing the shadow boundary should a later change dispatch from inside. Without a host (the admin assistant, Storybook) nothing is sent.
- **The moments.** `open` and `close` only for the floating chat (`config.mount === 'floating'`), from an effect in `useChatbotController`, which the window mounts on opening and unmounts on closing. `message` when `sendMessage()` adds the visitor's message, `answer` when an answer arrived on either path (not on an error or a stop), `feedback` when `ChatMessageFeedback` or `ChatCsatModal` stored a rating, `lead` when `LeadForm` was sent. A first version sent `open` once the history had loaded, so that it carried the session; the e2e run showed that in a slow site a visitor sends before that, which put `message` before `open`. `open` now goes out when the window opens, with the session the chat root remembers from an earlier opening in the page view.
- **The detail.** `type` and `sessionId` always, `rating` and `kind` for `feedback`. `kind` (`message` or `csat`) is not in the research: without it a rating of 1 is either a thumbs-up or one star. The session comes from a `WeakMap` per chat root that `useConversationController` keeps up to date; the rating components pass their own `sessionId`. It is empty while the chat does not know it yet: the first `open` of a page view, and a new visitor's first `message`.
- **Where else it fires.** The search answer box sends `feedback` (it uses `ChatMessageFeedback`). The chat preview in the settings (`PreviewWidgetRoot`) renders in a shadow root with a host too, so a chat there sends the events on the admin page; the page says so rather than adding a check for the preview.
- **The page's example** is plain ES5 (`function`, string concatenation), so it also runs in a Google Tag Manager Custom HTML tag.

### Where the build differs from the plan

- **Test classes by code path, not one per hook.** `tests/unit/Hooks/Chatbot/` has `RequestHooksTest` (7 hooks), `ResponseHooksTest` (3, both paths), `AnswerHooksTest` (6) and `WidgetHooksTest` (4): one fixture per code path instead of copies in 20 classes. Hooks whose code path needs a large fixture got their test in the class that has it: the two rating hooks in `ChatbotFeedbackTest`, the four retention hooks in `ChatbotSessionRetentionTest`, the handoff in `HumanHandoffTest`, the proxies in `SecurityTest`. Each test is named after its hook and calls `HookPage::example('<name>')`; each fails without the example (checked by running the classes with the example calls removed).
- **`kimaai_chatbot_should_load` and `kimaai_chatbot_theme_vars` are unit tests**, not WP-CLI tests: `ChatbotAssets` builds both without WordPress, and a unit test runs in every `npm run check` instead of only on the AI box. `is_page()` is defined for the test as `ChatbotContentAwarenessTest` defines `is_singular()`.
- **Docblocks.** The area items were to complete the docblocks: every public Chatbot hook now has its `@param` list and, for filters, `@return`; the page's parameters are the docblock's. PHPStan reads these docblocks (its WordPress extension checks hook docblocks against the call), so `ChatbotContentAwareness.php` imports `WP_Post` for `@param WP_Post $post`. The two docblocks above `kimaai_chatbot_final_message` (one stale, above another statement) are one now.
- **Typing in a shadow root in Jest.** user-event types into `document.activeElement`, which is the shadow host there, so the event's Jest test fills the fields with `fireEvent.change` and sends with the Send button.

### Found while writing the pages (not changed)

- A quick action whose callback answers without the provider (`ToolCommandHandler::handleCallback()`) saves a response it builds: `kimaai_chatbot_final_message` and `kimaai_chat_response_saved` fire for it (provider `openai`, no `usage`), `kimaai_chatbot_response_payload` and `kimaai_chatbot_after_response` do not. The pages say so.
- `kimaai_chatbot_quick_actions` runs in `GET /chatbot/history`, a REST request without a current post, so `postId` (`get_the_ID()`) is 0 there. The page says so; passing the widget's post ID would be a change of its own.
- The retention context's `cutoffTimestamp` is a date and time string (`Y-m-d H:i:s`, site time zone), not a Unix timestamp as the name suggests. The pages describe it as it is.
- The guardrails and the groundedness check read the chatbot settings in `$payload['chatbot_settings']`; the admin assistant's settings have neither switch, so their pages list the chatbot and the search answer as surfaces.

### Tests and runs

- `npm run check` before each commit: exit 0 (at the end PHPUnit unit 1512 tests, 1 skipped).
- The examples of the 28 PHP pages run in 30 test methods: 22 in `tests/unit/Hooks/Chatbot/` (4 classes) and 8 in `ChatbotFeedbackTest`, `ChatbotSessionRetentionTest`, `HumanHandoffTest` and `SecurityTest`; `kimaai_chatbot_after_response` and `kimaai_chatbot_error` run on both paths, and one more test in `ResponseHooksTest` checks the error codes of the stream (an error frame, a thrown error). The event's Jest suite (`tests/js/hooks/chatbotEvent.test.jsx`) has 5 tests: the dispatch, no host, the page's example, the floating chat mounted in a real shadow root (open, message, answer, feedback, close, open again) and the CSAT sheet with the lead form.
- E2E on the Mac, JS built with `npx wp-scripts build`, 2 workers: `chatbot-shadow-root` (with a new test: the event in the real widget, on `document` and `window`, its target the chat root, no visitor text), `chatbot-streaming`, `chatbot-handoff`, `chatbot-request`, `chatbot-feedback`, `chatbot-lead-capture`, `chatbot-widget`, `chatbot-search-answer`, `chatbot-ask-ai`, `chatbot-mounts`: 32 passed, 1 skipped (the `@slow` test with a real provider). The first run failed the new test as described under "The moments"; the fix passed it. The e2e streaming specs fake the stream in the browser, so the server's streaming path is covered by the unit tests only.

## HK-6 (build notes)

Built 2026-11-16 on `track/HK-hooks`: 17 pages, the public hooks of Embedding and search, a test per page that runs its example, the area out of `PENDING`. The check reads `Hook pages: 128 hooks, 46 pages, 27 pending, 0 untagged; 0 problems`.

### Behaviour changes

None. The code changes are the docblocks: every public hook of the area has its `@param` list and, for filters, `@return`, and `Embedding.php` imports `WP_Post` for PHPStan, as `ChatbotContentAwareness.php` did in HK-5. What the pages found and the item did not change is listed below.

### Where the build differs from the plan

- **Test classes by code path**, as in HK-5. `tests/unit/Hooks/Embedding/` has `ContentHooksTest` (render mode, shortcode blocklist, extra text, skip block names, class sets, each through `ContentProcessor::cleanPost()`), `SourceHooksTest` (supported sources, fetch query args, source title, through `SourceHelper`) and `IndexHooksTest` (chunk text, vector metadata, index changed, through `Embedding::sync()` with the AI provider and the vector database faked). The two PDF hooks are in `PdfTextExtractorTest`, the meta filter in `ToolRouterTest`, the keyword query args in `WpCoreProviderTest`, the providers in `KeywordSearchManagerTest`, the eval regression in `EvalSchedulerTest`: those classes have the fixtures.
- **Two classes run in separate processes.** `cleanPost()` renders through `the_content` with `setup_postdata()`, and the fallback extractor needs `parse_blocks()` and `render_block()`; the unit bootstrap has none of them, and a global `wp_reset_postdata()` would collide with the WooCommerce fixture, which declares it without a guard. `EmbeddingHookStubs.php` declares them and is required in `setUp()`, so only the child processes see it. `IndexHooksTest` needs the vector seam, so it sets `KIMAAI_UNIT_TEST_SITE` as `EmbeddingAccessTest` does. Neither keeps a mock in a property: PHPUnit sends a failing test's object back to the main process, which cannot rebuild a mock, and the failure then shows as `__PHP_Incomplete_Class` instead of the assertion.
- **The PDF size test** writes a copy of `fixtures/text.pdf` padded past 20 MB to the temporary directory; the parser reads it in about 0.01 s. The OCR test copies `image-only.pdf` there with a `.txt` file next to it.
- **The skip block names example** runs in the only place the filter applies, the fallback extractor (below), with blocks that render no text in `the_content`.

### Found while writing the pages (not changed, for the owner)

- **`kimaai_embedding_skip_block_names` applies only in the fallback extractor**, which runs when a post's rendered content gives fewer than 40 characters of text (`ContentProcessor::blocksToText()`). Most posts are indexed from the rendered content, where the filter changes nothing, so the research's reason ("Keep a block's output out of the index") does not hold. A fix would skip the listed blocks while rendering too (a `pre_render_block` callback during `renderForEmbedding()`), but the default `gravityforms/form` would then take the form titles and descriptions that stand outside the `<form>` out of the index on sites with Gravity Forms blocks: a change to what sites index, so not made here. The page says where the filter applies and points to the class sets and the shortcode blocklist. Owner: that fix, or the hook internal.
- **`kimaai_embedding_index_changed` fires once per stored chunk**, after each confirmed upsert batch (`Embedding::markUpserted()`), not once per sync, and **not on removals**: stale chunks pruned, vectors deleted in the admin (`RestApi::deleteVectors()`), a deleted collection. Its own listener, the search answer cache, also bumps on `save_post` and `deleted_post`, but vectors deleted in the admin leave cached search answers until the next bump. Firing it on deletions would change when cached answers are served; not made here. The page says when it fires and shows a callback that runs once per request.
- **`kimaai_kb_search_meta_filter` and hybrid search.** The keyword search gets the same filter but applies only `post_type`, `lang` and the `tax_` fields (`KeywordSearchManager::enforceScope()` and the engines), so an own field does not narrow the keyword hits. The page says so and points to `kimaai_keyword_search_query_args`. Also: `MetaFilter::translate()` writes the Pinecone syntax (the default for every provider but Qdrant) with one `$or` key, so two fields with `or_missing` overwrite each other; the access clause, which comes last, wins over a callback's own `or_missing` field. Results stay safe (every hit passes `canView()`), but the callback's field is lost. The page documents plain values and lists only.
- **`kimaai_keyword_search_query_args` does not fire for SearchWP**, which builds its own `SWP_Query` arguments. The page says so.
- **Stored data that a sync does not refresh.** The vector metadata is not part of the hash that tells a chunk changed, and a chunk under a heading does not contain the post's title, so a new `kimaai_embedding_vector_metadata` callback or a changed `kimaai_embedding_source_title` reaches those chunks only with a forced sync. The pages say so.
- **`kimaai_embedding_supported_sources` also gates the purge**: `PostEmbedSync` removes a post's chunks on unpublish or delete only for a source type, so removing a source leaves its indexed chunks behind for good. A sync without a post type (`'post_type' => 'any'`) does not ask the sources at all. The page says both and points to `kimaai_content_access_tokens`.
- **`kimaai_embedding_fetch_query_args`** leaves a post out of a sync, not out of the index: its chunks from an earlier sync stay. The page says so.
- **`kimaai_keyword_search_providers`** is applied once, when the integrations load on `init`; the "Keyword search engine" setting lists only the engines KimaAI ships, so an own engine runs through Automatic, first in the list. The page says so.
- **`kimaai_embedding_remove_node_class_sets`**: when the sets remove every text element, `htmlToTextPreserveStructure()` falls back to the text of the whole HTML, removed boxes included. An edge case, not on the page.

### Tests and runs

- `npm run check` before each commit: exit 0 (PHPUnit unit 1529 tests, 1 skipped).
- The 17 examples run in 17 test methods: 11 in `tests/unit/Hooks/Embedding/` (3 classes) and 6 in `PdfTextExtractorTest`, `ToolRouterTest`, `WpCoreProviderTest`, `KeywordSearchManagerTest` and `EvalSchedulerTest`. Each fails without its example (checked per class with the example calls commented out).
- No e2e or WP-CLI runs: nothing in the item touches the browser or needs WordPress to boot. No provider and no vector database were called; the tests fake both.

## HK-7 (build notes)

Built 2026-11-16 on `track/HK-hooks`: 8 pages, the 7 public hooks of Leads and customer centre and the new `kimaai_lead_validate`, a test per page that runs its example, the area out of `PENDING`. The check reads `Hook pages: 129 hooks, 54 pages, 20 pending, 0 untagged; 0 problems`: one hook more than after HK-6, the new filter. Before HK-7, a follow-up of HK-6 (`c2a66d07`).

### The HK-6 follow-up: `kimaai_embedding_index_changed` on removals

HK-6 found that the action fired only for stored chunks, so the search answer cache could serve answers from deleted content (decision: it fires on removals too). Every removal of vectors goes through two methods of `Embedding`: `delete()` (stale chunks pruned in a sync or the access backfill, a post's chunks purged on unpublish, delete, exclusion from the knowledge base or the reconcile, vectors deleted in the admin through `RestApi::deleteVectors()`, the WP-CLI deletes) and `deleteCollection()` (the admin route and WP-CLI). Both now fire the action when the vector database confirmed (`ok` in the envelope); a refused delete fires nothing. So it fires once per confirmed delete, not per chunk: a listener such as the cache, which bumps once per request, stays correct, and the arguments stay none, as before, because the action says that the index changed, not what changed. Stored chunks still fire it once each. The full docblock moved to the first call site in file order (`delete()`); the page lists the three cases. Tests in `IndexHooksTest`: prune, unpublish and delete of a post, vectors deleted in the admin, a deleted collection, each failing without the fix, and a refused delete that fires nothing. KimaAI deletes its own rows of the chunks right after the action, not before it.

### Behaviour changes

| Hook                             | Now                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_embedding_index_changed` | Fires on confirmed removals too (above)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `kimaai_lead_validate` (new)     | In `LeadForm::saveLead()`, after the consent version check and the building of the lead, right before `save()`. Only `true` stores the lead. A `WP_Error` refuses it with its message and status 400, which the widget shows under the form (`wpLeadApi.js` reads `error`). Any other answer, and a `WP_Error` without a message, refuses it with a general message, as `kimaai_chatbot_gate` blocks on anything but `true`. A refusal stores nothing, does not count towards the five leads per IP and day and fires no `kimaai_lead_saved`. "Not now", the honeypot and the meeting report never reach the filter |

The other seven hooks are unchanged; their code changes are the `@return` tags of the four filters.

### Decisions (the research left them open)

- **Anything but `true` refuses.** The research typed the filter `true|WP_Error`. A callback that answers `false` means to refuse, and the chatbot's gate already works that way, so the filter does the same rather than storing the lead. The general message is a new string, `Your details could not be accepted. Please check them and try again.`, with the text domain `kimaai`; `languages/kimaai.pot` is not regenerated, as asked.
- **Where it runs.** After the lead array is built, so the callback sees the lead as it would be stored, consent text included, and cannot change it (the filter returns only the decision).
- **No browser change.** The widget already shows the route's `error`, so no Playwright run was needed.

### Where the build differs from the plan

- **Tests in the classes that have the fixtures**, not in `tests/unit/Hooks/Leads/`: every hook of the area has a class with its code path already, as the rating and retention hooks had in HK-5. `LeadFormTest` (lead saved, the three tests of lead validate), `MeetingBookingTest` (lead event, through the booking report of the lead route), `LeadPrivacyTest` (lead erased, through the eraser), `LeadsAdminTest` (leads capability), `LeadScorerTest` (free mail domains, which gets a `tearDown()`), `AccessResolverTest` (content and user tokens).
- **`kimaai_leads_capability` is a unit test**, not the WP-CLI test the research planned: the capability decides `LeadsAdmin::canManage()`, which the routes and the export use, and a unit test runs in every `npm run check`. That a user with the capability but without `manage_options` sees the Leads page under the KimaAI menu (WordPress shows a parent menu through its first accessible submenu) and that the Leads app works for them has not been run in a real WordPress.
- **Examples without personal data leaving the site.** The main use of `kimaai_lead_saved` in the research is a CRM KimaAI does not support; the example counts leads per page and trigger instead, and the page points to the Lead webhook (Pro) for other CRMs. The examples of the lead event and erased pages store counts or own notes in options.

### Found while writing the pages (not changed, for the owner)

- **`kimaai_lead_erased` fires only for the privacy eraser** (Tools > Erase Personal Data). A lead deleted on the Leads page (`LeadsAdmin::deleteLead()`) or by the "Keep leads" period (`LeadRetention::runCleanup()`) fires nothing, so the lead webhook gets no `lead.erased` event then and Insights keeps the lead's conversions. Firing it there would change what webhook receivers get; not made. The page says when it fires.
- **`kimaai_lead_event` reports a booking from the browser.** The booking calendar posts `meeting_booked` to the public lead route; the provider does not confirm it. A visitor who holds the session can report a booking that did not happen, once per lead, which adds 30 points to the score and a meeting conversion. The page says the report comes from the browser.
- **`$lead` in `kimaai_lead_saved` is the array built for `save()`**, not the stored row: `marketing_opt_in` is a boolean there (0 or 1 in the table), and `id`, `fields`, `score` and the dates the model adds are missing. The page lists the keys as they are.
- **`kimaai_lead_free_mail_domains`** cannot remove the six providers matched by their first label (gmx, hotmail, live, outlook, yahoo, yandex: `LeadScorer::FREE_MAIL_PROVIDERS`). The page says so.
- **The access hooks' feature.** Both run in free code (`app/Access/`), for the content awareness and the search answer too, but carry the feature `members-only-knowledge`, which is premium in the registry, as the inventory set it. The index shows them as free with that feature; if the feature were hidden, the website sync would hide the two pages although the filters work on every site.

### Tests and runs

- `npm run check` before each commit: exit 0. At the end: PHPUnit unit 1544 tests, 1 skipped (1529 after HK-6, plus 5 for the follow-up, 7 page tests and 3 for the new filter); Jest 1190 tests in 152 suites.
- Each of the 8 examples fails its test when removed (checked per test with the example call removed), the four removal tests of the follow-up (the fifth, a refused delete, passes either way) and the three tests of `kimaai_lead_validate` fail on the code before them.
- No e2e or WP-CLI runs: nothing in the item changes the browser, and no provider, vector database, CRM, webhook or mail service was called; the tests fake them.

## HK-8 (build notes)

Built 2026-11-16 on `track/HK-hooks`: 7 pages, the public hooks of the Admin assistant, a test per page that runs its example, the area out of `PENDING`. The check reads `Hook pages: 129 hooks, 61 pages, 13 pending, 0 untagged; 0 problems`. Before HK-8, a follow-up of HK-7 (`7c99391c`): `kimaai_content_access_tokens` and `kimaai_user_access_tokens` carry the feature `none` instead of `members-only-knowledge`. Both filters run in free code on every site (the content awareness, the search answer, and in Pro the knowledge search and the sync), so the access model belongs to no single feature, and a hidden premium feature must not hide their pages on kimaai.com; `index.json` shows them with `featureStatus` `null`.

### Behaviour changes

None. The code changes are the docblocks: the seven hooks have their `@param` list and, for filters, `@return`. The `$post_id` of `kimaai_admin_assistant_instructions` said "the current post ID"; it is the request's `postId`, which the admin assistant sets to 0, so the docblock and the page say that.

### Renames and surfaces

- **No renamed hook among the seven.** The four `kimaai_assistant_*` filters renamed in HK-4 are internal (history and renderables), so they get no page; `ChatHookRenamesTest` already checks that callbacks on the old names still run and give their notice.
- **No shared hook among the seven.** They fire only in an admin assistant request (`AdminAssistantRequestPreparer`, and `Helper::buildMessageTree()` for the admin assistant surface), so each page lists `surfaces: [admin_assistant]`. The hooks the admin assistant shares with the chatbot (`kimaai_chatbot_response_payload`, `_after_response`, `_error`, `_final_message`, `kimaai_chat_response_saved`) already list `admin_assistant` since HK-5; the pages of the AI payload and before request link to them.

### Where the build differs from the plan

- **Tests by code path.** `tests/unit/Hooks/AdminAssistant/RequestHooksTest.php` runs the six hooks of the request preparer on a prepared request (the history faked through `$wpdb`, as `AdminAssistantRequestPreparerTest` does). The instructions test is in `AiServiceInstructionResolutionTest`, which has the fixture for `AiService::resolveChatPayload()`. Each test calls `HookPage::example('<name>')` and fails without it (checked with the example calls commented out: 7 of 7 fail).
- **The rate limit test sets a limit through the internal `kimaai_admin_assistant_config` filter**, because nothing else can (below).

### Found while writing the pages (not changed, for the owner)

- **The admin assistant's panel is off by default.** `app/Admin/config/global.php` has `adminAssistant.enabled` false since `ef8bf9d8` ("chore: disable admin assistant (#359)"), so 1.5.0 to 1.5.13 shipped with it off; only the internal `kimaai_settings_ui_config` filter turns it on (the e2e helper `installAdminAssistantE2ERuntimeHook()` does). The REST route stays registered for users with `manage_options`. The feature registry lists `admin-assistant` as stable, so the website sync would publish seven pages for an assistant sites do not see. Each page says the panel is off by default in this release. Owner: turn the panel on, hide the feature (the sync then hides the pages; what else hiding it changes would need checking), or keep it as it is.
- **`kimaai_admin_assistant_rate_limited` does not fire out of the box.** The assistant's configuration sets `maxMessages` to 0 and no setting offers a limit; only the internal configuration filter sets one. The page says so. Owner: a setting or a public limit filter, or the hook internal.
- **The instructions get no placeholders filled** (`InstructionComposer` runs only for the chatbot), and **an OpenAI session that continues sends only the new message** with `previousResponseId`, so the filtered instructions of later turns do not reach the provider; the first turn's stay in force. The page says both.
- **No masking and no built-in gate.** The admin assistant masks no card numbers or IBANs, and the banned words and IP addresses of the chatbot settings do not apply to it. The pages say so.
- **A `WP_Error` without a message from the gate** refuses the request with an empty error text, in the admin assistant as in the chatbot; `kimaai_lead_validate` uses a general message then (HK-7). Not changed.

### Tests and runs

- `npm run check` before each commit: exit 0. At the end: PHPUnit unit 1551 tests, 1 skipped (1544 after HK-7, plus the 7 page tests); Jest 1190 tests in 152 suites.
- No e2e or WP-CLI runs: nothing in the item changes the browser or needs WordPress to boot, and no provider was called; the tests stop before the request runs or build the messages without sending them.

## HK-9 (build notes)

Built 2026-11-16 on `track/HK-hooks`: 4 pages, the public hooks of Settings and admin (two PHP, two JS), the field key in `kimaai_trigger_button_click`, the field-components guide, a test per page and for the guide that runs its example, the area out of `PENDING`. The check reads `Hook pages: 129 hooks, 65 pages, 9 pending, 0 untagged; 0 problems`.

### Behaviour changes

| Hook                          | Now                                                                                                                                                                                                                                                                                                                                                                                          |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_trigger_button_click` | The second argument is `{text, variant, key}`: `key` is the button's field key, the `id` prop that `FieldRenderer` (a settings page) and `ConnectionPanel` give every field component. Callbacks that read `text` and `variant` work as before. In a list's entry form (`RepeatableEntryForm`, which passes no `id`) `key` is undefined; the page says so. No KimaAI setting uses the button |

The other three hooks are unchanged; their code changes are the docblocks (`@param` and `@return`).

### `kimaai:fieldComponentsChanged` stays internal

The guide does not need it. An add-on's script loaded on the settings page runs before the settings app draws its first page (`domReady`, after the page's scripts), so a filter added there is in place without any event, and the guide's Playwright run below shows it. `registerFieldComponent()` sends the event itself, for a component registered after the app has drawn; the add-on neither sends nor listens to it. Made public, it would fix how the app redraws as an API. The guide names `window.kimaaiAdmin.registerFieldComponent()` in one sentence, for a script that can only run late, and not the event; `FieldRenderer.test.jsx` already checks that a late registration draws the page again.

### Decisions

- **Where the guide lives.** The research names no place. `docs/guides/field-components.md`: the roadmap's UD track puts guides in `docs/guides/<guide>.md`, and outside `docs/hooks/` the check does not take it for a hook page (it walks `docs/hooks/` with its subfolders). Its format follows the pages where it can: a frontmatter (`summary`, `area`, `hooks`; no `title`, which the Markdown lint counts as a second top-level heading, MD025), the title as `# ...`, the Markdown the website converts, and its example first under `## Example`, so `hookPage.run()` runs it. `index.json` lists only hook pages; how the website syncs guides is for HK-12. The guide's path is in the test map's "Hook pages" rule.
- **Examples as plain scripts.** The JS examples use `wp.hooks`, `wp.element` and `wp.apiFetch`, so they run without a build step. The admin bundle takes `@wordpress/hooks` from WordPress (`wp-hooks` in `build/admin/index.asset.php`), so an add-on's `wp.hooks` is the instance KimaAI applies. The tests set `window.wp` from the same modules the code under test imports.
- **The key, not the path.** `key` is the field's key, as the research plans. The settings path (`basePath`) would be unique across add-ons; the page asks for keys with the add-on's name instead.
- **`JS_HOOK_TESTS`** (test map) lists the JS hook tests: `settingsFields.test.jsx` and HK-5's `chatbotEvent.test.jsx`, which was not in it, so a change to `docs/hooks/kimaai-chatbot.md` selected no Jest test in `check:related`.
- **Tests by code path.** `tests/js/hooks/settingsFields.test.jsx` builds an add-on's page from its schema with `buildMenu()` and draws it with `FieldRenderer`, as `useSettingsRoute` does: the button's key and the page's example, the field components example (typed key by key, so it also shows the component keeps the focus), the guide's example as a setting row with KimaAI's label and description. `kimaai_settings_schema_files` is a unit test in `SettingsSchemaFilesTest`, not the WP-CLI test the research planned: `getSchema()` runs without WordPress, and a unit test runs in every `npm run check`. It writes the page's second `php` block, the add-on's settings file, next to the example's temporary file, so the file shown on the page is tested too; a second test does the same with the guide's settings file and checks it names the component the guide's script adds. The MCP example is in `McpModuleTest`.

### Found while writing the pages (not changed, for the owner)

- **An add-on's settings are deleted when it is deactivated.** `Settings::register()` runs `maybeUpgradeOnSchemaChange(..., true)` on `init`: when the schema changed, `kimaai_options` keeps only the keys the schema has. Deactivate an add-on and its group leaves the schema, so its values are gone on the next request and the defaults come back with it. Checked in the Playground (below). The page says so. Keeping groups the schema does not know would change what sites store; not made. Owner: keep it, or keep unknown groups (or offer add-ons their own option, the existing `save_key`, which no file uses and this item did not test).
- **A file named like a KimaAI group** (`chatbot.php`) defines that group a second time; the sort by `order` decides which definition is used, and the other is lost. Its secrets stay marked (HK-4). The page warns.
- **The groundedness log holds visitors' questions.** `kimaai_mcp_log_retention_days` also prunes `kimaai_mcp_groundedness`, which stores the chatbot's ungrounded answers with the visitor's question, also on sites that never use the MCP server; 90 days, no setting. The page says so.
- **`event` is React's event.** `kimaai_trigger_button_click` gets React's click event (with `nativeEvent`), typed `Event` in the docblock; the page describes it.

### Tests and runs

- `npm run check` before each commit: exit 0. At the end: PHPUnit unit 1554 tests, 1 skipped (1551 after HK-8, plus 3); Jest 1194 tests in 153 suites (1190 in 152, plus the new suite's 4).
- Each example fails its test when removed (checked per test with the call commented out), and both tests of the button fail without the key.
- E2E on the Mac, JS built with `npx wp-scripts build` in the worktree, 2 workers: `admin-settings` and `white-label` (an add-on's schema file through `kimaai_settings_schema_files` in the real admin): 11 passed. A one-off Playwright spec, not committed, installed the guide's PHP and JS blocks as an mu-plugin in the Playground, with a `TriggerButton` field added: the page shows in the menu, the greeting is a setting row with its label, counts as it is typed, the button passes `{text, variant, key}`, Save stores `myAddon.general.greeting`, a reload shows it, and with the mu-plugin removed the value is gone after the next request. Passed.
- Not run: the WP-CLI suite (AI box only); nothing in the item needs it. No provider and no external service was called.

## HK-10 (build notes)

Built 2026-11-16 on `track/HK-hooks`: 9 pages, the public hooks of Tools and addons, `kimaai_tool_call_allowed` for every tool call, `kimaai_chatbot_max_tool_rounds` on the streaming path, the guides for add-ons and custom tools, a test per page and per guide that runs its example. `PENDING` is empty. The check reads `Hook pages: 130 hooks, 74 pages, 0 pending, 0 untagged; 0 problems`: one hook more than after HK-9, the internal `kimaai_tool_call_blocked`.

### Behaviour changes

| Hook                             | Now                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kimaai_tool_call_allowed`       | Applied once in `ToolCallOrchestrator::executeTool()`, after the check that the request offered the tool and before `kimaai_chatbot_tool_call`, so every tool call passes it on both paths and every surface: the contact form tool, the admin assistant's settings tools, the handoff, the meeting booking, the customer tools, the knowledge search, the custom functions and the integrations' tools. Same arguments (`$allow`, `$name`, `$args`) and contract: only `true` runs the tool, a string blocks with `{"error": <string>}`, anything else with "Tool call blocked". A blocked call keeps the trace status `success` with the error as its result, as a block in the tool router had, so a streamed chat shows no failure. `ToolRouter::handleToolCall()` runs the tool without asking again (the new private `run()`); `ToolRouter::call()` still asks, for its one caller outside the tool loop, the MCP tool `inspect_retrieval`. `CustomerTools` no longer asks; it writes its `blocked` audit row, with the session, from the new internal action `kimaai_tool_call_blocked` (`$name`, `$args`, `$payload`), which the orchestrator fires for a blocked call. `LeadTriggers` and `MeetingBooking` add the form or the calendar only for a call whose result is not an error, so a blocked call shows neither. The tier is free now (the call is in `app/`) |
| `kimaai_chatbot_max_tool_rounds` | Applied on the streaming path too (`ChatbotStreamingRequestRunner::consumeStream()`), which had a fixed 6, with the same provider payload. The chatbot streams by default, so the filter did nothing for most answers. Without a callback nothing changes. On that path a round is one request to the provider, and values below 1 count as 1, so a streamed answer is never empty because of the filter                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

The other seven hooks are unchanged; their code changes are the docblocks.

### Decisions

- **Why an internal action for the audit.** The research keeps `CustomerTools`' own audit row. The filter passes no payload, so a callback on it cannot know the session, and a row without a session is never deleted by the conversation retention (`ChatbotSessionRetention` deletes audit rows by session). A fourth argument to the public filter would change its arguments, which this item was to keep; so the orchestrator fires `kimaai_tool_call_blocked`, `@internal`, and `CustomerTools::auditBlocked()` writes the row as before.
- **The trace of a blocked call stays `success`.** Marking it `error` would show "`<tool> failed.`" in a streamed chat, which a block in the tool router did not; the visitor sees what the model writes from the message. The two features that read the trace for their widgets check the result instead.
- **The add-on hooks are unit tests**, not the WP-CLI tests the research planned: `AddonHooksTest` runs `KimaAI::pluginsLoaded()` in a process of its own, with a container that holds the add-on manager and the settings the logger reads, so they run in every `npm run check`. The add-on guide's test installs its two files as a plugin in a temporary folder and runs its command with a stand-in for `WP_CLI`.
- **The deprecated `kimaai_stream_tool_call`** has its own page, as `kimaai_chatbot_theme` did in HK-5, with the replacement under "More examples". Its test runs the example on the free path and checks the notice; a second test shows that with Pro's tool router it gets no call.
- **`PENDING` stays as an empty list**, as `UNTAGGED` did after HK-4; the check needs no change for it. `CONTRIBUTING.md` says it is empty.
- **Guides** follow HK-9's format: `docs/guides/add-on.md` ("Build an add-on") and `docs/guides/custom-tool.md` ("A tool for the chatbot"), each with its example first under `## Example`, both in the test map's "Hook pages" rule. The custom tool guide explains the two registries, as "Naming" planned.
- **The features stay as the inventory set them** (`function-tools` for the tool hooks, `none` for the add-on hooks), although the contact form tool and the admin assistant's tools are free; see below.

### Found while writing the pages (not changed, for the owner)

- **A streamed answer ends after its last round without a final answer.** When the model still calls a tool in the last round, those tools run, but their results never reach the model and no text follows; the path that does not stream answers the pending calls with a budget notice and asks for a final answer without tools. Making the streamed path do the same would change what visitors see; not made. The page describes both.
- **`kimaai_stream_tool_call` never fires with Pro**: the tool router answers every tool on `kimaai_chatbot_tool_call` at priority 10, so the result is never `null` after it. So it was in 1.5.13 too. The page says so.
- **The tool hooks' feature.** The tool hooks run in free code, for the free contact form tool, and `kimaai_chatbot_tool_call`, `kimaai_tool_call_allowed` and `kimaai_chatbot_max_tool_rounds` also for the admin assistant's tools, but they carry the premium feature `function-tools`. If it were hidden, the website would hide their pages, as HK-7 found for the access hooks. Owner: keep `function-tools`, or `none` as for the access hooks.
- **In the free version the catalogue does not reach the chatbot.** `kimaai_tools_registry` tools are offered only through Pro's tool router, and the setting "Allowed custom functions" is Pro; a free add-on defines its tool with `kimaai_chatbot_tools_registry`. The pages and the guide say so.
- **`ToolRegistry::builtin()` applies `kimaai_tools_registry` on every read**, several times per request (each tool call's `sensitive` check among them). The page asks callbacks to only add definitions.
- **Buttons and quick actions are not tool calls.** The handoff button runs through `kimaai_chatbot_command_callbacks` and does not pass `kimaai_tool_call_allowed`. The page says so.
- **`ToolRouter::handleChatResponse()` is dead code**: no hook calls it since the orchestrator took the tool loop, and it has its own fixed 6 rounds. Not removed.
- **Admin assistant tools for add-ons** stay internal (`kimaai_admin_assistant_tools_registry`, research "Later"); `kimaai_chatbot_tool_call` and `kimaai_tool_call_allowed` fire for the admin assistant's own tools.

### Tests and runs

- `npm run check` before each commit: exit 0. At the end: PHPUnit unit 1576 tests, 1 skipped (1554 after HK-9, plus 22); Jest 1194 tests in 153 suites, unchanged.
- Tests by code path, as in HK-5 to HK-9. `tests/unit/Hooks/Tools/ToolHooksTest.php` (12 tests: the catalogue, the request's tools, the allowed tools, the tool call, the deprecated name with its notice and without calls under Pro, three of the allowed filter, the rounds on both paths, the custom tool guide) and `AddonHooksTest.php` (3, in separate processes: the two add-on hooks and the add-on guide). The handoff example of `kimaai_tool_call_allowed` is in `VisitorHandoffTest`, which has the fixture; the blocked and allowed contact form and calendar in `LeadTriggersTest` and `MeetingBookingTest`; the blocked customer tool with its audit row, an allowed one asked once, and no row for other tools in `CustomerToolsTest`, whose old test called the handler directly.
- Each example and guide fails its test when removed (checked with the calls replaced). On the code before the item (the six changed classes put back) 7 of the new tests fail: the handoff example, the admin assistant block, the general message with the audit action, the streamed rounds, the blocked and the allowed contact form (the filter was not asked) and the blocked calendar. The "asked once" test of a Pro router tool passes on both, as it should.
- E2E on the Mac, JS built with `npx wp-scripts build` in the worktree, 2 workers: `chatbot-lead-capture`, `chatbot-meeting-booking`, `chatbot-handoff`, `chatbot-customer-orders`, whose server path fakes the provider's tool calls: 10 passed.
- Not run: the WP-CLI suite (AI box only; nothing in the item needs it now that the add-on hooks are unit tests). No provider and no external service was called.

## HK-11 (build notes)

Built 2026-11-16 on `track/HK-hooks`: reference pages for the REST routes, the WP-CLI command and the MCP tools in `docs/reference/`, and their check. The research left the format and the check to this item; this is the proposal it was built on.

### The format

- **One page per group, not per entry.** REST: seven pages by area (`rest-chatbot.md`, `rest-leads.md`, `rest-conversations.md`, `rest-admin.md`, `rest-admin-assistant.md`, `rest-embeddings.md`, `rest-mcp.md`), one `wp-cli.md` with every subcommand, one `mcp-tools.md` with every tool.
- **Frontmatter for the website sync**, as close to the hook pages as the kind allows: `kind` (`rest`, `wp-cli`, `mcp`), `area` (one of the six hook areas), `tier` (premium when every entry is in `premium/`) and `summary`. No `title` (the Markdown lint counts it as a second top-level heading, as for the guides) and no `since`, which the code does not record per route; the title is the `# ` heading.
- **One `## ` section per entry**, its heading the entry's name: `## <METHOD> /kimaai/v1/<path>` (one per method, path parameters as `{name}`), `## wp kimaai <subcommand>`, `## <tool>`. Under it a list of facts in a fixed order (REST: `Access`, `Permission`, `Tier`, `Feature`; WP-CLI: `Tier`; MCP: `Scope`, `Tier`), then the prose: what it does, an argument table (`Argument`, `Type`, `Required`, `Description`), what it returns. A WP-CLI entry starts its prose with a `sh` block holding the synopsis.
- **Internal or public** per route, with one sentence at the top of each REST page on what internal means. Permissions are described by what they require; no secret, token or nonce value and no way around a permission.
- The body uses the Markdown the hook pages use, checked with the same function.

### The check

`npm run check` gets a step "Reference pages" after "Hook pages": `node scripts/check-reference.mjs`. A PHP inventory, `scripts/reference-inventory.php`, reads the code with the tokenizer as `scripts/hooks-inventory.php` does (and reuses its helpers), runs none of it, and prints what it can read reliably: per `register_rest_route()` call each method with its namespace and path (literals, class constants, a variable assigned in the file), whether the permission callback is `__return_true`, the declared arguments (name, type, required), the class and its feature in `Loader::FEATURE_CLASSES`; per class with a static `getNamespace()` its public methods as subcommands (`@subcommand` renames one) with the synopsis of the docblock's `## OPTIONS`; per class in `premium/app/Mcp/Tools/` that implements `ToolInterface` its `name()`, `requiredScope()`, the properties and required list of `inputSchema()`, and whether the `ToolRegistry` service lists it. The check fails, with file and line, when an entry in the code has no section or a section no entry, or when the method, path, tier, feature, "anyone", the declared arguments, a synopsis or a scope differ. A booted registry in a unit test was the alternative; the tokenizer needs no WordPress, no container and no mocks, and runs in a fraction of a second.

### What was built

- **Nine pages.** 79 REST entries from the 78 `register_rest_route()` calls in 20 files (`/admin-theme` registers GET and POST in one call), 29 WP-CLI subcommands and 16 MCP tools. The research's "one `WP_CLI::add_command()`" is the one call in `Loader::loadCommands()`; it registers the ten command classes of `premium/app/Cli/`, each under its own name (`wp kimaai`, `wp kimaai db`, `wp kimaai eval`, `wp kimaai gaps`, `wp kimaai mcp token`, `wp kimaai usage`, `wp kimaai vectors` with `collections`, `config` and `items`). Every command and every tool is Pro; 41 routes are free, 38 Pro.
- **The check** reads `Reference pages: 9 pages, 79 routes, 29 WP-CLI subcommands, 16 MCP tools; 0 problems` in about 0.2 seconds. Its Jest test (`tests/js/hooks/checkReference.test.js`, 7 tests) runs it on trees of its own, as the hook check's does.
- **Run on this tree with a change each, then reverted:** a new GET route and the test connection route's method changed to PUT gave `GET /kimaai/v1/brand-new has no entry`, `PUT /kimaai/v1/test-connection has no entry` and `POST /kimaai/v1/test-connection is not in the code`; the write tools' scope set to `read` and an argument's Required changed on the MCP page gave `Scope is "read", requiredScope() returns "write"` per tool and the Required mismatch.
- **Test map:** a rule "Reference pages" (`docs/reference/**`) before the text rule selects the check's Jest test; the two scripts joined the rule "Hook check", which now selects both checks' tests, because the reference check reuses the hook check's helpers.
- **The rule** is in `CONTRIBUTING.md` ("Hooks": the rule, and a section "Reference pages" with the format and the check), and in one sentence in `CLAUDE.md` and `AGENTS.md`, next to the hook rule HK-2 put there.

### Internal and public

Only `POST /kimaai/v1/mcp` is public: MCP clients outside KimaAI call it, and its contract is the MCP protocol, not KimaAI's screens. Every other route is internal, the open ones too: the chat routes carry the widget's own protocol (commands, renderables, the streamed events), and `POST /kimaai/v1/answer` answers, without a vector database, only from the search results the page signed into `grounding`, so it is not usable on its own. Making a route public is the owner's promise to keep it; the pages say internal until then.

### Decisions

- **Arguments a route does not declare** (it reads them in its callback: the test connection, the logs, the post status, the import) and arguments built from a variable or a method (the leads list, the Insights routes) cannot be read reliably, so the check skips their table; the pages describe them by hand from the callback.
- **Feature** is the route's class in `Loader::FEATURE_CLASSES`, the list that keeps a hidden feature's classes from loading. Routes of other classes say `none`, also where their screen belongs to a feature (the feedback analytics, the MCP admin): the route is registered whatever the feature's status.
- **WP-CLI synopsis:** some docblocks write several options on one line or the description after `:` on the same line; the inventory splits a line into options and stops at `:`, as the synopsis tokens WP-CLI uses. Three subcommands declare no options but read some (`vectors stats`, `vectors health`, `vectors collections create`); their synopsis has none and the prose names what they read.
- **MCP arguments** are described with the input schema's own texts, as the client sees them (one dash made a colon); the prose per tool is written for the page.
- **The conversations and insights page has the area `chatbot`**: the six hook areas have no Insights area, and the pages need one of them for the sync's index per area.
- **No `index.json`** for the reference pages: nine files whose frontmatter carries what the sync needs; HK-12 decides whether the website wants an index.
- **How the pages were written:** the argument tables were drafted from the inventory's output (names, types, required, defaults, ranges) with a scratch script that is not committed; every description, permission and answer was written from the route's callback. The check guards the facts it can read; the prose is kept by the rule.

### Found while writing the pages (not changed, for the owner)

- **Security: nothing found.** Seven routes are open to anyone (the chat, its history and its reset, the two ratings, the search answer, the lead form). Each that reads or writes a conversation checks that it does not belong to another logged-in user (403), and an anonymous conversation's key is its session ID (128 random bits, in an `httponly` cookie). Every other route needs `manage_options`, the leads capability, the admin assistant's screen check, or for `/mcp` a token or application password of a user with the `kimaai_mcp` capability; the MCP admin lists tokens without their hashes.
- **Routes no KimaAI code calls** (searched in `src/`, `app/` and `premium/app/`; a path built at runtime could hide a caller): the four wizard routes (the home checklist took the wizard's place), `GET /feedback/analytics/message-feedback`, `csat/summary`, `csat/list` and `incident` (the Feedback tab reads `/feedback/analytics/items` since AD-17), and `GET /chatbot/all` with `POST /chatbot/delete` (`useChatHistory` is exported but imported nowhere). Owner: remove them in a later track, or keep them.
- **WP-CLI help text:** the irregular docblocks above make `wp help kimaai vectors query` (and `fetch`, `delete`, `collections list`, `collections delete`) show options without their descriptions, and `stats`, `health` and `collections create` show none of the options they read. Declaring them would make WP-CLI check the options, a change of behaviour; not made.
- **`wp kimaai db scenario` and `wp kimaai db run`** are tools for testing migrations, shipped in Pro. Owner: keep them, or keep them out of the release.
- **Small mismatches:** `POST /chatbot/session/delete` answers "Missing session_id or session_ids." but reads only `session_ids`; the docblock of `ChatbotAdmin::deleteChatHistory()` says "by session ID", it deletes one message row by its ID.

### Step 1: the two HK-10 follow-ups

- **The tool hooks' feature** (`7cc2280b`): `kimaai_chatbot_tools_registry`, `kimaai_chatbot_allowed_tools`, `kimaai_chatbot_tool_call`, `kimaai_tool_call_allowed` and `kimaai_chatbot_max_tool_rounds` run in free code (the contact form tool, the admin assistant's tools), and the deprecated `kimaai_stream_tool_call` fires only without Pro, so the six carry `feature: none`, as the access hooks since HK-7. `kimaai_tools_registry` keeps `function-tools`: its catalogue reaches the chatbot only through Pro's tool router. The tier of all seven stays free, because the check takes it from the call sites, which are in `app/`; `index.json` follows.
- **A final answer after the last streamed round** (`a977fa3a`): the streaming runner now counts rounds as the other path does, after the model's first reply. When the model still calls tools after the last round, those calls do not run: they get the budget notice, and one more request with `tool_choice` `none` streams the answer. The notice is built once, in `ToolCallOrchestrator::answerExhaustedCalls()`, for both paths. So the default 6 now allows six rounds of tools on a streamed answer (six requests before), and 0 runs no tool on either path (the streamed path counted values below 1 as one request before). The page of `kimaai_chatbot_max_tool_rounds` and the custom tool guide say so. Tests in `ToolHooksTest`: the request counts of a streamed answer equal those without streaming (8, 12 with the example, 2 with 0), and a new test streams an answer whose model calls a tool in every reply: the tool runs twice with 2 rounds, the third call gets the notice, the last request has `tool_choice` `none`, and the visitor gets the text and a `done` with it. Both fail on the runner before the fix.

### Tests and runs

- `npm run check` before each commit: exit 0. At the end: PHPUnit unit 1577 tests, 1 skipped (1576 after HK-10, plus the streamed final answer); Jest 1201 tests in 154 suites (plus the reference check's 7).
- No e2e run: no spec covers the server's streamed tool rounds with a faked provider (the fake HTTP clients of `tests/e2e/helpers/chat.ts` stream nothing, and the streaming specs fake the stream in the browser), and HK-11 changes nothing in the browser. No WP-CLI run (AI box only); the WP-CLI page was checked against the docblocks, not against `wp help` on a site. No provider and no external service was called.

## Owner decisions before the merge (build notes)

The owner decided five open points of the track on 2026-11-16, before pull request #435 merges.

- **The admin assistant is hidden** (`25db0428`). `admin-assistant` is `hidden` in the registry. `AdminAssistant` (its seven routes and the history model), `AdminAssistantSettingsTools` and `AdminAssistantWorkflowManager` are in `Loader::FEATURE_CLASSES`, and `AdminAssistantConfigProvider::isEnabledFor()` answers false while it is hidden, so no screen shows the panel (`kimaaiAdminChatbot.enabled`). The panel's own switch, `adminAssistant.enabled` in the settings UI config, stays off by default as before. The settings catalogue and the services the MCP settings tools use (`SettingsCatalog`, `SettingsMutator`, the rollback service) keep loading: they belong to `mcp-server`. `KIMAAI_FEATURES_PREVIEW` (Playground and WP-CLI setups) brings everything back; the integration tests build the classes directly and need no constant (their bootstrap does not define it). Before this, the routes answered on `toplevel_page_kimaai` although the panel was off: the config's own `enabled` is true. The seven hook pages are hidden in `index.json` and say the assistant is not released yet; the REST page names the feature, which the reference check now requires. `docs/research/FS-feature-status.md` still lists it among the stable 1.5.13 features; the registry is the source.
- **`kimaai_lead_erased` on every deletion** (`aa40470e`). It fires after a lead is deleted on the Leads page (the bulk delete sends one `DELETE` per lead) and for each lead the "Keep leads" period deletes: `LeadModel::deleteOlderThan()` now reads the batch's IDs and statuses first, deletes by ID and returns them. A lead erased before is not announced again, so the action fires once per lead. The argument stays the lead ID. The listeners needed one change: `LeadSyncQueue::run()` sends a lead that is gone to the webhook as `lead.erased` (other destinations skip it, as before) and removes its delivery state once that is sent or given up, so a failed `lead.erased` for a deleted lead leaves no trace on the Leads page. Insights finds no row after a deletion and deletes the lead's own conversions only; after an erasure also those of its conversation, as before. The webhook's description in the integration settings says deletions send the event too.
- **Add-on settings pruned on deactivation:** unchanged.
- **Later, not now** (`1e6b1339`): the routes no KimaAI code calls, the WP-CLI docblocks whose help lacks options, a provider-confirmed meeting booking; each is in "Later" in `docs/ROADMAP.md`.
- **`wp kimaai db scenario` and `wp kimaai db run` only on a test site.** The two moved to `DbTestCommand`, a subclass of `DbCommand` with the same namespace. Both are registered; `Loader::TEST_COMMANDS` skips `DbTestCommand` unless `Helper::isTestSite()`, and on a test site it comes second and takes the place of `kimaai db` (WP-CLI's `add_subcommand()` overrides). The WP-CLI suite is a test site: `CliTestCase` sets `KIMAAI_E2E_TESTING` and `WP_DEBUG` from `tests/e2e/playground.json`, and the checkout with `tests/` is mounted. The reference check reads classes, not their registration, so the two keep their entries in `docs/reference/wp-cli.md`, marked test-only.

### Tests and runs

- `npm run check` before each commit: exit 0. PHPUnit unit 1586 tests, 1 skipped. Each new test fails on the code before its change (checked by restoring the old files in place).
- Playwright on the Mac after `npx wp-scripts build`: `admin-settings.spec.ts` (with the two admin assistant tests), `admin-settings-transfer.spec.ts` and `admin-chat-history.spec.ts`, 12 passed; `admin-leads.spec.ts` and `lead-privacy.spec.ts`, 5 passed.
- Not run: the WP-CLI suite (AI box; `DbTest`, `FeatureStatusTest`) and the integration suite. No provider, CRM or webhook was called.
