# Contributing to KimaAI

Thanks for contributing! This guide covers how to set up a development environment and run every check locally. See `CLAUDE.md` for an architecture overview.

## Requirements

- PHP >= 8.0 (CI tests 8.0–8.4)
- Composer 2
- Node.js >= 20 (see `.nvmrc`; run `nvm use` if you use nvm)

> Older Node versions fail with misleading errors (e.g. `Object.hasOwn is not a function` in Jest, or stylelint crashing on `stripVTControlCharacters`). Check `node -v` first.

## Setup

```bash
npm install
npm run dev:refresh
```

`npm run dev:refresh` installs the Composer dependencies with the dev tools (free and premium; premium needs access to the private `kimaai/kimaai-vector-db-sdk` package), deletes the compiled service containers in `app/Generated/` and builds the JS and the admin CSS. Run it after every pull or branch switch: the container is cached per plugin version, so a constructor change without a version bump otherwise ends in a fatal error, and new screens stay empty until the JS is rebuilt. `npm run build` is the release build: it installs Composer without the dev tools, so tests and linters stop working until the next `dev:refresh`.

## Running checks

| Check                 | Command                                                | Notes                                                                  |
| --------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------- |
| PHP coding standards  | `npm run lint:php-check` (fix: `npm run lint:php-fix`) | WordPress standards, see `phpcs.ruleset.xml`                           |
| PHP static analysis   | `composer analyse`                                     | PHPStan level 1                                                        |
| PHP unit tests        | `npm run test:unit`                                    | No WordPress/database needed                                           |
| PHP integration tests | `npm run test:integration`                             | Real providers only with `KIMAAI_PAID_TESTS=1` and `.env.test` (copy `.env.example`); without the flag the file is ignored |
| JS lint               | `npm run lint:js`                                      |                                                                        |
| CSS lint              | `npm run lint:css`                                     |                                                                        |
| JS unit tests         | `npm run test:js`                                      | Jest via `@wordpress/scripts`                                          |
| E2E tests             | `npm run test:e2e`                                     | Playwright; needs provider API keys in the environment                 |
| Everything lintable   | `npm run lint`                                         | Runs every `lint:*` script (JS, CSS, markdown, package.json, PHP)      |

### Local CI

GitHub Actions cost money, so no CI runs on GitHub (owner, 2026-11-13). The checks run on the Mac and on the AI box instead, one at a time, never two checks, builds or reviews at once.

- **`npm run check`** (Mac, about half a minute): Prettier and the Markdown lint on the files changed since `development`, then the brand-token check (`scripts/check-brand-tokens.mjs`: the plugin's tokens must equal the website's, read from `../kimaai`'s git repository; skipped without it), the hook pages (`scripts/check-hooks.mjs`, see "Hooks"), the reference pages (`scripts/check-reference.mjs`, see "Reference pages"), PHPCS, PHPStan, ESLint, stylelint, Jest and the PHP unit tests, with a summary. Run it before every commit of code.
- **`npm run check:related`** (Mac and AI box, once per track, before it is merged into `development`, after the review fixes): `scripts/test-plan.mjs` maps the files the track changed (`git diff origin/development...HEAD`) to the suites they need through `ci/test-map.mjs` and prints the plan with the reason for each suite; then the selected fast suites (ESLint, stylelint, PHPCS, PHPStan, Jest on the related tests, the PHP unit tests) run on the Mac and the heavy ones (integration, the selected Playwright specs and WP-CLI test classes, the Storybook build, Plugin Check, the unit tests on PHP 8.0 to 8.4) on the AI box (`ci/run-remote.sh --plan`). Docs-only changes select nothing; a file no rule matches selects every suite and is reported, so the map gets a rule for it. `npm run check:related -- --base <ref>` plans against another base. Design: `docs/research/CI-related-tests.md`.
- **`npm run check:all`** (AI box, before a release, never per track): `ci/run-remote.sh` copies the committed `HEAD` and the installed Composer vendors to `aibox:/srv/work/ci/kimaai/`, and `ci/remote-check.sh` runs every suite there in containers: the build, ESLint, stylelint, Jest, the Storybook build, `composer validate`, PHPCS, PHPStan, the PHP unit tests on PHP 8.0 to 8.4, the PHP integration tests (Ollama on the box), the Playwright e2e suite, the WP-CLI commands against a Docker WordPress (`tests/cli`, `phpunit.cli.xml`) and WordPress Plugin Check. The checkout is removed afterwards, also after Ctrl-C or a dropped connection: the box stops the run when the Mac's heartbeat ends and removes its containers, the checkout and the env file.
- **Paid providers.** `check:all` (before a release) sends the Mac's `.env.test` to the box's memory (`/dev/shm`, never its disk) so the real-provider tests (OpenAI, OpenRouter, Pinecone) run on the box; `-- --no-paid` leaves them out. `check:related` never sends it unless you pass `-- --paid`, so a track merge costs nothing. `KIMAAI_CI_HOST` overrides the SSH host (default `aibox`).
- **When the box is not available** (asleep, unreachable, not provisioned): `npm run check:all -- --local` (or `check:related -- --local`) runs the same suites in Docker Desktop on the Mac, from a copy of `HEAD` in `$TMPDIR/kimaai-ci/`.
- **Minimum WordPress.** `npm run check:all -- --wp-min` also runs the WP-CLI suite on WordPress 6.6 and PHP 8.0, the oldest the plugin supports (about 3 minutes more); with `check:related` only when the plan selects WP-CLI tests. The default run uses the latest WordPress.
- **Storybook for design reviews:** `npm run storybook:publish` builds Storybook and copies it to the AI box, where it opens at <https://aibox.tailda25c5.ts.net:6443/kimaai/> (Mac and phone, on the tailnet).
- **Needs:** `ssh aibox` working as a user in the box's `docker` group, and `composer install` plus `composer install --working-dir=premium` done on the Mac.

## Local WordPress

`npm run server` starts a disposable WordPress via WP Playground with the plugin active. `npm run watch` rebuilds JS/CSS on change.

## i18n

After adding or changing translatable strings (`__('…', 'kimaai')` in PHP or JS), regenerate the translation files:

```bash
npm run i18n
```

If `wp i18n make-pot` runs out of memory, raise the limit: `php -d memory_limit=4G $(which wp) i18n make-pot . languages/kimaai.pot --domain=kimaai --exclude=node_modules,build`.

## Tracks, review and merging

Open work is planned in `docs/ROADMAP.md` as tracks (owner, 2026-11-13). A track has an id (`DS`, `QA`, ...) and numbered items (`DS-1`, `DS-2`, ...).

### Branches

- `master` holds released code. Never push to it directly; it changes only through a release pull request from `development`, on the owner's word.
- `development` collects finished tracks. Never push to it directly either.
- A track works on `track/<ID>-<slug>` (for example `track/DS-design-system`), cut from `development`. Keep it current with `git merge origin/development`. Never rebase it, never force-push, never rewrite published history.
- A hotfix that cannot wait for a track is a one-item track: `track/<ID>-<slug>` with its own pull request into `development`.
- Never name a branch `codex/...` or `agent/...`.

### Items and commits

- Each item is one commit on the track branch (or a few, when it is large), its subject ending in the item id: `feat(chatbot): add the AI disclosure notice (DS-7)`.
- Conventional prefixes: `feat(scope):`, `fix(scope):`, `refactor(scope):`, `test(scope):`, `docs:`, `chore:`. Imperative subjects.
- Before each commit, run `npm run check` (see "Local CI") or, for a docs-only change, nothing.
- The first item of a track is its research or design document, `docs/research/<ID>-<slug>.md`. DS waits for the owner's design approval in Storybook; BM and the feature tracks wait for the owner's approval of their research; the roadmap notes "Design approved YYYY-MM-DD" or "Research approved YYYY-MM-DD" in the track's section.

### The track's pull request

Open it as a draft into `development` when the track starts: `gh pr create --draft --base development --head track/<ID>-<slug>`, titled `feat: <Track name> (<ID>)`. Its body lists every item with its commit, then what changes, the tests, the verification and notes for review. Mark it ready after the last item.

### Review

Only the whole track is reviewed, once its last item is in. A review looks for real bugs, security issues and regressions a user or site owner would hit; rare edge cases are noted in its comment, not chased.

1. **Review round N.** One reviewer per round, never two at once, and never next to a check or a build:

   ```bash
   CODEX_HOME="$HOME/.codex-alt" codex review --base development < /dev/null
   ```

   When codex-alt has hit its usage limit, claude-tech reviews instead, and its comment is labelled "Code review (claude-tech), round N":

   ```bash
   CLAUDE_CONFIG_DIR="$HOME/.claude-tech" claude -p "Review the changes on this branch against development (git diff development...HEAD) in this WordPress plugin: real bugs, security issues (missing nonce or capability checks, unescaped output, unprepared SQL, data exposed to the wrong user) and regressions a site owner or visitor would actually hit; for UI changes also WCAG 2.2 AA failures and visual regressions. Leave out rare edge cases and style. List each finding with its file, line, priority (P1/P2/P3) and why; say so if there are none." < /dev/null
   ```

2. **Judge every finding** against the code. Fix each valid one with a new commit on the track branch, with a test when it is a bug and `npm run check` before the commit: `fix(scope): ... (<ID> review)`. Do not fix what is not valid; say why.
3. **Comment** on the pull request, "Codex review (codex-alt), round N": every finding with "fixed in `<sha>`" or "not valid: (reason)", or "no findings".
4. **Next round or the related tests:**
   - A round with no findings, or only minor or edge-case points, ends the review (step 5). This needs no word from the owner.
   - In rounds 1 and 2, a real bug or security issue gets another round after its fixes.
   - From round 3 on, only a **security issue or a major bug** gets another round (4, 5 and so on). Other bugs found from round 3 on are fixed, and the review ends.
   - If round 6 still finds a P1, stop and ask the owner.
5. **Related tests.** Once the review has ended and its fixes are in, run `npm run check:related` once and post its plan and summary as a pull request comment, "Related tests (check:related)". Fix failures as new commits, each with `npm run check`; the related tests are not run again per fix commit, and the full `npm run check:all` waits for the release.
6. **Merge.** Push normally, then merge with a merge commit so the items stay visible, and delete the branch:

   ```bash
   gh pr merge <n> --merge --delete-branch
   git checkout development && git pull
   ```

   The track's last commit deletes its section in `docs/ROADMAP.md`. Release notes are written at release time from the commits (`release-pr` skill).

A docs-only change, or one that cannot cause a bug or security issue (wording, a comment), needs no review.

### Feature status

Every user-facing feature has a status in `app/Features/Features.php` (owner, 2026-11-14; `docs/research/FS-feature-status.md`). The list is internal: users only see the Beta label, and only in the admin.

- **hidden:** switched off. Its settings, blocks, shortcode modes, REST routes, AI tools, cron jobs and admin pages are not registered, and the admin assistant and MCP cannot read or change its settings. Its migrations still run, and its stored settings are kept.
- **beta:** works, with a "Beta" label in the admin: menu, page, sub-tab, section, field, Insights tab, block title.
- **stable:** no label.

`development` is too far ahead of `master` to ship features one by one through git, so all code goes to `master` and each release moves features on: the `release-pr` skill asks the owner, per hidden and beta feature, what it becomes.

A new feature:

1. Enters the registry as `hidden`, with `requires` when it needs another feature.
2. Marks its settings with a `feature` key: on a settings group or page (`link`), a sub-tab, a section in `sections`, a field, or a select option. A section's key covers its fields. `FeatureSchema::filter()` removes hidden nodes from what the admin sees; the Beta labels follow by themselves.
3. Registers nothing while hidden: a class that belongs to the feature alone goes into `Loader::FEATURE_CLASSES`; anything else checks `Features::isEnabled('<id>')` at its entry point. A class that adds settings to the schema (`kimaai_settings_schema_files`) keeps adding them while hidden, or `Settings::register()` prunes their stored values. Admin pages of their own use `featureStatus()` and `<BetaBadge>` from `@admin/components/atoms`.
4. Is tested hidden and visible. `KIMAAI_FEATURES_PREVIEW` (set by `tests/e2e/playground.json`, so in the Playwright and WP-CLI suites, and by the PHPUnit unit bootstrap) shows hidden features as beta; the `kimaai_feature_status` filter sets one status in a test, and `FeaturesWithoutPreviewTest` checks the registry as released.

### Release

Only when the owner says so: the `release-pr` skill opens a pull request from `development` into `master` (version bump, `CHANGELOG.md`, `readme.txt`). Before it opens, `npm run check:all` runs every suite on the AI box, once; what it finds is fixed as part of the release (commits on the release branch, or a fix pull request into `development` before it), and its summary is posted in the release pull request. Every release also updates the WordPress.org listing: the screenshots in `.wordpress-org/` (`npm run wporg:screenshots`) and the captions and texts of `readme.txt` show the release as users get it, without hidden features (owner, 2026-11-16). Tagging the merged release runs the WordPress.org and Freemius deploy workflows.

## Hooks

Every `kimaai` hook in the code (`apply_filters`, `do_action` and their `_deprecated` forms in PHP; `applyFilters`, `doAction` and `kimaai` browser events in JS) is public or internal (`docs/research/HK-hooks.md`). Public hooks are documented on kimaai.com and kept stable; internal hooks get no page and may change without notice.

**The rule:** whoever adds, renames, changes or removes a public hook, person or AI, changes its page in the same commit: its name, parameters, return value, when it fires, its feature or its deprecation. A new hook is either public, with its docblock, page and test in that commit, or `@internal`.

The same holds for the REST routes, the WP-CLI subcommands and the MCP tools: whoever adds, changes or removes one updates its entry on its reference page in `docs/reference/` in the same commit (see "Reference pages").

### Docblock

A public hook has the full form at its first call site in file order; further call sites carry only the `@kimaai-hook` 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.
 * @return true|string|WP_Error
 */
```

- **Internal:** `@internal Not a public hook: no page, and it may change without notice.`
- **A dynamic name** (`$hook_prefix . '_tools_registry'`) lists every name it builds, each as `@kimaai-hook <name>` or `@internal <name>`.
- **A deprecated alias** calls `apply_filters_deprecated()` or `do_action_deprecated()` right after the new name, with the release version and the replacement, and carries `@kimaai-hook <old name>` and `@deprecated <version> Use <new name>.` It keeps working for two minor releases (deprecated in 1.6, removed in 1.8); its page stays until then.
- **JS hooks and browser events** use the same tags in a JSDoc block above `applyFilters()`, `doAction()` or `dispatchEvent()`. New JS names use the dotted form (`kimaai.admin.fieldComponents`).

### Page

One page per public hook: `docs/hooks/<name>.md`, the hook's name as the file name; a browser event uses `-` for the `:` (`kimaai:chatbot` is `docs/hooks/kimaai-chatbot.md`). Start from `docs/hook-page-template.md`, which lists the frontmatter (name, type, since, tier, feature, area, summary, parameters, returns, surfaces, deprecation), the title (`# <name>`) and the body sections in their order: "When it fires", "Example" (one complete code block, which the hook's test runs), "More examples" (optional) and "Related". The body uses only what the website converts: headings, paragraphs, lists, tables, fenced code, inline code and links. `docs/hooks/index.json` is generated, never edited by hand.

### The check

`npm run check` runs `node scripts/check-hooks.mjs`. It reads every hook call in `app/`, `premium/app/` and `kimaai.php` (`scripts/hooks-inventory.php`, PHP's tokenizer) and in `src/`, and fails, with file and line, when a call site has no tag, a public hook has no page or a page no hook, the type, parameters (names, types, the number of arguments at every call site), return type, `since`, tier, feature, `@see` link or deprecation of a page and its code differ, an internal hook has a page, a page's sections, example or Markdown are off, no test names the page (`HookPage::example('<name>')` in a PHP unit test, `HookPage::page('<name>')` in `tests/cli/HooksTest.php`, `hookPage.example('<name>')` in Jest), or `docs/hooks/index.json` or `docs/features.json` (the features a release shows, from `app/Features/Features.php`, without the hidden ones; kimaai.com lists them) is out of date: `node scripts/check-hooks.mjs --write` regenerates both.

`PENDING` in the script listed the public hooks without a page while the hooks track wrote them; it is empty since HK-10. Every call site has its tag since HK-4, so `UNTAGGED` and `UNTAGGED_DYNAMIC` are empty too: a hook without a tag fails, and a public one needs its page.

### Reference pages

`docs/reference/` documents every REST route (`register_rest_route()`), every WP-CLI subcommand (a class with a static `getNamespace()`) and every MCP tool (`premium/app/Mcp/Tools/`), one page per group: `rest-<group>.md`, `wp-cli.md` and `mcp-tools.md`. A page has a frontmatter (`kind`: `rest`, `wp-cli` or `mcp`; `area`, one of the hook areas; `tier`; `summary`), the title (`# ...`), an introduction, and one `## ` section per entry: `## <METHOD> /kimaai/v1/<path>` with path parameters as `{name}`, `## wp kimaai <subcommand>`, or `## <tool>`. Under the heading comes a list of facts in this order, then the prose:

- REST: `Access` (`internal`: serves KimaAI's own admin or widget and may change without notice; `public`: stable, changed only after a deprecation), `Permission` (what the route requires; `anyone` first for a route open to everyone), `Tier`, `Feature` (the feature of the route's class in `Loader::FEATURE_CLASSES`, or `none`); then an argument table (`Argument`, `Type`, `Required`, `Description`) and what it returns.
- WP-CLI: `Tier`; then a `sh` block with the synopsis as WP-CLI reads it from the docblock's `## OPTIONS`, an option table and an example.
- MCP: `Scope`, `Tier`; then the argument table of its input schema.

Permissions are described by what they require; a page never shows secrets, token or nonce values, or a way around a permission.

`npm run check` runs `node scripts/check-reference.mjs`, which reads the code with PHP's tokenizer (`scripts/reference-inventory.php`) and 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 (name, type, required), a subcommand's synopsis or a tool's scope and arguments differ. Arguments a route reads without declaring them are described by hand and not checked.

### Versions

A hook, or a deprecation, that no release has shipped yet has the version `next`: `@since next` and `since: next`, `@deprecated next` and `deprecated.since: next` (without `removal`), and `'next'` as the version argument of `apply_filters_deprecated()` or `do_action_deprecated()`. The release writes the version in (`release-pr` skill).

## Secrets

Never commit API keys. Local credentials belong in `.env` / `.env.test` (both git-ignored); `.env.example` documents the expected variables.
