# Kibi documentation > Kibi is a requirements framework for AI coding agents. It records the reasoning behind your code as requirements in your repository, links them to code and tests, and makes every later agent respect them. This file holds the full text of the Kibi documentation published at https://getkibi.dev/. Each page starts with its title, URL and summary. --- # What is Kibi? URL: https://getkibi.dev/guide/welcome.html > Kibi is a requirements framework for AI coding agents. It records the reasoning behind your code as requirements in your repository, links them to code and tests, and makes every later agent respect them. You say what the software should do. Your coding agent writes the code. Kibi keeps those two attached: the behavior you asked for, the code that is supposed to do it, and evidence that it still does. Kibi turns that intent into a structured, checkable model — requirements, scenarios, tests, facts, and code links — that lives beside your code and travels with every branch. Your agent does the routine work: authoring and updating the model as the code changes. Kibi does the unforgiving part: checking that the model stays coherent, that the code still maps to it, and that claims of "done" are backed by fresh evidence. ## The problem it solves AI agents forget. Context windows roll over, sessions end, and the reasoning behind yesterday's change quietly disappears. Intent gets scattered across prompts, tickets, and conversations, and nothing connects it to the code that was supposed to implement it. Kibi puts that reasoning in the agent's workflow instead of hoping the agent remembers. It brings the relevant product context back into the work automatically, and it treats undocumented or unproven behavior as a gap — not as success. ## How it fits into your work You keep working the way you already do: prompt your agent, review its changes, merge. Underneath, a loop runs: 1. **You state intent.** "Draft edits must auto-save when the user navigates away." 2. **The agent records it.** Your coding agent turns the prompt into typed requirements, scenarios, tests, and links to the code symbols that implement them. 3. **Kibi checks it.** A deterministic Prolog layer verifies schemas, coherence, traceability, and contradictions before anything becomes accepted project knowledge. 4. **Evidence closes the loop.** Proof-bearing tests record fresh end-to-end results tied to the current code snapshot, and a health report shows exactly what is tested, what only rests on someone's word, and what is still waiting. Nothing about this requires you to maintain a parallel requirements bureaucracy. The prompt is the interface; humans resolve genuine product decisions, agents own the bookkeeping. ## Two levels: `remember` and `test` Not every repository wants scenarios, linked tests, and end-to-end proofs on day one. During `kibi init`, you choose a [Kibi level](../reference/cli.md#kibi-level) recorded in `package.json` (`kibi.level`) or `.kb/setup.json` (`level`): - **`test` (default)** — Full loop: requirements, code links, hooks, contradiction checks, scenarios, linked tests, and fresh proofs. - **`remember`** — Requirements, why they exist, code links, hooks, the firm-edit guard, the commit gate, and contradiction checks, with no scenarios, tests, or proofs required and a trimmed knowledge-only MCP tool list. Changing the project's level or lowering a requirement's `required_evidence` is guarded as a person-only decision across every supported agent host. ## What you will see - A `.kb/` directory in your repository holding the branch-local project model (or a single local store if you are working outside Git; running `git init` and `kibi init` later carries it over). - Git hooks that keep the model synchronized as you work (in Git repositories). - New tools available to your agent, through MCP or the `kibi` CLI: search, query, gap analysis, coverage, validation, and proof. - Optionally, read-only answers from the KBs of repositories you depend on, each pinned to a commit and kept apart from your own. - A self-contained HTML health report and a status badge you can publish, showing the percentage of requirements with current proof. ## What Kibi is not - **Not a ticket system.** It does not replace your issue tracker; it connects intent to code and evidence. - **Not a passive memory store.** Retrieval alone cannot tell you a requirement is contradictory or a test is stale. Kibi checks. - **Not an oracle.** Prolog proves what has been encoded. Ambiguity and missing knowledge stay explicitly visible instead of being dressed up as consistency. ## Where to go next - [Quick start](quick-start.md) — install Kibi and bootstrap your repository. - [Read the health report](reading-the-report.md) — what tested, an evidence level, a proof gap, and a contradiction mean. - [How Kibi works](how-it-works.md) — the mental model behind the loop. - [Connect your coding agent](connect-an-agent.md) — wire Kibi into your client. - [Kibi compared with other approaches](compare.md) — rules files, memory tools, spec-driven workflows and traceability tools. ## Use cases - [Keep every coding agent on the same requirements](use-case-consistent-agents.md) — Claude Code, Cursor, Codex and cloud agents read and check the same rules. - [Enforce the rules in AGENTS.md](use-case-agents-md.md) — turn instruction-file rules into requirements that are shown before edits and checked before commits. - [Prove that an agent's change meets a requirement](use-case-prove-changes.md) — fresh end-to-end evidence tied to the current code. --- # Quick start URL: https://getkibi.dev/guide/quick-start.html > Paste one prompt into your coding agent to install Kibi, initialize it, and bootstrap the project model behind a plan you approve. This page takes you from an empty repository to a bootstrapped, validated project model. It assumes you have a coding agent you can prompt (Antigravity, Claude Code, Cursor, Codex, OpenCode, Mistral Vibe, ZCode, VS Code, and other MCP clients all work). Git is recommended for branch isolation and the commit gate, though Kibi also works in a directory outside Git ([working without Git](../reference/errors.md#working-without-git-no_git_repository-git_required)). Kibi is meant to be run by your agent, not by hand, so the recommended setup is one prompt. The manual commands are still there if you want them. ## 1. Check the prerequisites Kibi runs on **Node.js 22+**, and its deterministic checks run on SWI-Prolog. SWI-Prolog ships with Kibi as a per-platform npm package, so on Linux (x64 or arm64, glibc 2.28+), macOS (Apple silicon or Intel) and Windows x64 there is nothing else to install; the setup brings it along. On other platforms, such as Alpine (musl) or native Windows arm64, install **SWI-Prolog 9.0+** yourself and make sure `swipl` is on your `PATH` (on Windows, running Kibi inside WSL uses the bundled build). Platform instructions, the `KIBI_SWIPL` override, and what to do if an install skipped the bundled runtime are in the [installation guide](install.md). ## 2. Paste the setup prompt into your agent (recommended) From your repository, give your coding agent this prompt: ```prompt Set up Kibi (https://github.com/Looted/kibi) in this repository, then bootstrap its knowledge base. 1. Install: confirm Node.js 22+ is available. With the package manager this repository already uses, add kibi-core, kibi-cli and kibi-mcp as dev dependencies. Do not skip optional dependencies; the bundled SWI-Prolog runtime is one. 2. Initialize: run every `kibi` command through the package manager's local runner (npm: `npm exec -- kibi `). Run `kibi init`; if it reports a problem, run `kibi doctor` and fix what it names. If this platform has no bundled SWI-Prolog, tell me what to install and stop. 3. Connect: register the project-local `kibi-mcp` server for the agent host you are running in, following https://getkibi.dev/guide/connect-an-agent.html. Prefer project-scoped configuration, and ask me before installing a plugin or changing global settings. Until the kb_* tools are visible to you, use Kibi's CLI JSON routes instead. 4. Bootstrap: run `kibi skills load kibi-bootstrap --format markdown` and follow that skill exactly. It starts by asking me where product intent lives outside the code (issue trackers, wikis, specs) and which sources to trust; read them through the connectors you have and cite them. Show me the complete plan and its hash, and write nothing until I approve it. 5. Verify: run `kibi check` and `kibi status`, fix anything they report, and summarize what was added. Do not commit; I will review the changes. ``` The agent installs `kibi-core`, `kibi-cli`, and `kibi-mcp` with your package manager, runs `kibi init` to create the `.kb/` layout, record your chosen [Kibi level](../reference/cli.md#kibi-level) (`test` recommended, or `remember` if you want requirements, code links, hooks, and contradiction checks without scenarios, tests, or proofs), and install the Git hooks that keep it synchronized, and registers Kibi's MCP server for itself. Re-running `kibi init` completes missing directories and schema files while preserving existing knowledge and schema files (changing an already-recorded level non-interactively requires `--change-level`). A hook you already have is never edited. With a hook manager (lefthook, husky, the pre-commit framework), `kibi init` installs no hooks and prints the configuration to add; `kibi init --print-hook all --format lefthook` prints it again, as the [installation guide](install.md#existing-git-hooks-and-hook-managers) shows. It also writes a Kibi section into `AGENTS.md` (imported from `CLAUDE.md` and `GEMINI.md`) and a `package.json` `prepare` step that installs the hooks, so a fresh clone of the repository, by a teammate or a cloud agent, is told about Kibi and gets the hooks on its first install; its first Kibi query compiles the branch's store. Each of these is a [setup choice](../reference/cli.md#setup-choices) you can turn off. Some agents only see new MCP tools after a restart; until then they use the same operations through the CLI. Next it interviews you. Code shows what the software does but rarely why, so the agent asks where product intent already lives (issue trackers such as Jira or YouTrack, wikis, specs, decision logs), which of those sources are authoritative and which are stale, and what it cannot reach yet. It reads the sources through the connectors it has, then combines what they say with what it finds in the codebase into a read-only bootstrap plan. Each requirement taken from a source cites the ticket or page it came from. Nothing is written until you approve it: the agent shows you the complete plan and its hash, you approve, and it applies the plan in one audited step, then validates the result. It then deepens the result in the normal Kibi workflow: it authors claims the plan could not write, proposes scenarios from acceptance criteria and models predicates for the new requirements. > [!NOTE] > Initialization does not invent product knowledge. Behavior enters when you approve the plan.
Manual installation From your repository root: ```bash npm install --save-dev kibi-core kibi-cli kibi-mcp npm exec -- kibi init ``` If anything looks off, `npm exec -- kibi doctor` reports which SWI-Prolog Kibi is using (`bundled`, `KIBI_SWIPL`, or `PATH`), whether its required libraries load, and which Kibi package versions the running engine daemon was started with; a daemon left by another install is replaced by the next Kibi command. It also reports when the current branch's authored knowledge was never compiled into its store: a warning when auto-sync compiles it on the next Kibi command (auto-sync also re-compiles a healthy store when tracked `.kb/` sources or the compiler contract change), a failure (fix: `kibi sync`) when auto-sync is off. It warns when Kibi's Git hooks are not installed, because commits then skip Kibi's check (`kibi hooks install` installs them), and warns when a recorded setup choice, such as the `AGENTS.md` section, is not in place. pnpm, Yarn, and Bun equivalents are in the [installation guide](install.md#manual-project-local-install). Then [connect your coding agent](connect-an-agent.md) and ask it: > Bootstrap Kibi for this repository.
## 3. Approve the bootstrap plan Read the plan the agent shows you. Check that requirements cite the sources you trust, answer any remaining questions the planner raises, and correct any product call it got wrong before you approve. Kibi never contacts your tracker or wiki itself; it records what the agent read and binds it into the plan's hash. Bootstrap plans bind approval to the current workspace and KB snapshot, including the journal generation and revision. A changed KB requires a new plan and matching approval. How the planner picks candidates and how a large plan is applied, tracked and resumed after an interruption are covered under [`kb_plan_bootstrap`](../reference/mcp.md#kb_plan_bootstrap) and [`kb_apply_plan`](../reference/mcp.md#kb_apply_plan). ## 4. Look at the proof state After bootstrap, ask your agent for the health report — or run it yourself: ```bash npm exec -- kibi report --open ``` You get a self-contained HTML page. The headline is a count, such as "0 of 12 current requirements fully tested end-to-end." An honest zero on day one is a successful report: it exists to make gaps explicit. [Read the health report](reading-the-report.md) explains the rows. ## 5. Work normally From here, prompt as usual. Ask for features, fixes, refactors. Your agent keeps the requirements, scenarios, tests, and code links in step with the code, and Kibi's validation gates run in the background on every change. Useful manual commands: ```bash npm exec -- kibi status # branch, snapshot freshness, migration state npm exec -- kibi search login npm exec -- kibi gaps req --format table ``` ## Upgrading After you update the Kibi packages, ask your agent to run `kibi migrate`, or run it yourself. It shows a plan and its hash and changes nothing; `kibi migrate --yes` (or `kibi migrate --apply-safe --approved-plan-hash `) applies the automatic steps you approved, including refreshing outdated Kibi-managed Git hook sections and `AGENTS.md` / `CLAUDE.md` / `GEMINI.md` blocks. Everything Kibi cannot decide for you, such as an exception nobody has approved or two requirements that supersede each other, stays in the plan as a review item. What each KB schema version changes is listed under [`kibi migrate`](../reference/cli.md#kibi-migrate) in the CLI reference. ## Next steps - [Connect your coding agent](connect-an-agent.md) — per-client configuration. - [Modeling requirements](modeling.md) — how intent becomes structured knowledge. - [Publish requirement health](github-integration.md) — put the report and badge on GitHub Pages. --- # Installation URL: https://getkibi.dev/guide/install.html > Install the Kibi packages with your package manager; SWI-Prolog is bundled on Linux, macOS, and Windows x64, with manual setup for other platforms. ## Prerequisites Kibi needs **Node.js 22+** for the CLI, MCP server, and engine. npm only warns when an older Node is active, so `kibi` and `kibi-mcp` check at startup and exit with an error naming the Node they found. Both start through the first `node` on `PATH`, so Node.js 22+ must come first there for your shell, your Git hooks, and the agent host that launches `kibi-mcp`. It also needs **SWI-Prolog 9.0+**, and on supported platforms that comes with Kibi: you install nothing extra. Git is recommended, not required. In a Git repository Kibi keeps knowledge per branch and installs the commit gate; in a directory without one it works on a single knowledge store, with no commit gate or Git hooks, and says so. Running `git init` and then `kibi init` later turns those on and keeps what was recorded ([Working without Git](error-reference.md#working-without-git-no_git_repository-git_required)). ### Bundled SWI-Prolog `kibi-cli` (and `kibi-runtime`, which `kibi-mcp` uses) depend on `kibi-swipl`, which lists one platform package per target as an optional dependency. Your package manager installs only the one that matches your machine: | Platform | Package | Requirement | | --- | --- | --- | | Linux x64 | `kibi-swipl-linux-x64-gnu` | glibc 2.28 or newer (for example Debian 10+, Ubuntu 20.04+, RHEL 8+) | | Linux arm64 | `kibi-swipl-linux-arm64-gnu` | glibc 2.28 or newer | | macOS arm64 (Apple silicon) | `kibi-swipl-darwin-arm64` | macOS 12 or newer | | macOS x64 (Intel) | `kibi-swipl-darwin-x64` | macOS 12 or newer | | Windows x64 (native) | `kibi-swipl-win32-x64` | Windows 10 or newer | On these platforms `npm install --save-dev kibi-cli kibi-mcp kibi-core` followed by `kibi init` works on a machine with no SWI-Prolog at all. The build is relocatable, ships its own libraries and licenses, and is tested with the same Prolog suites Kibi's own CI runs. Not covered: Alpine and other musl-based Linux, and native Windows arm64. On those, run Kibi inside WSL (a glibc distribution uses the bundled build), or install SWI-Prolog yourself as described below. ### Which SWI-Prolog Kibi uses Kibi picks a SWI-Prolog in this order and uses the first that works: 1. `KIBI_SWIPL=`: that executable, which must be SWI-Prolog 9.0 or newer. An invalid value is an error, never a silent fallback. 2. The bundled platform package, after Kibi verifies its manifest and the binary's SHA-256. 3. `swipl` on your `PATH`, which must be 9.0 or newer. 4. Otherwise Kibi stops with an error that names your platform, the platform package that would have covered it, and the install command for your OS. When both a bundled build and a system `swipl` exist, the bundled build wins, so a project behaves the same on every machine that installs the same packages. To use the system install instead, set `KIBI_SWIPL=system`, which skips the bundle and uses `swipl` from `PATH`: ```bash KIBI_SWIPL=system npm exec -- kibi doctor KIBI_SWIPL=/opt/swipl/bin/swipl npm exec -- kibi doctor ``` `kibi doctor` shows what was chosen: the `SWI-Prolog` check reports the source (`bundled`, `KIBI_SWIPL`, or `PATH`), the executable's path and version, and loads every library Kibi needs, so a SWI-Prolog build that lacks one (for example a minimal `swi-prolog-nox` package) fails there rather than in the middle of a command. With `--format json` the same facts appear as `details.source`, `details.path`, and `details.version`. #### If the bundled runtime is missing The platform packages are optional dependencies, so an install can leave them out without failing. `kibi doctor` and the first command that needs Prolog then name the package to add: ```bash npm install --save-dev kibi-swipl-linux-x64-gnu # the package for your platform ``` The usual causes: - Installing with `--omit=optional` or `--no-optional` (or `npm_config_omit=optional`, `optional=false`). Install without it. - pnpm `supportedArchitectures` (in `pnpm-workspace.yaml` or `package.json`) that does not include your platform, for example a Docker build that fixes `os`/`cpu` to another machine. Add your platform to it, or build the image for the platform it runs on. - Installing on one platform and running on another (copying `node_modules` from macOS into a Linux container, or the reverse). Install on the machine, or in the image, that runs Kibi. - An Alpine/musl host or Windows arm64, which has no bundled build; see below. ### Installing SWI-Prolog yourself Do this on platforms with no bundled build, or when you want Kibi to use a system install through `KIBI_SWIPL=system` or `KIBI_SWIPL=`. Kibi needs SWI-Prolog **9.0 or newer** with its standard libraries (`semweb`, `pcre`, `crypto`, `http/json`, `chr`, and others, all in a normal full install). #### Ubuntu (Recommended) The official SWI-Prolog project provides a Personal Package Archive (PPA) for Ubuntu that stays current with every release. ```bash sudo apt-get install software-properties-common sudo apt-add-repository ppa:swi-prolog/stable sudo apt-get update sudo apt-get install swi-prolog ``` #### Other Linux Distributions Official Linux distribution packages are often outdated. For other Linux distributions, including Alpine, please refer to the official SWI-Prolog documentation: - [Unix/Linux installation guide](https://www.swi-prolog.org/build/unix.html) - Comprehensive instructions for building from source or using other methods - [Stable downloads page](https://www.swi-prolog.org/download/stable) - Source archives and binaries - [Flatpak](https://flathub.org/apps/org.swi_prolog.swipl) - Available for most Linux distributions #### macOS ```bash brew install swi-prolog ``` #### Windows Windows x64 needs nothing extra: the `kibi-swipl-win32-x64` optional dependency ships the runtime. Windows arm64 has no bundled build: use the installer from the [stable downloads page](https://www.swi-prolog.org/download/stable) and let it add `swipl` to your `PATH`, or set `KIBI_SWIPL` to the full path of `swipl.exe`. Alternatively run Kibi inside WSL, which uses the bundled build and needs no SWI-Prolog install. #### Verify a system install ```bash swipl --version ``` You should see output like `SWI-Prolog version 10.x.x`. ## Installing kibi ### Recommended: Agent-led setup Kibi is operated by your coding agent, so the recommended install is a prompt. Paste this into Claude Code, Cursor, Codex, OpenCode, or any coding agent that can run commands in your repository: ```prompt Set up Kibi (https://github.com/Looted/kibi) in this repository, then bootstrap its knowledge base. 1. Install: confirm Node.js 22+ is available. With the package manager this repository already uses, add kibi-core, kibi-cli and kibi-mcp as dev dependencies. Do not skip optional dependencies; the bundled SWI-Prolog runtime is one. 2. Initialize: run every `kibi` command through the package manager's local runner (npm: `npm exec -- kibi `). Run `kibi init`; if it reports a problem, run `kibi doctor` and fix what it names. If this platform has no bundled SWI-Prolog, tell me what to install and stop. 3. Connect: register the project-local `kibi-mcp` server for the agent host you are running in, following https://getkibi.dev/guide/connect-an-agent.html. Prefer project-scoped configuration, and ask me before installing a plugin or changing global settings. Until the kb_* tools are visible to you, use Kibi's CLI JSON routes instead. 4. Bootstrap: run `kibi skills load kibi-bootstrap --format markdown` and follow that skill exactly. It starts by asking me where product intent lives outside the code (issue trackers, wikis, specs) and which sources to trust; read them through the connectors you have and cite them. Show me the complete plan and its hash, and write nothing until I approve it. 5. Verify: run `kibi check` and `kibi status`, fix anything they report, and summarize what was added. Do not commit; I will review the changes. ``` The agent picks your package manager, installs the three packages project-locally, runs `kibi init`, registers the `kibi-mcp` server for its own host, and runs the [bootstrap workflow](#first-run-lifecycle). It writes no product knowledge until you approve the plan, and it leaves the changes uncommitted for your review. The rest of this section is the manual route, and the reference for what the agent does.
Manual installation ### Manual: Project-local install For a reproducible, CI-friendly workflow, install kibi as project-level dev dependencies. Use your project's package manager; npm is shown as the Node baseline: ```bash npm install --save-dev kibi-cli kibi-mcp kibi-core ``` Equivalent project-local installs: ```bash pnpm add -D kibi-cli kibi-mcp kibi-core yarn add -D kibi-cli kibi-mcp kibi-core bun add -d kibi-cli kibi-mcp kibi-core ``` **pnpm 11 and release age.** pnpm 11 sets `minimumReleaseAge` to 1440 minutes (one day) by default, and refuses to resolve a version that does not meet it when you set `minimumReleaseAge` yourself. Kibi packages are released together and depend on each other's new versions (`kibi-cli` needs a matching `kibi-core` range, and `kibi-swipl` pins its platform packages exactly), so on the day of a release the install can fail or resolve an older, mismatched Kibi set. Either wait out the window or exempt Kibi in `pnpm-workspace.yaml` (all Kibi packages are unscoped `kibi-*` names; patterns need pnpm 10.17 or later): ```yaml minimumReleaseAgeExclude: - "kibi-*" ``` `kibi-mcp` depends on compatible `kibi-cli` and `kibi-core` versions, but installing all three explicitly makes version pinning and lockfile review clear. After installation, verify the tools from the local project using your package manager's local binary runner: ```bash npm exec -- kibi --version npx --no-install kibi-mcp --help ``` For other package managers, use the same local-runner pattern: | Package manager | CLI example | MCP example | | --- | --- | --- | | npm | `npm exec -- kibi status` | `npx --no-install kibi-mcp` | | pnpm | `pnpm exec kibi status` | `pnpm exec kibi-mcp` | | Yarn | `yarn exec kibi status` | `yarn exec kibi-mcp` | Common environment check: `npm exec -- kibi doctor` (optional troubleshooting after initialization). Validation command: `npm exec -- kibi check`.
The CLI and MCP server are peer agent-operation surfaces. MCP-capable hosts can call the public `kb_*` contracts directly; agents in trusted project-local shells can invoke the equivalent CLI JSON routes with `kibi --input `. Neither path requires direct access to `.kb/**` files. ### Kibi release versions Each Kibi package keeps its own semantic version, so `kibi-cli` 2.41.0, `kibi-mcp` 3.25.0 and `kibi-core` 0.30.0 can belong to the same release. Every release therefore also gets one Kibi release version in calendar form, `YYYY.M.N`: `2026.11.0` is the first release in November 2026, and `2026.11.1` is the next one. A release version names an exact package set and says nothing about compatibility on its own. - `kibi --version` prints both versions, for example `Kibi 2026.11.0 (kibi-cli 2.41.0)`. - `kibi doctor` reports the release under "Kibi release". If an installed Kibi package has a version other than the one that release lists, it warns with a "Mixed install" message that names each package. The JSON output (`kibi doctor --format json`) carries the full manifest under `runtime.release`. - The MCP server's title names the release, for example `Kibi MCP (Kibi 2026.11.0)`. - Each release is published as a `kibi@` GitHub release that lists every package version, with the manifest attached as `release.json`. To install a specific release, install the versions it lists. The manifest ships in `kibi-core` as `release.json`. It also declares the compatibility versions of that release: | Field | Meaning | | --- | --- | | `kbSchema.current` | The `.kb/manifest.json` `schemaVersion` this release reads and writes. | | `kbSchema.migratesFrom` | The oldest `schemaVersion` that `kibi migrate` upgrades in place. | | `operationProtocol` | The `kibiProtocol` of every CLI JSON and MCP result envelope. | | `pluginApi` | The capability plugin API (`kibi.plugin.v1`) that plugins declare as `apiVersion`. | Compatibility questions key off these numbers, not off package versions. A KB at `schemaVersion` 13 works with every release whose `kbSchema.current` is 13, whatever its package versions are. ### Update notices When a newer `kibi-cli` is published on npm, the CLI prints one line on stderr after a command, for example: ```text Kibi update available: kibi-cli 2.41.0 -> 2.42.0. Update with 'npm install -D kibi-cli@latest'. (KIBI_UPDATE_CHECK=0 turns this off) ``` The update command matches the install: the project's package manager (from its lockfile) for a project dependency, `npx kibi-cli@latest` for an npx cache, and a global install otherwise. When the newer release writes a newer KB schema (`kibi.kbSchema` in its `package.json`), the line also names the schema move and asks you to run `kibi migrate` after updating. Update `kibi-mcp` and the other Kibi packages to the same release; `kibi doctor` warns about a mixed install. - The CLI asks the npm registry for the latest `kibi-cli` at most once a day, from a detached background process, so no command waits on the network. The request sends nothing about you or the project, and the answer is cached in Kibi's per-user state directory (`update-check.json` next to the telemetry settings). It uses `KIBI_UPDATE_REGISTRY`, then `npm_config_registry`, then `https://registry.npmjs.org`. - The line appears at most once a day per version, and only when stderr is a terminal. Agent and hook runs, pipes, commands that print JSON (`--json`, `--format json`, `--input`), CI and test runs, local dev builds and a Kibi source checkout never show it and never check. - `KIBI_UPDATE_CHECK=0` or `NO_UPDATE_NOTIFIER=1` turns the check off entirely. - `kibi doctor` reports the same answer under "Kibi updates" for every agent host and for the plain CLI: a newer version is a warning with the update command, an unreachable registry is neither a warning nor a failure. ### First-run lifecycle After installing the packages, use this short path: 1. Run `kibi init` to create repository infrastructure and Git hooks. 2. Ask your coding agent to “Bootstrap Kibi for this repository.” The agent first asks where product intent lives outside the code (issue trackers, wikis, specs) and which of those sources are authoritative, reads them through its own connectors, and passes cited intent claims to the read-only `kb_plan_bootstrap` planner. After that it asks only questions returned by a `needs_context` result, and shows the exact plan for approval. 3. After approval, the agent passes the unchanged returned plan to `kb_apply_plan`, then runs `kb_check` and `kb_status`. 4. Continue normal work with the seeded Kibi context. Use `kibi doctor` only when typed status says infrastructure is degraded. ### Fresh clones and new machines `kibi init` runs once per repository, but `.git/hooks`, the compiled branch store and agent plugins never travel with a clone. So that a teammate's or an agent's fresh clone still uses Kibi, `kibi init` also: - writes a Kibi section into `AGENTS.md`, an `@AGENTS.md` import into `CLAUDE.md` and an `@./AGENTS.md` import into `GEMINI.md` (Gemini CLI reads `GEMINI.md`, not `AGENTS.md`, by default), so every coding agent, with or without a Kibi plugin, is told the knowledge base exists and how to query it; - adds `kibi hooks install --quiet` to the root `package.json` `prepare` script, so installing dependencies installs the hooks (without a root `package.json`, run `kibi hooks install` after cloning); - records these choices in `package.json` `kibi.setup` (or `.kb/setup.json`). The first Kibi query, check or write in a clone compiles the branch store from the committed sources, and agent plugins tell the agent at session start when the hooks are missing. Each piece can be turned off; see [setup choices](cli-reference.md#setup-choices). An optional pull-request gate (`kibi init --ci-gate`) runs `kibi check` in CI, where no local hook can. ### Existing Git hooks and hook managers Git runs one script per hook, so Kibi and another tool cannot both own `.git/hooks`. `kibi init` never edits a hook it did not write (the section between `# BEGIN kibi-managed` and `# END kibi-managed` is the only part it touches); it reports such a hook as skipped instead. When the repository uses a hook manager, Kibi leaves the hooks to the manager and you add Kibi's commands to the manager's configuration. These are the commands Kibi's own hooks run. Any setup that runs the same commands under the same conditions is equivalent: | Git hook | When | Commands (all must succeed) | | --- | --- | --- | | `pre-commit` | every commit | `kibi check-generated --staged --changed-only`, then `kibi check --staged` | | `post-checkout` | branch checkouts only (third hook argument is `1`) | `kibi sync` | | `post-merge` | every merge | `kibi sync` | | `post-rewrite` | rebases only (first hook argument is `rebase`) | `kibi sync` | The sync hooks compile the checked-out branch's KB store, so tools and the next commit see current knowledge; the pre-commit commands are Kibi's commit gate. Hooks never run in CI: run `kibi sync` there (with `KIBI_BRANCH` set when the checkout is a detached HEAD) before `kibi check`. **What `kibi init` does.** It detects lefthook (a `lefthook.yml` or its variants, or hook runners lefthook generated), husky (`core.hooksPath` set to `.husky` or `.husky/_`, or a `.husky/` directory) and the pre-commit framework (`.pre-commit-config.yaml` or hooks it generated). With one present it installs nothing into the hooks directory and prints the configuration to add for every hook the manager does not visibly run Kibi's commands for yet. Use `--no-hooks` to skip hook setup altogether. **Print the configuration** in your manager's format at any time; it writes nothing: ```bash npx --no-install kibi init --print-hook all --format lefthook # or husky, pre-commit npx --no-install kibi init --print-hook pre-commit # one hook, as a shell snippet ``` `--print-hook` takes `pre-commit`, `post-checkout`, `post-merge`, `post-rewrite` or `all`; `--format` takes `shell` (the default), `lefthook`, `husky` or `pre-commit`. - **lefthook**: merge the printed entries into `lefthook.yml`, then run `lefthook install`: ```yaml pre-commit: commands: kibi-check: run: npx --no-install kibi check-generated --staged --changed-only && npx --no-install kibi check --staged post-checkout: commands: # {3} is 1 for a branch checkout, 0 for a file checkout. kibi-sync: run: if [ "{3}" = "1" ]; then npx --no-install kibi sync; fi post-merge: commands: kibi-sync: run: npx --no-install kibi sync post-rewrite: commands: kibi-sync: run: if [ "{1}" = "rebase" ]; then npx --no-install kibi sync; fi ``` - **husky** (or any hand-written shell hook): append the printed snippet to each hook file. It finds a project-local `kibi` even when `node_modules/.bin` is not on the hook's `PATH`, and stops the commit if either check fails: ```bash npx --no-install kibi init --print-hook pre-commit >> .husky/pre-commit npx --no-install kibi init --print-hook post-checkout >> .husky/post-checkout npx --no-install kibi init --print-hook post-merge >> .husky/post-merge npx --no-install kibi init --print-hook post-rewrite >> .husky/post-rewrite ``` - **pre-commit framework**: merge the printed local hooks into `.pre-commit-config.yaml` and add the hook types to `default_install_hook_types`, then run `pre-commit install`. The post-checkout and post-rewrite entries read the hook arguments from `PRE_COMMIT_CHECKOUT_TYPE` and `PRE_COMMIT_REWRITE_COMMAND`. Calling the commands through a task runner (`task`, `make`, `just`, an npm script) works too. `kibi doctor` reads the manager's configuration (lefthook YAML or JSON, `.husky/`, `.pre-commit-config.yaml`) and passes each hook that visibly runs Kibi's commands. It cannot follow a task runner, so a hook that reaches Kibi that way is reported as a warning naming the commands to check, never as a failure. Avoid auto-install or hot-load commands for MCP startup (`npx -y`, `pnpm dlx` / `pnx`, or `yarn dlx`) unless you intentionally want the client to fetch a package outside the project lockfile. ### OpenCode MCP For OpenCode, add a local MCP server in `opencode.json`. OpenCode uses a token-array `command` field. This npm example is local-only and does not download packages at startup: ```json { "$schema": "https://opencode.ai/config.json", "mcp": { "kibi": { "type": "local", "command": ["npx", "--no-install", "kibi-mcp"], "enabled": true } } } ``` If your project uses another package manager, keep the same MCP shape and use that manager's local binary runner. For example, pnpm projects can use: ```json { "$schema": "https://opencode.ai/config.json", "mcp": { "kibi": { "type": "local", "command": ["pnpm", "exec", "kibi-mcp"], "enabled": true } } } ``` ### VS Code MCP For VS Code, create `.vscode/mcp.json`. VS Code uses a `command` string with a separate `args` array: ```json { "servers": { "kibi": { "type": "stdio", "command": "npx", "args": ["--no-install", "kibi-mcp"] } } } ``` If you use pnpm, replace `"command": "npx"` and `"args"` with: ```json { "servers": { "kibi": { "type": "stdio", "command": "pnpm", "args": ["exec", "kibi-mcp"] } } } ``` ### Optional: OpenCode plugin `kibi-opencode` is an optional OpenCode plugin. It injects Kibi guidance, provides the `/kibi-bootstrap` convenience command when the host supports it, and runs background sync/check maintenance. When the file being edited implements a requirement, the guidance names it, what it must keep true, and the decision behind it. On OpenCode v1 the plugin also runs the decision hooks the other host plugins run. A message that states a rule is noted, and the note and a fill-in `kb_record` capture template are added to the result of the session's first source edit. An edit of code that implements a firm requirement is stopped once with the notice to ask the person first and, after the edit, to record a verdict with `kb_review_firm_edit` (the same edit tried again goes through; `KIBI_CONFIRM_FIRM_EDITS=0` turns the stop off, never the commit gate). When a session that changed source and recorded nothing goes idle, the plugin asks once for the capture, or for `kibi signoff` after requirement writes. Shell in-place edits (`sed -i`, `>`, `tee`) count as source edits. These need the v1 plugin hooks `chat.message`, `tool.execute.before` and `session.idle`, which the v2 plugin API does not expose yet, so they are off under OpenCode v2. Canonical bootstrap behavior lives in the bundled `kibi-bootstrap` skill (`kb_plan_bootstrap`, preview, apply via the approved plan). Generic MCP agents should start from [generic-agent onboarding](generic-agent-onboarding.md). The plugin does **not** ship a replacement `kibi` or `kibi-mcp` binary, so keep the base `kibi-cli`, `kibi-mcp`, and `kibi-core` packages installed and keep the `mcp.kibi` server configured separately. ```bash npm install --save-dev kibi-opencode ``` ```json { "plugin": ["kibi-opencode"] } ``` The OpenCode plugin auto-updates itself by default on OpenCode startup. This only refreshes OpenCode's cached `kibi-opencode` package; it does not update your project-local `kibi-cli`, `kibi-mcp`, or `kibi-core` dependencies. To lock the plugin, use an exact semver entry in the plugin array: ```json { "plugin": ["kibi-opencode@"] } ``` Set `autoUpdate: false` in `.opencode/kibi.json` or `~/.config/opencode/kibi.json` to disable the startup updater entirely. A `plugin` array entry always installs from npm into OpenCode's cache, never from the project's `node_modules`, and a `file://` path there does not load. To run the version installed in the project instead, drop the array entry and re-export it from `.opencode/plugins/kibi.js`: ```js export { default } from "../../node_modules/kibi-opencode/dist/index.js"; ``` The local file is not auto-updated; it follows the project's installed version. See `packages/opencode/README.md`. The plugin's internal maintenance expects a `kibi` CLI command to be available from the project context or `PATH`; the canonical setup above satisfies that by installing `kibi-cli` project-locally. #### OpenCode v1 and v2 The same `kibi-opencode` package loads on OpenCode v1 (1.4 and later) and on OpenCode v2. The default export carries both plugin shapes: v1 reads `{ id, server }` (and `{ id, tui }` for the TUI entry), and v2 reads `{ id, setup }`. Install and configure it the same way on either version. A directory install (a distro package or a local folder) does not read `package.json` `"exports"`. The package ships root `index.js` and `tui.js` shims that re-export the built server and TUI entries, so both parts load. Without `tui.js`, that install reports the server plugin only. On OpenCode v2: - Kibi guidance, background sync/check maintenance, and `/kibi-bootstrap` work as on v1. The decision hooks (stated-rule capture, the firm-edit stop and the idle capture request) are off, because v2 exposes none of the hooks they need. Syncs triggered by file changes come from completed `edit`, `write`, and `patch` tool calls. On OpenCode v2.0.32 a plugin can async-iterate `event.subscribe()` and will see public bus events, including `filesystem.changed`, but the host publishes that event only for the VCS HEAD file (creating a branch delivered `{ type: "filesystem.changed", data: { file: "/.git/HEAD", event: "change" } }`). A bash `rm` or `mv`, appending to a tracked file, and `git checkout -- ` produced no `file.created`, `file.edited`, `file.deleted`, or `filesystem.changed` event. The SDK's `file.watcher.updated` type is not in the v2.0.32 binary, and `file.edited` is only a schema with no publish site. Changes from bash, `git checkout`, or an external editor therefore do not trigger a Kibi sync. Run `kibi sync` yourself, or rely on the `post-checkout`, `post-merge`, and `post-rewrite` hooks installed by `kibi init` (each runs `kibi sync`). The next status refresh also picks up the working tree. `kibi sync` reads only documents Git tracks (staged is enough), so a new document written outside the agent needs `git add` before `kibi sync` imports it. Documents written through `kb_upsert` are covered until then. - v2 has no toast or structured plugin log, so kibi-opencode shows no toasts and reports plugin errors on stderr with a `[kibi-opencode]` prefix. - **Code Mode:** v2 exposes MCP tools through Code Mode by default. On OpenCode v2.0.32 the catalog lists `kibi (19 tools, 1 shown)` at level `test` (fewer at level `remember`, or eight with the `core` profile), `search({ query: "kibi" })` finds all of them, and the tools are reachable through `execute` under `tools.kibi`. To call the native `kibi_*` tools directly, set `codemode: false` on a v2-native server entry under `mcp.servers`: ```json { "mcp": { "servers": { "kibi": { "type": "local", "command": ["npx", "kibi-mcp"], "codemode": false } } } } ``` Setting `codemode` on a v1-style entry (`mcp.kibi` with `enabled`) has no effect: OpenCode v2 migrates v1 entries and drops that key. OpenCode v1 reads every key under `mcp` as a server name, so keep this entry in a configuration that only OpenCode v2 reads. - OpenCode v1 and v2 share the same `opencode.db`. To run both on one machine, give each its own `XDG_DATA_HOME`, `XDG_STATE_HOME`, `XDG_CACHE_HOME`, and `XDG_CONFIG_HOME`. ### Optional: Codex plugin `kibi-codex` is an optional adapter that gives Codex users prepackaged Kibi skills, hooks, and MCP configuration. It builds on `kibi-core`, `kibi-cli`, and `kibi-mcp` and does not replace them. Install through the repo-scoped Kibi marketplace: ```bash codex plugin marketplace add Looted/kibi codex ``` Then run `/plugins`, choose **Kibi Plugins**, and install `kibi-codex`. The marketplace lives at `.agents/plugins/marketplace.json` and points Codex at `./packages/codex`, where the plugin manifest, skills, hooks, and MCP config are stored. Codex resolves that path relative to the marketplace root. Local marketplace installs copy the plugin directory as-is. The committed `bin/hook-runner.mjs` makes lifecycle hooks work from an unbuilt source checkout; run `bun run build:codex` when you also need refreshed generated skills or MCP configuration. (Packed npm installs run the build automatically via `prepack`.) #### Workspace opt-in rule The plugin may be installed and enabled globally, but it only activates in workspaces that opted into Kibi: - A workspace is opted in when its Kibi project root owns `.kb/manifest.json` (the manifest `kibi init` creates). Installing the plugin, having `kibi-mcp` on `PATH`, or enabling the plugin in `~/.codex/config.toml` never counts. - Project-root resolution honors the standard `KIBI_WORKSPACE`, `KIBI_PROJECT_ROOT`, and `KIBI_ROOT` environment overrides, then walks up from the session directory and stops at the first `.kb/manifest.json` (opted in) or `.git` boundary (not opted in). Subdirectories of an opted-in repository map to that repository; a Git worktree is evaluated by its own root and never inherits the main checkout's state; an unrelated enclosing repository never leaks opt-in into a nested project. - In unconfigured workspaces every hook exits successfully and silently — no bootstrap prompts, no edit tracking, no reminders, no state writes — and the MCP server starts with an empty tool catalog. Nothing is initialized or written unless you explicitly ask for it (`kibi init` or the kibi-bootstrap skill). - In opted-in workspaces the plugin behaves as before: hooks warn about direct `.kb` edits, track changed paths, and surface freshness/impact reminders at session stop, scoped to the workspace they were generated in, so activity in one project cannot generate reminders in another. - Before `apply_patch` (or another edit tool) changes a file whose symbols are linked to a requirement, `PreToolUse` adds a short snippet to the agent's context: the requirement, what it must keep true (its linked facts), the decision behind it (its ADR), and the tests that cover it. It covers up to three changed files per call, once per file per session, and a superseded or retired requirement is never presented as current. #### Codex host limitations and the MCP launcher Codex (verified against `codex-cli 0.153.4`) has no workspace-scoped or content-conditional activation for plugins or their MCP servers: plugin enablement is global, and legacy `.codex-plugin` MCP entries support no placeholder expansion or plugin-root environment. To keep non-Kibi workspaces free of MCP startup errors, the plugin's `.mcp.json` therefore inlines a launcher (`node -e`, built from `packages/codex/bin/mcp-launcher.cjs`) that: - resolves the workspace from the active session cwd and the opt-in rule above; - serves a silent MCP server with zero tools in unconfigured workspaces; - probes and proxies the project-local `kibi-mcp` (`npx --no-install kibi-mcp`, exactly the previous config) in opted-in workspaces, with `KIBI_WORKSPACE` set to the resolved root; - starts cleanly with a guidance message when an opted-in workspace has no resolvable `kibi-mcp` executable — the MCP handshake still succeeds, so no startup error is reported. The launcher is a supported stdio server from Codex's point of view; it simply stays empty unless the workspace opted in. For local development or npm package smoke testing, you can also install the adapter package with your project-local dependencies: ```bash npm install --save-dev kibi-codex ``` The official OpenAI Plugin Directory does not currently provide self-serve public plugin publishing. Use the repo marketplace or a local plugin fixture while developing/testing. The installed plugin package contributes: - `.codex-plugin/plugin.json` manifest - `assets/` Kibi logo and composer icon assets - `.mcp.json` MCP config with the inline workspace-opt-in launcher - `hooks/hooks.json` lifecycle hooks - `skills/*/SKILL.md` Kibi workflow guidance Review hook trust policy before enabling automatic trust: - confirm the plugin source and hook paths are expected in your environment - review local trust settings if your Codex host requires explicit plugin trust - prefer warning-only behavior and disable automatic trust for unvetted sources Manual MCP fallback (no plugin install required): keep base dependencies and configure your Codex MCP client directly: ```toml [mcp_servers.kibi] command = "npx" args = ["--no-install", "kibi-mcp"] ``` This fallback is supported for teams that do not use the adapter package. ### Optional: Cursor plugin `kibi-cursor` is an optional adapter that gives Cursor users prepackaged Kibi rules, skills, commands, MCP configuration, and advisory editor hooks. It builds on `kibi-core`, `kibi-cli`, and `kibi-mcp` and does not replace them. Install from the repo marketplace at `.cursor-plugin/marketplace.json`, which points at `./plugins/kibi-cursor`. For local development, copy the built plugin into Cursor's user-plugins directory (symlinks are rejected on WSL): ```bash ./scripts/sync-cursor-plugin-local.sh ``` On WSL workspaces, Cursor reads `~/.cursor/plugins/local` in your Linux home. Restart Cursor or run **Developer: Reload Window**, then check **Plugins → User**. You can also install the npm package for smoke testing: ```bash npm install --save-dev kibi-cursor ``` The installed plugin package contributes: - `.cursor-plugin/plugin.json` manifest - `mcp.json` MCP config with a launcher that resolves and starts the `kibi-mcp` installed in the opened project - `hooks/hooks.json` advisory lifecycle hooks; before Cursor reads or edits a file whose symbols implement a requirement, they show that requirement and its tests, and before an edit, what it must keep true and the decision behind it - `rules/*.mdc` workflow and traceability guidance - `skills/*/SKILL.md` Kibi workflow skills - `commands/kibi-bootstrap.md` bootstrap command guidance The plugin launcher runs the consumer project's `kibi-mcp` with the opened workspace as its current directory and with `KIBI_WORKSPACE` set to that root. It does not download, bundle, or use a global Kibi runtime. Install the base packages in each project before enabling the plugin MCP server. Manual MCP fallback (no plugin install required): ```json { "mcpServers": { "kibi": { "command": "npx", "args": ["--no-install", "kibi-mcp"] } } } ``` See [Cursor Plugins](https://cursor.com/docs/plugins) and `packages/cursor/README.md` for hook behavior and local testing details. ### Optional: ZCode plugin `kibi-zcode` is an optional adapter that gives ZCode users prepackaged Kibi skills, a `/kibi-bootstrap` command, advisory lifecycle hooks, and MCP configuration. It builds on `kibi-core`, `kibi-cli`, and `kibi-mcp` and does not replace them. Local ZCode development, package builds, and tests currently use Linux/WSL. The launcher retains shell-free runtime handling for Windows npm shims. Install through the **Kibi** repo marketplace: 1. In ZCode, open **Settings → Plugin Management → Discover**, use the **`+`** button, and add the `Looted/kibi` GitHub repository — or a local checkout through **local directory**, selecting the repository root — the directory that contains `.claude-plugin/marketplace.json` (the manifest points ZCode at `./packages/zcode`). 2. Install `kibi-zcode` from the **Kibi** marketplace. New installs are enabled by default. The hook runner ships as the tracked `bin/hook-runner.mjs` bundle, so a marketplace copy of the repository — GitHub-sourced or a local checkout, built or not — contains a working hook runner for every lifecycle hook. `prepack` (the automatic build for packed npm installs) runs only for `npm pack`/`npm install kibi-zcode` packaging flows; ZCode's marketplace copy never builds anything, which is why the bundle is committed and drift-checked in CI. The installed plugin package contributes: - `.zcode-plugin/plugin.json` manifest with the inline `mcpServers` entry - `bin/mcp-launcher.cjs` workspace-gated MCP launcher (resolves kibi-mcp shell-free: the project-local package entry through Node's own resolution, then a PATH lookup, with the Windows npm-shim layout handled without a command interpreter) - `hooks/hooks.json` advisory lifecycle hooks (`SessionStart`, `PreToolUse`, `PostToolUse`, `Stop`) - `skills/*/SKILL.md` Kibi workflow skills (frontmatter rewritten for ZCode's skill loader; bodies and resources are byte-identical to the canonical bundled skills) - `commands/kibi-bootstrap.md` slash command that routes into the `kibi-bootstrap` skill The plugin follows the same workspace opt-in rule as the Codex adapter: hooks and the MCP launcher stay completely silent in workspaces whose Kibi project root does not own `.kb/manifest.json`. In opted-in workspaces, the MCP launcher proxies the resolved `kibi-mcp` with `KIBI_WORKSPACE` set, and hooks are advisory only — they warn about direct `.kb` edits, track file mutations per host session (read-only tool calls never count as changes, and a later edit invalidates an earlier impact check for that path), and surface freshness/impact reminders at session stop with workspace-relative paths. Before an edit of a file linked to a requirement, `PreToolUse` adds the requirement, what it must keep true, the decision behind it, and its tests to the agent's context, once per file per session. The hard enforcement gate remains the `kibi check --staged` git hook installed by `kibi init`. Manual MCP fallback (no plugin install required): ```json { "mcpServers": { "kibi": { "command": "npx", "args": ["--no-install", "kibi-mcp"] } } } ``` See `packages/zcode/README.md` for the ZCode declaration contract the plugin targets (hook events, output schema, skill frontmatter rules). ### Optional: Vibe plugin `kibi-vibe` is an optional Mistral Vibe plugin in Agent Plugins 1.0 format. It bundles the `kibi` MCP server, the canonical Kibi skills (mirrored under `skills/`), and fail-open Vibe hooks. It builds on `kibi-core`, `kibi-cli`, and `kibi-mcp` installed project-locally and does not replace them. Install from a **local checkout** into the user plugins root, then restart Vibe or run `/reload`: ```bash mkdir -p ~/.vibe/plugins && cp -r packages/vibe ~/.vibe/plugins/kibi ``` The plugin contributes `plugin.json`, `mcp.json` (the `kibi` stdio server via `bin/launch-kibi-mcp.mjs`), `ai.mistral.vibe/hooks.toml` (session-start KB status, per-prompt KB hits, per-file linked entities), and `skills/*`. **Windows:** Kibi needs Node.js 22+ and SWI-Prolog 9+. The bundled SWI-Prolog covers Linux, macOS and Windows x64, so the launcher runs Kibi natively on Windows by default. A workspace opened as a `\\wsl.localhost\\...` UNC path (or any workspace with `KIBI_FORCE_WSL=1`) runs inside that WSL distribution instead: `wsl.exe [-d ] --cd --exec [args...]`, with paths and arguments passed as literal argv entries, never a shell string. `KIBI_FORCE_DIRECT=1` forces a native spawn. If a WSL workspace needs the wrap but the distribution has no usable Node.js 22+, the launch fails with a message saying so instead of falling back to Windows Node.js. Because Vibe spawns stdio servers with the plugin directory as cwd, not the session folder, the launcher resolves the workspace from `KIBI_WORKSPACE`/`KIBI_PROJECT_ROOT`/`KIBI_ROOT`, a `.git`-bounded upward walk for `.kb/manifest.json`, or a `kibi-workspace.txt` pointer next to the launcher (ignored when the cwd is inside another Git repository). The pointer names one workspace, so treat it as a single-project fallback: use `KIBI_WORKSPACE` to serve several projects. In a direct (non-WSL) launch, `kibi-mcp` still answers each call from the Kibi workspace under the MCP roots the client declares. When registering the server manually instead of via the plugin: ```toml [[mcp_servers]] name = "kibi" transport = "stdio" command = "node" args = ["/packages/vibe/bin/launch-kibi-mcp.mjs"] # a cold WSL boot can exceed the 10s default: startup_timeout_sec = 120 tool_timeout_sec = 300 ``` In workspaces without `.kb/manifest.json` the launcher serves a silent zero-tool MCP server (exit 0) instead of failing the handshake, and the hooks exit quietly — Kibi stays out of non-Kibi projects. Set `KIBI_VIBE_LAUNCHER_DEBUG=1` for a per-user launcher log (`kibi-vibe-launcher.log-`) in the OS temp dir; it also lets the hooks' child processes print to stderr, which they otherwise keep silent. See `packages/vibe/README.md` for the full contract and the executable tests (`packages/vibe/tests/`). ### Optional: Claude Code plugin `kibi-claude` is an optional Claude Code adapter. It builds on `kibi-core`, `kibi-cli`, and `kibi-mcp` and does not replace them. It contributes: - the workspace-gated Kibi MCP server; - the seven bundled Kibi skills, invoked as `/kibi-claude:kibi-usage`, `/kibi-claude:kibi-bootstrap`, and so on; - advisory hooks that show the agent requirement and test context before it reads or edits linked code (before an edit, also what the requirement must keep true and the decision behind it), and remind it once to run an impact check before finishing. The repository root is a Claude Code marketplace, and the hook runner is a committed self-contained bundle, so a GitHub install needs no build: ```bash claude plugin marketplace add Looted/kibi ``` ```bash claude plugin install kibi-claude@kibi ``` To try a local checkout without installing, run `claude --plugin-dir packages/claude` from a Kibi workspace. The plugin follows the same workspace opt-in rule as the Codex and ZCode adapters: hooks and the MCP launcher stay completely silent in workspaces whose project root does not own `.kb/manifest.json`. Hooks read a cached index of `.kb/symbols.yaml` instead of calling the CLI, so they add tens of milliseconds per tool call. The hard enforcement gate remains the `kibi check --staged` git hook installed by `kibi init`. See `packages/claude/README.md` for exactly what each hook emits and how often. Cloud sessions (Claude Code on the web and in the desktop app) load the plugin only when the repository enables it: commit `extraKnownMarketplaces` for `Looted/kibi` and `"enabledPlugins": {"kibi-claude@kibi": true}` to the repository's `.claude/settings.json` (the exact snippet is in `packages/claude/README.md`). ### Optional: Antigravity plugin `kibi-antigravity` is an optional Google Antigravity plugin (`packages/antigravity`). It builds on `kibi-core`, `kibi-cli`, and `kibi-mcp` and does not replace them. It contributes: - the workspace-gated Kibi MCP server (which resolves project-local `kibi-mcp` immediately in workspace-scoped installs and via MCP `roots/list` in globally installed Marketplace setups, staying silent with zero tools in non-Kibi repositories); - the seven bundled Kibi skills (`kibi-usage`, `kibi-bootstrap`, `kibi-decisions`, `kibi-traceability`, `kibi-commit-review`, `kibi-freshness`, `kibi-provable-code`); - always-on workflow rules (`rules/AGENTS.md`); - lifecycle hooks (`SessionStart`, `PreInvocation`, `PreToolUse`, `PostToolUse`, `Stop`) that inject progressive-disclosure requirement snippets, stamp `workspaceRoot` onto Kibi MCP calls, ask before edits that change code implementing a `firm` requirement (`KIBI_CONFIRM_FIRM_EDITS=0` disables), and remind once at stop about unchecked edits, unrecorded decisions, or pending signoff. Install globally from GitHub with the Antigravity CLI (`agy`) (use `tree/develop/packages/antigravity` instead of `tree/master/packages/antigravity` if installing before the plugin is released on `master`): ```bash agy plugin install https://github.com/Looted/kibi/tree/master/packages/antigravity ``` When validating or installing from a local Kibi monorepo checkout, exclude `node_modules` first (`agy plugin install` rejects workspace symlinks pointing outside the plugin directory): macOS / Linux: ```bash agy plugin validate --strict ./packages/antigravity rsync -a --delete --exclude node_modules ./packages/antigravity/ /tmp/kibi-antigravity/ agy plugin install /tmp/kibi-antigravity rm -rf /tmp/kibi-antigravity ``` Windows (PowerShell): ```powershell agy plugin validate --strict .\packages\antigravity $tmp = Join-Path $env:TEMP kibi-antigravity Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue New-Item -ItemType Directory -Path $tmp | Out-Null Get-ChildItem .\packages\antigravity -Exclude node_modules | Copy-Item -Destination $tmp -Recurse agy plugin install $tmp Remove-Item -Recurse -Force $tmp ``` To share the plugin across a repository via VCS, register it in `.agents/plugins.json`. See `packages/antigravity/README.md` for details. ### Optional: languages beyond TypeScript and JavaScript TypeScript and JavaScript symbols are built in. For Python, Go, Rust, Java, C#, PHP, C, C++, Bash, Ruby, SWI-Prolog and Terraform/HCL, add the optional `kibi-plugin-treesitter` package and the grammar pack of each language the repository uses. Each pack is a small data-only `kibi-lang-*` package: `kibi-lang-python`, `kibi-lang-go`, `kibi-lang-rust`, `kibi-lang-java`, `kibi-lang-csharp`, `kibi-lang-php`, `kibi-lang-c`, `kibi-lang-cpp`, `kibi-lang-bash`, `kibi-lang-ruby`, `kibi-lang-hcl` and `kibi-lang-prolog`. `kibi init` and `kibi doctor` name the packs the tracked sources need, at the version the plugin pins. Generated files (`linguist-generated` in `.gitattributes`, or a generator header) count only when the KB references them, and a pack the project does not want can go in `package.json` `kibi.declinedLanguagePacks`; see the [plugin guide](plugin-development.md). ```bash npm install --save-dev kibi-plugin-treesitter kibi-lang-python kibi-lang-go ``` Then activate it in `package.json`. `kibi.symbol-extractor.v2` gives symbols, their coordinates and the commit gate for those languages; `kibi.reference-extractor.v1` also lets source proofs read what Go, Java, C#, Rust, PHP, C and Bash files import, call and read from the environment, and the values Terraform/HCL files set: ```json { "kibi": { "plugins": [ { "package": "kibi-plugin-treesitter", "capabilities": { "kibi.symbol-extractor.v2": { "mode": "augment" }, "kibi.reference-extractor.v1": { "mode": "augment" } } } ] } } ``` A project without a `package.json` (a Go, Rust or Java project, say) creates a minimal one first with `npm init -y`; Kibi reads only its `devDependencies` and `kibi.plugins`. Add `node_modules/` to `.gitignore`. Code and source proofs read TypeScript, JavaScript, Python and SWI-Prolog without the plugin. The [plugin reference](./plugin-development.md) and the [`kibi-plugin-treesitter` README](https://www.npmjs.com/package/kibi-plugin-treesitter) cover symbol titles, partial analysis and what each language reads; [proving requirements](./proving-requirements.md) covers what source proofs list and refuse in each language. ### Optional capability plugins Builtin classification, ontology matching, and symbol extraction need no plugin configuration. Installing an optional package does not activate it. ```text install package → explicitly activate in package.json → provide required secret/environment → restart long-lived Kibi MCP/client runtime ``` `kibi-plugin-jev` is the optional TypeSafe semantic classifier. It is not part of the default Kibi install. ```bash npm install --save-dev kibi-plugin-jev ``` ```json { "kibi": { "plugins": [ { "package": "kibi-plugin-jev", "capabilities": { "kibi.semantic-classifier.v1": { "mode": "augment" } } } ] } } ``` Set provider secrets through Kibi-owned env files (same resolution for every harness that starts `kibi` / `kibi-mcp` — no Cursor/OpenCode/Codex/ZCode-specific secret config is required): ```bash mkdir -p ~/.config/kibi printf '%s\n' 'TYPESAFE_API_KEY=...' >> ~/.config/kibi/env ``` Optional project override: `/.env.kibi`. Existing process environment variables always win. `KIBI_ENV_FILE` replaces the project file path. A legacy `/.env` is still loaded for compatibility to fill remaining gaps, but is not preferred (it can pull unrelated app secrets into Kibi). Restart long-running MCP or host processes after changing env files. Do not put secrets in `package.json`. The project file and the legacy `.env` come with the checkout, so Kibi lets them set only provider secrets and provider settings: `KIBI_JEV_*`, and keys named like a provider secret or setting (ending in `_API_KEY`, `_KEY`, `_TOKEN`, `_SECRET`, `_PASSWORD`, `_MODEL`, `_ORG`, `_ORG_ID`, `_ORGANIZATION`, `_PROJECT`, `_PROJECT_ID` or `_REGION`, such as `TYPESAFE_API_KEY`). Every other key there is ignored, including variables that make a process load code, such as `OPENSSL_CONF` or `_JAVA_OPTIONS`, and provider endpoints (`_URL`, `_ENDPOINT`, such as `TYPESAFE_BASE_URL`), which would let a cloned repository send the API key you keep in the user env file to its own server. That covers any other `KIBI_*` key, such as `KIBI_NODE_PATH`, `KIBI_SWIPL`, `KIBI_KB_PL_PATH`, `KIBI_RUNTIME_DIR`, `KIBI_ENV_FILE`, `KIBI_WORKSPACE` or `KIBI_BRANCH`, and process variables such as `PATH`, `HOME`, `TMPDIR`, `NODE_OPTIONS`, `NODE_*`, `LD_*`, `DYLD_*`, `BUN_*`, `GIT_*`, `XDG_*`, `SWI_HOME_DIR` and the proxy variables, so a cloned repository cannot choose what Kibi runs or loads. Each command names the ignored keys once on stderr (never their values; a line that is not a plain upper-case variable name is only counted, and a legacy `.env` names only the Kibi and process keys it tries to set, not your application's own settings). A quoted value may span lines, as a PEM key does. Set those keys in the process environment or in `~/.config/kibi/env`, which Kibi applies unfiltered. Optional settings: | Variable | Role | | --- | --- | | `KIBI_JEV_MODEL` | Model id. Empty is unset. Default `jev-latest`. | | `KIBI_JEV_TIMEOUT_MS` | Positive integer timeout in milliseconds, at most 120000. A malformed value fails activation with a provider diagnostic. | Modes: ```text augment — builtin handles normal cases; external provider helps unresolved/ambiguous cases replace — configured provider owns the capability; builtin is only failure fallback shadow — provider runs for comparison but cannot affect canonical output ``` Removing the `kibi.plugins` entry disables the plugin. Restart long-running MCP or host processes after plugin configuration changes. Activating a third-party package grants that package code-execution trust. `permissions` metadata is disclosure, not sandbox enforcement. `kibi doctor` lists configured packages, capabilities, modes, and dependency declaration without importing plugin packages. For first-party Jev it also reports secret source labels (`process` / `project_env` / `user_env` / `legacy_env` / `missing`) without values, plus effective model and timeout from env. It fails when a known first-party plugin secret is missing. Legacy `.env` sources get a migration hint. Deeper authoring rules live in [plugin-development.md](./plugin-development.md). ### Optional: Global install Global install is convenient for interactive use across projects, but local install is preferred for reproducibility. ```bash npm install -g kibi-cli kibi-mcp kibi-core ``` Optional Bun alternative: ```bash bun add -g kibi-cli kibi-mcp kibi-core ``` If `kibi` is not found afterwards, add the directory printed by `npm config get prefix` (plus `/bin` on macOS and Linux) to your `PATH`. ## Local checkout workflow When a workspace is intentionally configured to run Kibi from a local checkout, invoke that checkout's wrapper or binary directly. Do not use `pnpm exec kibi-mcp` in an application repository unless you intend to run that repository's installed `node_modules` version. After changing package versions or local package wiring in a checkout used by another workspace, rebuild before testing or using OpenCode with those local artifacts: ```bash bun run build ``` ## Troubleshooting Installation ### SWI-Prolog Issues Start with `npm exec -- kibi doctor`: it reports which SWI-Prolog Kibi chose, from where, and whether every required library loads. - `could not find a usable SWI-Prolog`: the message names your platform and the platform package that should have supplied it. Add that package (see [If the bundled runtime is missing](#if-the-bundled-runtime-is-missing)), or install SWI-Prolog 9.0+ and put `swipl` on `PATH`, or set `KIBI_SWIPL`. - `The bundled SWI-Prolog package ... is damaged`: reinstall the platform package, or set `KIBI_SWIPL=system` to use `swipl` from `PATH` meanwhile. - `KIBI_SWIPL=... is not an executable file` (or is too old): `KIBI_SWIPL` must be the absolute path of a SWI-Prolog 9.0+ executable, or `system`. Unset it to use the bundled build. - A system SWI-Prolog is installed but ignored: that is the default when the bundled package is present. Set `KIBI_SWIPL=system` to prefer `swipl` from `PATH`. If you need help with SWI-Prolog itself: - Refer to the [SWI-Prolog build documentation](https://www.swi-prolog.org/build/) for platform-specific guidance - Check the [SWI-Prolog FAQ](https://www.swi-prolog.org/FAQ/) - Report issues on the [SWI-Prolog forum](https://swi-prolog.discourse.group/) ## Next Steps 1. Paste the [agent setup prompt](#recommended-agent-led-setup) into your coding agent. It covers steps 2 to 4. 2. Check the environment: `npm exec -- kibi doctor` 3. Initialize the repository: `npm exec -- kibi init` 4. [Connect your coding agent](../docs-site/content/connect-an-agent.md) and ask it to "Bootstrap Kibi for this repository." 5. Open the health report: `npm exec -- kibi report --open` The [CLI reference](cli-reference.md) documents every command, and [Troubleshooting](troubleshooting.md) covers recovery. --- # Connect your coding agent URL: https://getkibi.dev/guide/connect-an-agent.html > Give your coding agent the same Kibi operations you can run yourself, through an MCP server or the kibi CLI. If you used the [agent setup prompt](quick-start.md#2-paste-the-setup-prompt-into-your-agent-recommended), your agent has already done this for its own host; this page is the manual route and the reference for other clients. Once Kibi is installed in the repository, your agent needs a way to call it. Two surfaces expose the same operations: - **MCP server** (`kibi-mcp`) — all 19 tools show up in the client's tool list at Kibi level `test`. At Kibi level `remember`, the `full` profile lists only the knowledge tools (plus bootstrap tools while the KB is empty and impact-review tools when an impact policy is active, omitting `kb_ingest_proof`). With `KIBI_MCP_TOOLS=core` only eight are listed (`kb_search`, `kb_query`, `kb_record`, `kb_upsert`, `kb_check`, `kb_status`, `kb_skills` and `kb_review_firm_edit`), and the others run through the project CLI with the same input. `kb_search` also answers plain questions, such as "what governs checkout rounding?", with decision cards and bundled meaning hints. The [MCP reference](../reference/mcp.md) lists every tool. - **CLI** (`kibi`) — the same operations as JSON on stdin, plus commands you run yourself, such as `kibi report`. Use whichever surface your client can see. You do not configure both unless you want to. > [!TIP] > Antigravity, Claude Code, Cursor, Codex, OpenCode, Mistral Vibe, and ZCode also have optional plugins that wire this up for you. Each plugin shows the agent linked requirements when reading, searching, or editing code, and guards firm requirements, the project's Kibi level, and requirement evidence floors. The JSON below is the manual fallback when you are not using a plugin. Details and plugin install steps are in the [installation guide](install.md). ## Antigravity Install the optional `kibi-antigravity` plugin (bundled skills, always-on workflow rules, workspace-gated MCP server with automatic `roots/list` workspace discovery, and lifecycle hooks for read/search/edit requirement context, firm-edit and level/floor prompts, and stop reminders): ```bash agy plugin install https://github.com/Looted/kibi/tree/master/packages/antigravity ``` Without the plugin, add `npx --no-install kibi-mcp` to `~/.gemini/config/mcp_config.json`. See [Antigravity plugin](install.md#optional-antigravity-plugin). ## Claude Code The `kibi-claude` plugin brings the server, the bundled skills, and hooks that show the agent the linked requirements and tests before it reads or edits code, and before an edit, what those requirements must keep true, why the lead one exists, and the decision behind them. The same context reaches reads and writes the agent makes through shell commands such as `cat`, `sed -i` or a script, and an in-place write such as `sed -i` hears what must stay true before it runs: ```bash claude plugin marketplace add Looted/kibi claude plugin install kibi-claude@kibi ``` Without the plugin, register the server for the project. This writes `.mcp.json`, so the whole team gets it: ```bash claude mcp add --scope project kibi -- npx --no-install kibi-mcp ``` See [Claude Code plugin](install.md#optional-claude-code-plugin). ## Cursor, Codex, and most other clients Add this server to the client's MCP config. The working directory must be the repository where you ran `kibi init`, so the server attaches to that project's `.kb/`. ```json { "mcpServers": { "kibi": { "command": "npx", "args": ["--no-install", "kibi-mcp"] } } } ``` `--no-install` matters. The client starts the `kibi-mcp` already in the project. It does not download a different copy at launch. Plugin pages in the installation guide: - [Antigravity plugin](install.md#optional-antigravity-plugin) - [Cursor plugin](install.md#optional-cursor-plugin) - [Codex plugin](install.md#optional-codex-plugin) - [ZCode plugin](install.md#optional-zcode-plugin) - [Mistral Vibe plugin](install.md#optional-vibe-plugin) ## Mistral Vibe Install the optional `kibi-vibe` plugin from a local checkout, then restart Vibe or run `/reload`: ```bash mkdir -p ~/.vibe/plugins && cp -r packages/vibe ~/.vibe/plugins/kibi ``` The plugin brings the `kibi` MCP server, the bundled skills, and fail-open hooks (KB status at session start, KB hits for each prompt, entities linked to a file after reads/edits). On Windows the launcher runs Kibi natively with the bundled SWI-Prolog, and inside WSL only for a `\\wsl.localhost\` workspace — see [Vibe plugin](install.md#optional-vibe-plugin). Without the plugin, register the server in `~/.vibe/config.toml`: ```toml [[mcp_servers]] name = "kibi" transport = "stdio" command = "node" args = ["/packages/vibe/bin/launch-kibi-mcp.mjs"] startup_timeout_sec = 120 tool_timeout_sec = 300 ``` ## OpenCode OpenCode takes the command as a list of tokens, in `opencode.json`: ```json { "$schema": "https://opencode.ai/config.json", "mcp": { "kibi": { "type": "local", "command": ["npx", "--no-install", "kibi-mcp"], "enabled": true } } } ``` The optional `kibi-opencode` plugin adds prompt guidance, background maintenance and, on OpenCode v1, the decision hooks the other plugins run: a message that states a rule gets a `kb_record` capture template, an edit of code that implements a firm requirement is stopped once so the agent asks the person first, and a session that changed source and recorded nothing is asked once to record the decision. Shell in-place edits count as source edits. It does not replace the server above. See [OpenCode MCP](install.md#opencode-mcp). ## VS Code Create `.vscode/mcp.json`: ```json { "servers": { "kibi": { "type": "stdio", "command": "npx", "args": ["--no-install", "kibi-mcp"] } } } ``` See [VS Code MCP](install.md#vs-code-mcp). ## pnpm or Yarn Keep the same shape and swap in that package manager's local runner. For pnpm, the command is `pnpm` with args `["exec", "kibi-mcp"]`. For Yarn, `yarn` with args `["exec", "kibi-mcp"]`. The [installation guide](install.md#manual-project-local-install) has the full table. ## No MCP? Use the CLI If the agent cannot see MCP tools, it can call the same operations through the CLI: ```bash printf '%s\n' '{"query":"login","limit":10}' | npm exec -- kibi search --input - ``` Agents discover this path from the [agent onboarding snippet](agent-onboarding.md). You do not configure it beyond installing the packages. ## The first prompt After the tools are visible, ask: > Bootstrap Kibi for this repository. The agent first asks where product intent already lives outside the code, such as your issue tracker or wiki, and reads those sources through its other connectors. Connect those tools to the agent too if you want them used. It then shows a read-only plan and a hash, and it waits for your approval before writing. After that, ordinary prompts — features, fixes, refactors — keep the model in step with the code. ## What stays in your hands - **Product calls.** If two behaviors would contradict, you pick one. Kibi will not paper over that. - **Approval of the plan.** Bootstrap and other bulk writes show you the plan before they apply it. A plan compiled from a prompt applies in full or not at all; if the agent is interrupted mid-write, its next write completes or rolls back that plan. - **The report.** You decide whether a gap is work still to do, or a behavior you no longer want. The agent writes the model through typed operations. It does not edit `.kb/` by hand. A change is not finished while checks are failing or the snapshot is stale. --- # How Kibi works URL: https://getkibi.dev/guide/how-it-works.html > The loop from human intent to proven implementation — compilation, deterministic checks, and fresh end-to-end evidence. You do not operate this loop by hand. You prompt, and you approve the decisions that are actually about the product. The rest of this page is what happens after that. Kibi combines two kinds of intelligence on purpose: probabilistic interpretation for understanding, deterministic verification for trust. A large language model is good at reading intent and navigating code; it is bad at remembering, and it will confidently invent things. Prolog is the opposite: it remembers nothing you did not encode, and it never pretends. Kibi wires them together so each covers the other's weakness. ## The loop ```text Human prompt | v Agent updates code and product knowledge | v Requirements + semantic facts/rules + scenarios + tests + symbol links | v Prolog coherence checks + traceability gates + fresh E2E evidence | v Proven result, or explicit and repairable gaps ``` The agent never writes raw logic that gets trusted blindly. It works through typed entities and schemas, and Kibi validates those encodings before the Prolog layer reasons over them. ## What the model contains The project model uses eight entity types — requirements, scenarios, tests, facts, architecture decisions, runtime flags, events, and code symbols — connected by typed relationships. The chain that matters most: ```text Requirement -> Scenario -> Test ^ ^ | | Production symbol Executable test symbol ``` Every production symbol traces to the requirement it implements. Every requirement is specified by scenarios, and those scenarios are verified by tests. The [entity schema reference](../reference/entity-schema.md) has the complete model. ## Why coverage is not proof A coverage number can tell you a test executed a line. It cannot tell you *which product behavior* the test exercised, whether that behavior still matches the intent, or whether the evidence is fresh. Kibi records proof differently: a proof-bearing test declares what it verifies, and its evidence is bound to the current code snapshot. Change the code, and the stale evidence stops counting as proof. That binding uses repository-relative paths and file contents only, so a CI runner and your own checkout of the same commit agree on what is fresh. Each test is judged by its own evidence: when the proof command reports results per test, one failing step fails only the tests that own it, and the run summary names the step. Receipt history keeps only the receipts that can still decide proof, so it does not grow with every run. The agent does not hand-write how proof runs either: `kibi proof inspect --json` proposes an integration for your test runner (or the command you pass with `--command`) and returns a plan you approve, and applying it writes `.kb/proof/integrations.json` for `kibi prove` to run. A plan that can no longer apply, because the file already exists or the runner configuration changed since planning, is refused as an error and changes nothing. A command integration is judged as one run, so a suite with an unrelated failing test proves nothing: narrow the command to the proof-bearing tests, or have it report results per test. That is why the health report distinguishes "tested end to end" from "passing", and labels every requirement with its evidence level: proved, tested, asserted or unverified. Green is reserved for requirements whose evidence is current; everything else is shown honestly as waiting, stale, or broken. ## Two Kibi levels: `remember` and `test` Every project chooses how hard Kibi holds the agent to its recorded requirements ([Kibi level](../reference/cli.md#kibi-level)), recorded in `package.json` (`kibi.level`) or `.kb/setup.json` (`level`): - **`test` (default)** — Everything `remember` does, plus scenarios, linked tests, and fresh end-to-end proofs. `kibi check` and the commit gate run both the `knowledge` and `verification` rule layers. - **`remember`** — Requirements, reasons, code links, read/edit hooks, the firm-edit guard, the commit gate, and contradiction checks, with no scenarios, tests, or proofs required. `kibi check` and the commit gate skip verification rules, requirements with `required_evidence: tested` or `proved` are reported by the non-blocking `required-evidence-above-level` rule, writes raising the floor are refused (`LEVEL_DOES_NOT_CHECK_EVIDENCE`), and the MCP server trims its `full` profile to the knowledge tools (omitting `kb_ingest_proof` and `kibi-provable-code`). Only `kibi init` writes the level (asking interactively, or via `--level remember|test`; changing an existing level non-interactively requires `--change-level`). ## What the checks catch Once a constraint is encoded — say, the product has exactly three user roles — it becomes part of the deterministic world. An agent cannot quietly invent a fourth role and treat it as established intent: the contradiction or missing authorization is surfaced mechanically. The same layer catches dangling references, incomplete semantics, unsupported invention, and requirements that constrain the same subject in incompatible ways. The `kb-consistency` rule of `kibi check` goes one step further: it proves the encoded facts are consistent and the stored rules are stratified, and leaves a certificate for each answer that a small separate checker re-checks without running the search that found it. Facts that contradict only together are caught there, and anything the checker cannot compare is reported as unresolved rather than consistent. Numeric constraints are compared exactly, so "greater than 0" conflicts with "equals 0", and integer values are compared as integers, so "greater than 0" also conflicts with "less than 1". When a requirement still has clauses that are not modeled, the check says the analysis is incomplete instead of reporting no conflict (a plan compiled from new intent does the same: when the intent or a related requirement is prose only, the plan names that requirement for the agent to compare instead of reporting no conflict), and when such a requirement is linked to one that is modeled with strict facts, `kibi check` blocks it until the clauses are modeled against the same subject or the older requirement is superseded. An allow and a deny for the same actor, action and resource contradict, so "coaches can read unassigned requests" and "coaches cannot read unassigned requests" are reported as a pair. Two opposing rules Kibi cannot decide stay unresolved, and when the only missing piece is a `key_arguments` declaration on a predicate, an advisory check names that predicate. A predicate the agent models for a requirement takes the subject key the requirement already constrains, in the argument its schema names `subject` or, for a schema without one such as a permission rule, as the predicate fact's own subject key, so the predicate and the requirement's other facts are checked as one subject; a predicate about another subject is not offered as the requirement's grounding. Scenarios can state the outcome they expect and the facts they assume; one that expects success while assuming values a current requirement forbids, alone or only in combination, is reported and blocks proof, unless an exception requirement that a human approved (`approved_by`) covers it. An exception can be limited to single clauses (`exempts_claims`), so waiving one clause does not waive the others. Conditional requirements are checked the same way: "checkout may happen only when the cart total is positive" (or "must not happen unless") compiles to a typed rule, and a checkout scenario that assumes a zero total is infeasible. A requirement scoped to the EU does not govern a US scenario, and one whose facts carry a validity window only governs scenarios inside it. A success scenario whose feasibility cannot be decided, such as one that assumes a "basket amount" where the rule reads the "cart total", is flagged as unknown rather than passed. A conditional the compiler cannot translate stays an open ontology gap; it is not stored as a note that looks modeled. Entity bodies keep the reasons that front matter cannot hold. A requirement body carries its statement, a `## Context` section (why, who asked, constraints) and a `## Source` section with the verbatim excerpt; scenarios, tests and observations carry prose that says what they cover and how they were confirmed. Context sections never change a requirement's checked meaning, because `semantic_text` is written explicitly. `kibi check` blocks an entity whose body has no real context, and Kibi never invents one: when the reason was not given the body says so. Entities from before this rule are tagged `review:context-missing` by the schema 8 migration and counted in an advisory diagnostic instead of blocking; the migration records them, and the tag does nothing on any other entity, so the way past the check is real context. Every entity can also say who wrote it (`origin`: a human, an agent, a migration or an import) and who approved it. Kibi cannot check that a person really approved something, so it does not try. Advisory checks list exceptions that nobody approved, exception approvals only an agent recorded, and agent-written requirements no one has reviewed. Requirements and ADRs can also say how firmly they were decided (`firmness`): `firm` for a rule a human stated, `default` for a delegated or agent choice, and `exploratory` for a guess. When nothing is said, a decision an agent wrote is `default` and any other (written by a person, imported from their documents, or carried over from an older KB) is `firm`; bootstrap marks the rules it imports as `firm` with a reference to the passage. Search and query show it, so a later agent knows whether it may change the decision on evidence or must ask first. `kibi check` blocks a firm decision that names no human words it rests on (`origin.ref`, or `approval_ref` on a requirement), a decision that is not firm superseding a firm one, a firm decision whose title, statement or ADR body changed since the last commit without new human words (`kb_upsert` refuses such a write up front), and a current requirement or ADR that supersedes another without a `## Why this changed` section naming the evidence. Kibi checks that a firm decision has a reference, not that the reference is genuine. A requirement is replaced through `supersedes`, or, when its behavior is gone and nothing replaces it, retired: `status: retired` with a `retired_reason`. A retired requirement no longer governs search, hooks or checks, and `kibi check` blocks a current fact, scenario or test that only a retired requirement still owns. A `closed` requirement is done and still governs. Supersede edges recorded before these rules are acknowledged once by the schema 9 and 10 migrations instead of blocking; Kibi never writes a reason for them, and a new supersede on the same decision still has to explain itself. Code that implements a current firm requirement is guarded too. Reading or searching linked code (including shell reads such as `cat`, `sed -n`, `head`, `tail`, `grep -n`, and `rg`) surfaces compact requirement rows on every supported host. Before an agent edits firm code, the host plugins prompt you (Claude Code and Antigravity), tell the agent to ask you first (Codex, Cursor, ZCode, and OpenCode v1, which stops the first attempt once), or warn right after the edit (Mistral Vibe). The commit gate does not rely on that: `kibi check --staged` refuses a change inside such code (`firm_edit_unreviewed`) until the agent records its verdict for each edited symbol with `kb_review_firm_edit` (CLI `kibi review-firm-edit`). A `keeps` receipt, bound to the requirement's statement and the symbol's code, says the change still does what the rule says and clears the gate; a `changes` receipt keeps the change blocked until the requirement is superseded with your words. A receipt is the agent's judgment, not your approval, and `kibi signoff` lists each one as such so you can check it. Two settings are yours alone: the project's Kibi level (`kibi.level` in `package.json`, or `level` in `.kb/setup.json`) and how much evidence a requirement must reach (its `required_evidence` floor). When an agent changes the level or lowers a floor, the host plugins put it to you the same way: Claude Code and Antigravity show a permission prompt, Codex, Cursor and ZCode tell the agent to ask you first, OpenCode stops the change once, and Vibe tells the agent afterwards to ask you and undo it unless you agree. `kibi signoff` lists both under "Decisions only you make". Code that no symbol links to a requirement yet is not treated as ungoverned. Before such a file is edited, and in a `kb_check` scoped to it, Kibi names the current requirements whose titles share the file's path words, so an agent changing `coach-dashboard.html` is pointed at "The coach inbox must list the analysis requests assigned to the coach." even though nothing in the page is linked to it yet. Recording the behavior a change adds (a requirement, a scenario and an implements link) is part of finishing that change, and Kibi tells the agent so: it records it without asking and asks only when the change conflicts with a recorded rule. Linked code is not proven code either. Kibi's checks compare links, coverage and facts, never the code with what a requirement says, so after an edit `kb_check` quotes the statement and firmness of every requirement the changed code implements and reports "no structural violations" rather than "no violations". If the change no longer does what a quoted requirement says, the agent has a conflict with a recorded rule to put to you, not a passing check. Prolog verifies the knowledge that was encoded. It does not decide whether the original intent was correct — that stays with you. Ambiguity and ontology gaps stay explicitly visible rather than silently resolved. ## Knowledge that follows your branch The model lives in your repository under `.kb/`, and each Git branch carries its own snapshot. Feature work gets its own isolated project state; switching branches switches context with it. Kibi compiles each branch's snapshot from that branch's own files and never copies another branch's; a branch created without Kibi's Git hooks starts uncompiled, and `kibi status`, `kibi check` and `kibi doctor` (and `kb_status` and `kb_check` over MCP) say so once and point at `kibi sync`. Because the model is reviewed and committed like code, its history is your project's history. Outside a Git repository, Kibi still works on a single local store (without Git hooks or the commit gate) and carries that store onto the new branch automatically once you run `git init` and `kibi init` ([working without Git](../reference/errors.md#working-without-git-no_git_repository-git_required)). ## Knowledge from the repositories you depend on A project can read the KB of another repository it builds on, such as a library or a service it calls. List the repository and a tag, branch or commit in `.kb/dependencies.json`, and `kibi deps lock` pins it to a commit in `.kb/dependencies.lock.json`, which you commit. Reads named with `kb` (MCP) or `--kb` (CLI) are answered from that repository's own KB at the pinned commit. It is a read-only copy kept in a shared cache outside your repository, it never mixes with your KB or slows your own checks, and the other repository can stay on an older KB schema until it chooses to upgrade. The [CLI reference](../reference/cli.md#kibi-deps-lockfetchstatus) has the file format. ## Go deeper - [The proof ladder](proof-ladder.md) — the stages from stated intent to a tested requirement, the evidence levels, and knowledge-base certificates. - [Architecture](../reference/architecture.md) — storage, branch isolation, and data flow. - [Inference rules](../reference/inference-rules.md) — the deterministic checks themselves. --- # Read the health report URL: https://getkibi.dev/guide/reading-the-report.html > How to open the requirement-health report and what tested, an evidence level, a proof gap, stale evidence, and a contradiction mean. The health report is the page you read. It is a single HTML file generated from one coverage snapshot. It does not call a server, and it does not fetch fonts or images. ## Open it From the repository root: ```bash npm exec -- kibi report --open ``` That writes `kibi-report/index.html` and `kibi-report/badge.svg` together, then opens the HTML file. Use your package manager's local runner if you are not on npm (`pnpm exec kibi report --open`, `yarn exec kibi report --open`). ## The number at the top The score is a count, not a mood: > 4 of 11 current requirements fully tested end-to-end The percentage is that fraction. The numerator is requirements with fresh end-to-end evidence on this code. The denominator is current requirements. An honest zero on the day you bootstrap is a working report. > [!NOTE] > A passing test suite, a coverage percentage, and an old receipt are not this number. The report keeps those facts separate from proof. ## What the page is showing you Each requirement sits on a ladder. The report names the earliest thing still missing, and it totals these across the branch: - **Fully tested** — a test that claims this requirement has fresh end-to-end evidence for the current code snapshot. A requirement that only names a UI pattern counts as tested with a fresh isolated component test instead. - **Proof gap** — the chain is incomplete. Typical gaps are a missing scenario, incomplete semantics, or evidence that was never recorded. - **Stale evidence** — a receipt exists, and the code has moved since. It stops counting as proof until the test is run again. - **Contradiction** — two encoded claims about the same behavior disagree. Kibi will not pick a winner. - **Unowned production symbols** — code the model does not yet connect to a requirement. Next to each requirement id is its **evidence level**, the strength of what backs it: - **proved** — every claim of the requirement holds for every case, backed by fresh certificates a separate checker re-checks. Certificates come from the `exhaustive`, `typecheck`, `arithmetic`, `smt`, `rule`, `state_machine`, `regex` and `source` proof kinds; see [proving requirements](proving.md#certificate-proof-kinds). - **tested** — fresh end-to-end evidence, as above. Tests sample cases; they do not cover all of them. - **asserted** — a person stands behind the statement, but nothing current checks it. - **unverified** — an agent wrote it and no person has approved it. The summary counts the asserted and unverified requirements, because those are the ones you are trusting on someone's word. Color repeats the word. Do not read status from color alone. ## What you do with a row | What you see | What you do | | --- | --- | | Fully tested | Nothing, until the code changes. | | Asserted or unverified | Ask the agent for a test, or approve the requirement if it states what you want. | | Proof gap | Ask the agent to close that gap, or decide the behavior is not a requirement. | | Stale evidence | Re-run the test that claims to prove it. | | Contradiction | You choose which claim is the product. The agent updates the model. | | Unowned symbol | Ask the agent which requirement that code implements, or whether it should. | You do not edit the report. The next `kibi report` rebuilds it from the repository. ## Go deeper - [The proof ladder](proof-ladder.md) — the stages a requirement climbs before it counts as tested, and the evidence levels. - [Publish requirement health](github-integration.md) — put this report and its badge on GitHub Pages. - [Quick start](quick-start.md) — generate the report for the first time. --- # The proof ladder URL: https://getkibi.dev/guide/proof-ladder.html > From a stated requirement to fresh end-to-end evidence: the stages a requirement climbs to count as tested, and how strong its evidence is. Consumer-facing reference for `proofStatus`, `proofStages`, `proofGaps`, and `proofAdvisories` as reported by `kibi coverage --by req` and `kb_coverage`. The authoritative implementation is `packages/core/src/requirement_proof.pl` (proof version `kibi.requirement-proof.v5`); this document explains what each stage means and what to do when it does not pass. ## Applicability: is the requirement in scope at all? The ladder only evaluates **current** requirements. A requirement is current when its `status` is one of: - Canonical: `open`, `in_progress`, `closed` - Legacy (accepted for backwards compatibility): `active`, `approved` Everything else is out of scope by design. Three things can take a requirement out of scope: 1. **Supersession** — a newer requirement links to it with `supersedes`. 2. **Retirement** — `status: retired` with a `retired_reason`: the behavior is gone and nothing replaces it. The applicability reason reads "requirement is retired: the behavior it stated no longer exists". 3. **Status outside the vocabulary** — e.g. the ADR vocabulary `accepted`. Since that silently excludes the requirement from proof, `kibi check` reports it as a blocking `req-status-vocabulary` violation instead of letting it hide. Out-of-scope requirements report: ```json { "proofStatus": "not_applicable", "proofGaps": [], "proofStages": { "applicability": { "status": "not_applicable", "reason": "status 'accepted' is not a current requirement status" } } } ``` The typed `reason` is what `not_applicable` used to hide: superseded requirements say so; status-vocabulary mismatches name the offending status. ## Proof exemption: current but intentionally not E2E-provable Some current requirements cannot be proven by end-to-end evidence — toolchain-currency gates, architectural boundaries, quality-gate policy. Parking them with an ADR status is exactly the trap above. Instead, mark them explicitly in the requirement document: ```markdown --- id: REQ-TOOLCHAIN-001 status: open priority: must proof_exempt: true proof_exempt_reason: architectural boundary — verified by toolchain CI, not product E2E --- ``` `proof_exempt` requires a non-empty `proof_exempt_reason` (upsert validation enforces the pairing, and the ladder ignores an exemption without a reason). Exempt requirements report `not_applicable` with the author's reason attached, so coverage can distinguish "cannot be proven" from "not proven yet". To re-enter the proof ladder, remove both properties. ## The stages For in-scope requirements the ladder evaluates the stages below, in order. Each stage reports a `status` under its key in `proofStages`; `productionSymbols` also carries a typed `reason` when it does not pass. | # | Stage | Key in `proofStages` | | --- | --- | --- | | 1 | [Semantic inventory](#1-semantic-inventory) | `semanticInventory` | | 2 | [Logic grounding](#2-logic-grounding) | `logicGrounding` | | 3 | [Contradictions](#3-contradictions) | `contradictions` | | 4 | [Scenarios](#4-scenarios) | `scenarios` | | 5 | [Scenario tests](#5-scenario-tests) | `scenarioTests` | | 5a | [Failure side](#5a-failure-side) | `negativePath` | | 5b | [Quantified claims](#5b-quantified-claims) | `dimension` | | 5c | [Edge cases](#5c-edge-cases) | `cases` | | 6 | [Passing E2E tests](#6-passing-e2e-tests) | `passingE2e` | | 7 | [Executable test symbols](#7-executable-test-symbols) | `executableSymbols` | | 8 | [Production symbols](#8-production-symbols) | `productionSymbols` | | 9 | [Source coordinates](#9-source-coordinates) | `sourceCoordinates` | ### 1. Semantic inventory **Checks:** every assertive statement in the requirement's prose is listed in its semantic inventory and classified as modeled, unresolved, missing or nonlogical. - `passed`: the inventory is complete and nothing in it is unresolved. - `missing`: there is no inventory, an entry is classified as missing, or an entry is malformed. - `unresolved`: at least one statement is classified as unresolved. ### 2. Logic grounding **Checks:** each modeled claim is grounded by a strict property, predicate or safe rule fact, one to one with the declared manifest. - `passed`: every modeled claim has exactly one grounding fact. - `missing`: a claim has no grounding fact or no manifest entry. - `unresolved`: the grounding exists but does not line up (an extra or duplicate manifest entry, claim text that differs, an invalid or undeclared fact, an unsafe rule). ### 3. Contradictions **Checks:** no other current requirement contradicts this one over shared facts. - `passed`: no conflict was found and grounding is complete. - `blocked`: a conflict was found; `conflicts` names it. - `unresolved`: the check could not finish, usually because logic grounding is incomplete, so the absence of a found conflict is not evidence of safety. ### 4. Scenarios **Checks:** at least one scenario specifies the requirement (`specified_by`). - `passed`: one or more valid scenarios are linked. - `missing`: no scenario is linked, or a link points at a scenario that does not exist. - `blocked`: a linked success scenario is infeasible; `infeasibleScenarios` names it. ### 5. Scenario tests **Checks:** each linked scenario is validated by at least one test (`verified_by` or `validates`). - `passed`: every scenario has a test. - `missing`: a scenario has no test, or links a test that does not exist. ### 5a. Failure side **Checks:** a requirement that grounds a claim (a `requires_property`, `requires_predicate` or `requires_rule` fact) is not tested through its happy path alone. At least one linked scenario must expect `rejection` or `error` and assume a value or situation the requirement forbids: either the scenario-feasibility analysis finds a witness naming the requirement, or one of its `assumes` facts opposes one of the requirement's claim facts directly (a conflicting value or polarity on the same subject and property, the opposite polarity of the same predicate, or, for a rule over predicates, a predicate fact instantiating one of the rule's atoms). For a guarantee rather than an input constraint, the assumed fact describes the attempt to break the guarantee, and `rejection` means the system refuses or contains it. - `passed`: `negativeScenarios` lists the linked scenarios that do this. - `missing`: none does; the requirement gets the `happy_path_only` gap, and `suggestedNegatives` gives, per open claim, a fact that opposes it (the value just past a numeric bound, the other boolean, a different string, a set missing a required member, the opposite polarity of a predicate). - `not_required`: the requirement grounds no claim, or a fresh certificate proves every claim at code scope (`certifiedClaims`): a certificate decides both sides of the claim already. When every open claim is proved by a certificate test whose receipt is only older than the code (`pendingReproofClaims`), the evidence floor reports `pending_reproof` rather than `below`, as for any other stale receipt. - `waived`: the requirement has no failure side to test. Its claims state a capability or an output shape, so there is no input or attempt to refuse. The requirement records why in `failure_side_waiver` and who accepted it in `failure_side_waiver_approved_by`, and `waiver` shows both. A reason without an approver stays `missing`, and `kibi proof explain` reports the waiver as awaiting approval. The negative scenario needs a test like any other linked scenario, so the failure side is proven by the same passing E2E receipts. The canonical `scenario-outcome-mismatch` check rule reports a scenario that expects rejection or error while current requirements govern and permit everything it assumes. ### 5b. Quantified claims **Checks:** a claim that quantifies over a collection (`each`, `every`, `all`) or bounds a cardinality (`exactly`, `at least`, `at most`, `no more than`) is grounded on what varies, not only on its verdict. When every fact grounding such a claim is a boolean `property_value` or a ground `predicate`, the claim states that the behavior holds without naming the dimension it holds over, and a scenario with one item can pass where several items break. Ground it on an integer count or bound, a set of members, a rule over a variable, or a state machine instead. `only`, `any` and `some` are not counted: they mostly scope a condition ("only when", "before any write") rather than range over one. - `missing`: `claims` lists each such claim with its `quantifier`, the grounding `factIds`, and `rewrites`, the typed groundings that would represent it, likeliest first (`bound` for a cardinality; `rule`, `count` or `set` for a collection). The requirement gets the `dimension_unrepresented` gap. - `not_required`: no grounded claim is quantified this way, or a fresh certificate proves the claim at code scope. Stale certificate receipts are reported as `pendingReproofClaims`, as in the failure-side stage. - `waived`: every such claim has an approved waiver. When the quantifier word ranges over nothing ("start without all network access"), the grounding fact records why in `dimension_waiver` and who accepted it in `dimension_waiver_approved_by`; `waivedClaims` lists them. A reason without an approver keeps the claim in `claims`, and `kibi proof explain` reports it as awaiting approval. `kb_semantic_advisor` marks the same clauses: each normative proposition with such a quantifier carries `dimension` with its `quantifier` and `rewrites`, so the grounding can be chosen before the fact is written. ### 5c. Edge cases **Checks:** every value class a typed property claim predicts is refused has a scenario that reaches it. Kibi derives the cases from each `property_value` fact the requirement grounds a claim on with `requires_property`: - a numeric bound yields the bound itself (or the nearest value inside a strict bound) and the class past it: `files_per_batch lte 5` gives `eq 5` (success) and `gt 5` (rejection); - an integer bounded at one or more also yields zero, one and many (`eq 0`, `eq 1`, `gte 2`), keeping only the classes that fall wholly on one side of the bound; - a set yields each member (success) and the value outside it: rejection for `eq` and `subset_of`, `unspecified` for `includes`; each member of an `excludes` set is a rejection case. A case is dropped when an earlier one already names its class with the same outcome, and one fact yields at most 12 (`limitReached` says when the cap cut). Each case has a stable `caseId` (`CASE-` and 12 hex characters) and the `assumption` a scenario would state to land in it. A case is covered by a scenario of the requirement that is not a draft, whose `expects` matches the prediction (`rejection` also accepts `error`), and whose `assumes` fact on the same subject and property entails the case: `files_per_batch eq 6` covers `gt 5`. Success cases are reported but do not block; the requirement's success scenarios already exercise them. - `missing`: a rejection case is uncovered; `uncoveredCases` lists them and the requirement gets the `uncovered_case` gap. The repair plan's `case_scenarios` phase carries `caseSkeletons`, an upsert-ready draft scenario and assumed fact per case: fill in any placeholder value, verify the scenario by a test and make it active. - `passed`: every rejection case is covered. - `not_required`: no grounded claim predicts a rejection case, or a fresh certificate proves the claim at code scope. Stale certificate receipts are reported as `pendingReproofClaims`. - `waived`: the uncovered rejection cases all belong to facts with an approved waiver. When the cases are covered another way (a unit suite that walks every value, a class the system cannot produce), the grounding fact records why in `case_waiver` and who accepted it in `case_waiver_approved_by`. A reason without an approver keeps the gap. `kibi coverage --cases` lists every requirement's cases with their coverage, and `kibi proof explain` prints the assumption each uncovered case needs. `kb_semantic_advisor` previews the cases of each strict-property suggestion in `casesPreview`, so the scenario debt shows before the fact is written. ### 6. Passing E2E tests **Checks:** every linked scenario has at least one end-to-end test, and every linked E2E test that bears proof carries a valid, fresh, passing `kibi.proof-receipt.v1` receipt bound to the current snapshot, contract hash and fingerprint. - `passed`: every scenario obligation passed. - `missing`: a scenario has no qualifying E2E test or receipt. - `unresolved`: the evidence exists but does not qualify (for example a stale, failed or invalid receipt). Per-scenario results are in `scenarioObligations`, each with the `acceptedScopes` it allows. Unit and integration tests linked alongside the E2E tests do not block. A UI pattern scenario also accepts component tests; see [Component-scope proof](#component-scope-proof-for-ui-patterns). ### 7. Executable test symbols **Checks:** each qualifying E2E test is linked to executable test code with `executable_for`. - `passed`: every qualifying test has executable code linked. - `missing`: a test has no `executable_for` link; `missingTests` lists it. - `blocked`: there are no passing E2E tests to check. ### 8. Production symbols **Checks:** the production symbols that implement the requirement are covered by the passing E2E tests (`covered_by`). - `passed`: every production symbol is covered, or no symbol implements the requirement and a passing source proof proves every applicable claim (`scope: source_proof`, below). - `missing`: no production symbol implements the requirement and source proofs do not prove every applicable claim, or some symbols lack `covered_by` links; `uncoveredSymbols` lists them. - `blocked`: there is no passing E2E evidence in the current snapshot (usually stale or missing receipts), so coverage cannot be evaluated. `reason` says so and points at `kibi prove`. Type-shape symbols (interfaces, type aliases, enums) are listed under `structuralSymbols` instead. One counts as covered when it is `covered_by` a passing E2E test or a unit test with a current passing receipt; an authored `status: passing` on the unit test is not enough. Without that receipt the symbol is in `uncoveredSymbols` with the reason `structural_unit_receipt_not_current`, and `kibi prove` on the unit test (or `kibi prove --stale`) clears it. A rule about what a set of files never does ("files under `src/ui/` never import `x`") has no function that decides it, and an `implements` link to one of the files would claim that one file implements the rule. Such a requirement needs no implementing symbol: when every applicable claim has a derived binding of scope `source` from a passing receipt whose certificate re-checks, the stage passes with `scope: source_proof` and names the proving tests in `sourceProofTests`, because the files the proof reads are what the rule constrains. A claim bound only by another proof kind, or not bound, still needs an implementing symbol, and a requirement that some symbol implements is judged as above. See [Proving requirements](./proving-requirements.md). `explanations[]` gives each symbol a rollup reason and, for each rejected `covered_by` candidate, a primary rejection code plus optional secondary codes. See [Stage statuses, precisely](#stage-statuses-precisely). ### 9. Source coordinates **Checks:** the requirement source and every linked test and production symbol carry exact published coordinates. - `passed`: all coordinates are present. - `missing`: the requirement has no source, or a symbol has no coordinates; `missingSymbols` lists them. - `blocked`: there are no linked symbols to check. ### Component-scope proof for UI patterns A scenario whose specifying requirements are all grounded only in the built-in UI pattern predicates (`ui_pattern`, `same_pattern`, `pattern_marker`, each linked with `requires_predicate`, and no `requires_property` or `requires_rule`) accepts tests with `verification_scope` `unit` or `integration` as well as `end_to_end`. Such a test still needs a valid, fresh, passing receipt, `executable_for` code, and `covered_by` links for the production symbols it proves. Its obligation reports `acceptedScopes: [unit, integration, end_to_end]`; every other scenario reports `[end_to_end]`. The reason is cost, not leniency: a pattern ("this list is a line-and-dots timeline in both variants") is fully observable by rendering one component in isolation, so demanding a browser test per pattern would make E2E suites heavy for no extra evidence. The moment the requirement also carries a layout fact such as `ui_container`, a strict property or a logic rule, the scenario goes back to end-to-end proof. See [ui-requirements.md](./ui-requirements.md). ### Stage statuses, precisely - `passed`: the stage's obligations hold. - `missing`: the evidence is absent. The stage names what is missing (`missingTests`, `missingReceiptTests`, `uncoveredSymbols`, `missingSymbols`, ...), and `proofGaps` carries the blocking gap code. - `unresolved`: evidence exists but is not conclusive (for example unresolved statements in the inventory, or a stale receipt). - `blocked`: the stage found a hard stop or has nothing to evaluate: - `contradictions`: a conflicting requirement was found. - `scenarios`: a linked success scenario is infeasible. - `executableSymbols` and `productionSymbols`: there is no passing E2E evidence in the current snapshot (typically stale or missing receipts). `productionSymbols` says so in `reason`; `uncoveredSymbols` still lists every remaining production symbol, and each explanation uses `stage_blocked_no_passing_e2e` rather than implying the symbol itself lacks `covered_by`. - `sourceCoordinates`: there are no linked symbols to check. `explanations[]` on `productionSymbols` never changes `status`, `reason`, `uncoveredSymbols` or `proofStatus`. A rejected `covered_by` candidate carries the earliest disqualifying `reason` and optional `secondaryReasons` already known from cheaper checks. Tests outside the scenario chain do not have their receipts read. A `blocked` stage never silently counts as passing. A blocked `contradictions` stage makes `proofStatus` `unresolved`; any other blocked stage does the same unless another stage is `missing`, in which case `proofStatus` is `missing`. ## Gaps, advisories, and status - `proofGaps[]` — blocking only. Every entry carries a code (e.g. `missing_proof_receipt`, `missing_production_symbol_coverage`), a priority, a stage name, and a suggested repair action. - `proofAdvisories[]` — explicitly non-blocking context. Receipt-completeness codes (`missing_proof_receipt`, `stale_proof_receipt`, `failed_proof_receipt`, `invalid_proof_receipt`, and `proof_contract_mismatch`) remain blocking for every linked E2E obligation; they are never downgraded because another scenario has a passing receipt. - `proofStatus` — the headline: - `tested` — all stages passed (`proofGaps` is empty by invariant). Until `kibi.requirement-proof.v4` this value was `proven`; it was renamed because passing end-to-end tests are evidence, not proof. - `missing` — at least one stage is `missing` (evidence absent). - `unresolved` — evidence is inconclusive or a stage is `blocked`. - `not_applicable` — out of scope; see applicability above. - `proofRepairs[]` — ranked concrete recovery actions derived from blocking gaps. ## Evidence levels `proofStatus` says how far a requirement climbed the ladder. `evidenceLevel` says how strong the evidence behind it is, and is never stronger than what backs it: | Level | Meaning | What earns it | | --- | --- | --- | | `proved` | A checker established every claim of the requirement for every case and left certificates a second program can re-check | `proofStatus: tested`, and every applicable claim has a derived, code-scope binding: a fresh `kibi.proof-receipt.v2` of a certificate-kind contract (`exhaustive`, `typecheck`, `arithmetic`, `smt`, `rule`, `state_machine`, `regex`, `source`) that names the claim in `proves`, whose certificate re-checks now against the obligation Kibi derives from the claim's fact (see [Binding a certificate to claims](proving-requirements.md#binding-a-certificate-to-claims)) | | `tested` | Passing runs on sampled cases, bound to the current code snapshot | `proofStatus: tested` | | `asserted` | A person stands behind the statement, but nothing current checks it | `origin.approved_by`, or firm: `firmness: firm`, or no `firmness` and an origin other than `agent` | | `unverified` | Stated, not approved, no evidence | Nothing: an agent wrote it and no person approved it | Each row's `evidence[]` lists the entries that earned the level, each with `kind` (`certificate`, `e2e`, `human_intent`), `scope` (`code` for what the tests exercised, `intent` for what a person stated) and `level`; an `e2e` entry names its passing `tests`, a `certificate` entry its proved `tests` and their proof `kinds`, a `human_intent` entry its `basis` (`approved` or `firm`) and, when there is one, the `ref` to the person's words. The coverage summary counts rows per level under `evidenceLevels`. From `kibi.requirement-proof.v5` each row also judges its claims one by one. `claimEvidence[]` has an entry per inventory claim with its `claimKey`, `status`, whether it is `applicable` (a nonlogical context span is not), the `level` it reaches and the certificate `bindings` behind it (`derived`, `attested` or `rejected`, with the test, kind, scope and reason); `claimSummary` counts the applicable claims per level (`proved`, `attested`, `tested`, `unresolved`) and `unprovedClaims` lists those below proved. A claim is proved only through a derived binding with scope `code`; an attested binding (the fact has no derivation) and an intent-scope one (an arithmetic claim decided from the facts alone) count as tested. The coverage summary adds the claim totals under `proofClaims`. Firmness and evidence level are separate axes. Firmness says how sure the person is; the level says how strong the evidence is. A firm requirement at `asserted` is the gap to close before relying on it. ## Evidence floors Each current requirement also has a floor: the weakest evidence level it accepts. The `evidence-floor` rule of `kibi check` fails while a requirement's level is below its floor, so a regression is caught on the requirement itself and no shared snapshot file has to be kept in step. | Floor | Where it comes from | | --- | --- | | `required_evidence: proved \| tested \| asserted \| unverified` | Set on the requirement by its author | | `tested` | No `required_evidence` and the requirement is firm (`firmness: firm`, or no `firmness` and an origin other than `agent`) | | `tested` | No `required_evidence`, no `firmness`, and a person approved the requirement (`origin.approved_by`), from KB schema 15 | | `unverified` (no floor) | No `required_evidence`, not firm and not approved, or approved with an explicit `firmness: default` or `exploratory` | Coverage rows carry the floor as `evidenceFloor` with `required`, `source` (`explicit`, `firmness` or `approval`) and `status`: `met`, `below`, or `pending_reproof` when the floor is `tested` and every gap only says the receipts are older than the code. A plain `kibi check` lets `pending_reproof` pass, so a local check catches grounding, contradiction and link regressions without re-proving first. `kibi check --fresh-evidence` judges receipts as they are and also needs a clean proof snapshot; run it right after `kibi prove`, as CI does. The coverage summary counts current requirements with a floor under `evidenceFloors` (`met`, `below`, `pendingReproof`), the coverage table has a Floor column, and `kibi report` and `kibi signoff` show each requirement's floor and whether it is met. Requirements outside proof scope (`proof_exempt`, superseded or not current) have no floor. Lowering a floor is a visible edit to the requirement, so reviewers see it; give the reason in the requirement when you lower one. The schema 11 upgrade (`kibi migrate --yes`) records `required_evidence: asserted` on each current firm requirement that has no scenario verified by an end-to-end test with a proof contract and a passing receipt, since it has not reached `tested`; raise it once the requirement has an end-to-end proof. Firm requirements whose proof has passed keep the `tested` floor, and the migration lists them. Their proof can still have gaps it does not read, such as a stale receipt or a production symbol without `covered_by`, so run `kibi check --rules evidence-floor` after migrating and fix what it reports. The schema 15 upgrade does the same for approved requirements: an agent's requirement that a person approved and that states no `firmness` now needs `tested`, so `kibi migrate --yes` records `required_evidence: asserted` on each current one without a passing proof path and lists the ones that keep the `tested` floor. Remove the pin once the requirement has an end-to-end proof. One more rule reads the same requirement proofs: `agent-requirement-unapproved-implemented` (canonical, KB schema 15) blocks a current `priority: must` requirement whose `origin.kind` is `agent`, that production symbols implement, and that nobody has approved (`origin.approved_by`) more than 14 days after it was written: shipped behavior must not rest on a requirement no person confirmed. The age comes from authored data only: `origin.recorded_at` (every `kb_upsert` write records it), else a `created_at` the requirement's front matter states; a requirement with neither counts as older. So does one whose date is not an ISO 8601 date (`yesterday`, `2026-13-45`) or lies more than a day in the future: the finding names the unusable date, and its evidence carries `sinceProblem: not-a-date` or `future`. `kb_upsert` refuses such a `created_at` or `origin.recorded_at` on a requirement, so an agent cannot keep its own requirement out of review with a date. The stored `created_at` is not read, because sync fills a missing one with the sync time. The schema 15 upgrade (`kibi migrate`) lists the agent's must requirements this rule can fail right away. The schema 12 upgrade binds certificates to claims. `kibi migrate --yes` pins `proves` on each certificate-kind contract whose test reaches exactly one claim its kind can prove and lists the other contracts for review. Until a contract names its claims, the blocking `proof-contract-claims` rule reports it and its certificate proves nothing, so a requirement that reported `proved` before reports `tested` until its claims are bound and re-proved with `kibi prove`. ## Knowledge-base certificates Evidence levels describe requirements. The `kb-consistency` rule of `kibi check` (and `kb_check`) covers the knowledge base itself: it states a few theorems about the facts current requirements name, finds a certificate for each, and re-checks every certificate with a separate checker (`certificate_check.pl`) that never searches and never loads the code that found the certificate. | Theorem | Certificate when it holds | Certificate when it fails | | --- | --- | --- | | `properties_consistent` | A model per subject, property and scope: one value that satisfies every fact (a `forbid` fact counts as its negation) | An irreducible core: facts that admit no value together, with one model per dropped fact to show each is needed | | `predicates_consistent` | A truth value per ground atom that every fact agrees with | Two facts that assert and deny the same atom | | `decisions_consistent` | One allow or deny per decision key | Two facts with opposite effective decisions | | `rules_stratified` | A stratum number per rule predicate: a head is at least its body's stratum, and above it across `not` | A negation cycle: a closed path of rule dependencies with a negated edge | The property theorem is joint: facts that contradict only together, where every pair still admits a value (for example `int >= 0`, `<= 1`, `!= 0`, `!= 1`), are a contradiction here even though the pairwise `domain-contradictions` rule is silent. A core whose facts are never valid at the same time is reported as `property_unresolved`, not as a contradiction. A context the checker cannot compare (mixed value types or units, an operator other than `eq`/`neq` on a non-numeric value, an unknown polarity) is unresolved and needs no certificate; it never counts as consistent. A re-verified contradiction (a core, two disagreeing facts or a negation cycle) is a blocking `kb-consistency` violation, and so is a certificate the checker rejects. An unresolved context is a non-blocking `kb-consistency-unresolved` diagnostic. `kibi check --staged` runs the rule too, so a commit that introduces a joint contradiction is blocked. Opposing rule pairs and scenario feasibility are not certified yet; their own `kibi check` rules still decide them. Certificates are regenerated on each run and are not committed: `kibi check --write-certificates ` saves the bundle, and `kibi check --certificates ` re-checks a saved one and prints each theorem's verdict (`proved`, `disproved` or `unresolved`). ## The numeric decision procedure, proved Numeric contradictions, the arithmetic certificate kind and the property theorem above all rest on `intervals.pl`, which folds every comparison on a variable into an interval (open or closed ends, excluded points) or, for an integer variable, an integer range, and asks whether it is empty. The Lean 4 project in [`proof/lean`](../proof/lean/README.md) defines the same folds and proves: | Theorem | Statement | | --- | --- | | `realFeasible_iff` | The real fold is true exactly when some value satisfies every constraint | | `intFeasible_iff` | The integer fold is true exactly when some integer satisfies every constraint, whatever (fractional) values they compare with | | `satisfiable_iff` | `numeric_constraints_satisfiable/2` is true exactly when one assignment, integral on the integer variables, satisfies every constraint | | `entailed_iff` | `numeric_constraint_entailed/3` is true exactly when every such assignment that satisfies the premises satisfies the claim | The proofs hold for any dense linear order without endpoints that embeds the integers with a floor and a ceiling, so for the rationals and the reals, and rest on Lean's standard axioms only (CI fails on `sorry`). The rationals the model's executable computes with are proved to be such an order, so the theorems cover the executable itself. A proof about a model says nothing about the shipped code unless the two compute the same thing, so `scripts/intervals-differential.ts` decides 200000 generated cases (rationals, integers and floats) with `intervals.pl` on the bundled SWI-Prolog, with the Lean model's executable and with an independent CLP(Q)/CLP(FD) oracle, and fails on any disagreement. `intervals.pl` rejects a NaN or infinite bound with a domain error. Both run in CI (`lean-intervals-proof`) and as the proof of `REQ-kibi-intervals-verified`. ## Common failure patterns | Symptom | Usual cause | Fix | | --- | --- | --- | | `productionSymbols: blocked` | No passing E2E receipts in the current snapshot at all | Run `kibi prove` to refresh receipts, then re-check | | `missing_symbol_coordinates` gap | Symbol has no coordinate entry; often `granularity_reason` missing so the coarse fallback was gated off | `kibi sync --refresh-symbol-coordinates` reports failed ids and reasons; add `symbol_role`/`granularity_reason` where the reason says to | | Requirement missing from proof reports entirely | Non-current status or supersession | Coverage `--status not_applicable --by req` lists it with the typed applicability reason | | `passingE2e.scenarioObligations` has a non-passed status | A linked scenario has no E2E test or one of its E2E proof-bearing tests lacks qualifying evidence | Inspect the scenario's `gaps`, repair every listed receipt, and run `kibi prove` | ## Related surfaces - `kibi coverage --by req --status missing` (also: `tested`, `unresolved`, `not_applicable`) — enumerate exactly one proof-status slice; N/A rows include their applicability reason. The summary always reflects the whole KB. - `kibi proof inspect` — detect test infrastructure, propose a proof integration, and return the reviewed plan that writes `.kb/proof/integrations.json` through `kb_apply_plan`. - `kibi proof explain REQ-*` / `kibi proof explain SYM-*` — project the same Proof, labeling `required_proofs`, `executable_for`, and `covered_by` separately. - `kibi check --rules evidence-floor` — fail every current requirement whose evidence level is below its floor (see [Evidence floors](#evidence-floors)). Without `--fresh-evidence`, gaps that only reflect stale evidence (`stale_proof_receipt`, `proof_contract_mismatch`, and production coverage whose symbols all have a qualifying candidate or a scenario-backed E2E candidate rejected solely for stale evidence) count as pending re-proof, so a local run catches semantic regressions without re-proving. Unit or integration scope, missing receipts, invalid evidence, and scenario-chain failures stay blocking. - `bun run proof:gate` (this repository) — the integrity rules plus `evidence-floor`, as the pre-push hook and the KB merge workflow run them; CI runs it again with `--fresh-evidence` after `kibi prove --all`. - `bun run proof:replay` (this repository) — replay the CI proof job's gate steps from `.github/workflows/proof.yml` in a clean clone of the committed HEAD, outside the repository tree, and stop at the first failing step. - `kibi proof compact` — one-off: drop receipts that can no longer decide proof from a store written before `kibi prove` compacted histories on ingest. Coverage decisions are unchanged. - `kibi proof prune --keep 1` — keep only the newest receipt per test, whether or not older ones still decide proof. - `kibi proof migrate-legacy` — remove legacy `verification_receipts` blocks from tests that already carry a `proof_contract`. - `docs/proving-requirements.md` — the runner-neutral proof pipeline: contracts, integrations, artifacts, and how `kibi prove` produces receipts. Before pushing, run `kibi sync` with the project-local CLI (it keeps the gitignored symbol coordinates current), commit, and run `bun run proof:prepush`. If committing leaves the KB stale, sync it again before the check. This checks the committed manifests, publish metadata (including exact GitHub owner casing), and evidence floors (`scripts/proof-gate.sh`) using the project-local CLI. When proof contracts, coverage links, or proof tooling change, also run `bun run proof:replay` to reproduce the full CI gate on committed HEAD. The repository's pre-commit framework configuration includes a `pre-push` stage for the fast gate. Maintainers using that framework enable it with `pre-commit install --hook-type pre-push`; tracking the configuration alone does not install the hook. The fast gate checks the current clean checkout; use the corresponding checkout when pushing another branch or an explicit ref. --- # Modeling requirements URL: https://getkibi.dev/guide/modeling.html > A practical cheat sheet for turning product intent into requirements, scenarios, tests, facts, and code links. Use this one-page guide when deciding how to model knowledge through peer MCP tools or dedicated CLI JSON routes. ## Decision Tree 1. **Starting from raw normative prose?** Call `kb_model` with `mode: "analyze"` and the complete body. Audit its clause split and supply `clauses` when needed so every atomic obligation, prohibition, exception, condition, and threshold has a stable claim key. 2. **About to write/update a normative requirement?** Run `kb_upsert` with `dryRun: true` first and inspect `semanticAdvisor`. If it reports `needs_modeling`, repair the payload before treating the requirement as Prolog-checkable. 3. **Runtime/config gate?** Use `flag`, then link with `guards`. 4. **Bug, incident, workaround, audit note, or migration evidence?** Use `fact` with `fact_kind: observation` or `fact_kind: meta`. A bootstrap provider entry with no claim is a `meta` fact tagged `bootstrap:provenance-stub`; never add such a tag to a fact that states something, and never treat a stub as evidence for a requirement. 5. **For each normative property/value/limit clause?** Use a requirement plus strict facts: - `fact_kind: subject` with `subject_key`, linked from the requirement by `constrains`. - `fact_kind: property_value` with `subject_key`, `property_key`, `operator`, `value_type`, and exactly one `value_*`, linked by `requires_property`. - Prefer `kb_model` with `mode: "requirement"` when starting from prose. 6. **For each relational domain clause?** Call `kb_model` with `mode: "predicates"`, then write `fact_kind: predicate` with `predicate_name`, `predicate_args`, and `canonical_key`, linked by `requires_predicate`. For conditions, exceptions, modalities, quantifiers, cardinality, or bounded temporal clauses, submit typed `kibi.logic.v1` to `kb_model` with `mode: "requirement"`, persist `rule_schema` + `rule`, and link with `requires_rule`. - A conditional clause ("checkout may happen only when the cart total is positive", "checkout must not happen unless ...") restricts an action; it is a rule, not a property of every situation. `kb_compile_intent` and `kb_model` (`mode: "requirement"`) translate one comparison on one subject property into a `forbid` rule with that exception, linked by `requires_rule`. A conditional they cannot translate (several conditions, pronouns, relations) stays an `ontology_gap` in the inventory with no observation and no property; supply the typed rule yourself. 7. **BDD behavior?** Use `scenario`, linked with `specified_by`. A scenario that expects success and `assumes` values is checked against current requirements' property facts and rules (see `docs/inference-rules.md`). A human-approved exception requirement (`exempts` the base requirement, `specified_by` the scenario, `approved_by` set) waives the base requirement for that scenario only; `exempts_claims` narrows the waiver to the listed claim keys. 8. **Executable evidence?** Use `test`, linked with `verified_by` or `validates`. - When the requirement has a `scenario`, this link must target the scenario: use `verified_by(Scenario, Test)` or `validates(Test, Scenario)`. Directly linking `verified_by(Req, Test)` and `validates(Test, Req)` does not satisfy scenario-aware symbol-coverage. - For small behavior fixes discovered from source, create or update a `req` for the observable behavior. Link strict or observation facts from that requirement, then link the requirement or scenario to the executable test. Do not create direct `fact -> test` / `test -> fact` verification shortcuts. 9. **Code ownership or coverage?** Use `symbol`, linked with `implements`, `covered_by`, or `executable_for`. 10. **Storing visual/UI layout expectations** (button placement, centered content, header items, alignment)? Use the UI modeling lane in `docs/ui-requirements.md`: prose `req` for the full screen description, strict `property_value` facts for checkable positions/alignment/order, and `visual_layout_rule` (or a project-local `predicate_schema`) for relational layout. Optional and per-project; non-UI projects skip it. ## Names and subjects Name a new entity by the behavior it governs: `--` in kebab-case (`REQ-cli-gc`, `SCEN-mcp-search-discovery`). The filename stem equals the `id`. Search that area first. Update the existing entity when it already covers the behavior. Link `supersedes` when one requirement replaces another, and `restates` (requirement to requirement) when two current requirements intentionally say the same thing. Existing numbered IDs stay valid. A subject key is dotted `component.aspect[.sub]`: at least two lowercase snake_case segments, such as `docs.site` or `kibi.cli.check.staged`. Never derive it from a requirement ID. `kb_model` with `mode: "requirement"` returns `vocabularyAlignment` with ranked subjects and a `reuse_existing` or `declare_new` decision. Follow that decision. A requirement constrains one subject fact for a given key. Property facts for that subject share the key. A second subject fact with the same key grounds every claim twice. When a predicate is single-valued per key (one `reading` per `sensor`), add `key_arguments: [sensor]` to its `predicate_schema`. Rule comparison only treats two atoms as the same fact through such a declaration; without it, opposing rules over that predicate stay `unresolved` rather than `disjoint`. The advisory `rule-key-arguments-missing` check names the predicates whose missing declaration is the only thing keeping an opposing rule pair `unresolved`; declare keys only for predicates that really are single-valued per key. When a predicate schema declares `argument_constants`, new facts must use those values. `argument_aliases` names old spellings that map to a constant; writes reject both undeclared values and aliases. `kibi migrate` can apply the mechanical repairs (the only matching namespace, or an alias rewritten to its constant) after you approve the plan hash. ## Strict property example ```json { "type": "fact", "id": "FACT-SESSION-TIMEOUT", "properties": { "title": "Session timeout limit", "status": "active", "source": "docs/facts/session.md", "fact_kind": "property_value", "subject_key": "user.session", "property_key": "timeout_minutes", "operator": "lte", "value_type": "int", "value_int": 30, "canonical_key": "user.session.timeout_minutes.lte.30", "claim_key": "CLAIM-0123456789ABCDEF", "claim_text": "Sessions must time out within 30 minutes." } } ``` ## Predicate example ```json { "type": "fact", "id": "FACT-EDITOR-DRAFT-AUTOSAVE", "properties": { "title": "Editor drafts autosave on navigation", "status": "active", "source": "docs/facts/editor.md", "fact_kind": "predicate", "predicate_name": "commit_action", "predicate_args": ["editor.annotation", "navigation", "draft"], "polarity": "assert", "canonical_key": "commit_action(editor.annotation,navigation,draft)", "claim_key": "CLAIM-FEDCBA9876543210", "claim_text": "Editor annotation drafts must autosave on navigation." } } ``` ## UI / visual requirement lane For projects with a UI that must record what the screen should look like, store the full visual description as prose in a `req` and decompose checkable invariants into strict or predicate facts: - Strict placement/alignment/order invariants: `fact_kind: subject` (`subject_key`) linked via `constrains`, plus `fact_kind: property_value` (`property_key`, `operator`, typed `value_*`) linked via `requires_property`. Incompatible values on the same subject/property from two current requirements are rejected on write unless `supersedes`. - Relational layout ("X must remain visually aligned with Y"): the built-in `visual_layout_rule(subject, relation, target)` predicate linked via `requires_predicate`. - UI components: `symbol` with `sourceFile` and `symbol_role: behavioral`, linked `implements` to the requirement so component edits surface the visual spec in impact diagnostics. This lane is optional; a non-UI project simply never models UI subjects. See `docs/ui-requirements.md` for payload-shaped examples and the full workflow. ## Observation example ```json { "type": "fact", "id": "FACT-LOGIN-INCIDENT-001", "properties": { "title": "Login redirect incident evidence", "status": "active", "source": "docs/facts/login-incident.md", "fact_kind": "observation", "text_ref": "docs/incidents/login.md#L12" } } ``` ### Review observation for a claim Kibi could not write When a claim cannot be written yet (an `invalid_write`, an ontology gap, an open question), record it as a review observation. Quote the claim in `claim_text`; an observation is a non-grounding note, so it takes no `claim_key` and no `requires_*` link: ```json { "type": "fact", "id": "FACT-review-mic-failure-error", "properties": { "title": "Review: microphone failure claim needs a rule", "status": "active", "fact_kind": "observation", "text_ref": "tracker:ED-12", "tags": ["review:invalid-write"], "claim_text": "If microphone access fails, the editor must present an error instead of silently pretending to record." } } ``` Every other fact kind that carries `claim_text` gets the matching `claim_key` derived from it; sending the key is optional, and a sent key must match. ## Writing a scenario Scenario prose goes in `document.body`, never in `properties` (a `body`, `text` or `description` property is rejected as an unknown property that names `document.body`). `expects` is `success`, `rejection` or `error`. Set it only when the scenario also links `assumes` facts (the `property_value` facts whose values it relies on): Kibi checks feasibility from those values, and `expects` without `assumes` only yields a `scenario-feasibility-unknown` warning. A draft scenario tagged `needs-human-review` omits `expects`: ```json { "type": "scenario", "id": "SCEN-editor-mic-failure-error", "properties": { "title": "Microphone failure shows an error", "status": "active", "expects": "error" }, "document": { "body": "Given microphone access is denied, when the user starts recording, then the editor shows an error and records nothing.\n\nSupport asked for this after users lost takes they believed were recorded; ticket ED-88.\n" }, "relationships": [ { "type": "assumes", "from": "SCEN-editor-mic-failure-error", "to": "FACT-editor-mic-permission-denied" } ] } ``` ## Linking a scenario to an existing requirement To add `specified_by` to a requirement that already has a proposition ledger, upsert the requirement with its stored `title`, a `status`, and the relationship only. Kibi keeps the stored ledger when the payload has no `semantic_*` or `logic_claims` field and does not change `title` or `text_ref`: ```json { "type": "req", "id": "REQ-editor-mic-failure-error", "properties": { "title": "", "status": "open" }, "relationships": [ { "type": "specified_by", "from": "REQ-editor-mic-failure-error", "to": "SCEN-editor-mic-failure-error" } ] } ``` ## Body context example Front matter holds the checked meaning; the body holds the reasons. A requirement body needs a `## Context` section that is not a restatement of the title. ```markdown Refunds above 500 EUR require a second approver. ## Context Finance asked for this after the March audit found two unreviewed large refunds. The 500 EUR threshold was their number; the requester gave no reason for it. ## Source > Refunds over 500 EUR need a second approver. Finance audit follow-up, ticket FIN-212. ``` Scenarios and tests keep Given/When/Then prose, assumptions, what is asserted and what would make it a false pass. When the reason was not given, write "Reason not stated"; never invent one. `entity-context-missing` blocks entities without context; `review:context-missing` is reserved for entities the schema 8 migration acknowledged and is not honored on any other entity; write who asked, the source and "Reason not stated" instead. ## Claim keys `claim_key` is `CLAIM-` plus sixteen hex digits, a stable hash of the exact `claim_text`. Kibi derives it: a ground fact (`property_value`, `predicate`, `rule`) that sends `claim_text` alone gets its `claim_key` filled in on `kb_upsert` and on `kibi sync`. `kb_model` `mode: "analyze"` lists every proposition's `claim_key` with its `claim_text`, and `mode: "requirement"` and `mode: "predicates"` put the pair on each planned fact in `applyPlan`, so apply those entries unchanged; a sent key that does not match its text is refused with the expected key in the message (`claim_key must equal the stable key derived from claim_text (expected 'CLAIM-…')`), and a `claim_key` without `claim_text` is refused. Repair a mismatch by copying that value or dropping the key, never by editing `claim_text` to fit. The stored key of a `requires_predicate`, `requires_property` or `requires_rule` target must appear in the requirement's `semantic_inventory` entry with `status: modeled`, so the fact's `claim_text` must be that exact clause. Observation and meta facts quote the clause in `claim_text` without a key. ## Common field-name mistakes The claim keys above are illustrative. Always use the stable key returned for the exact clause text. Store every returned normative key in the requirement-only `logic_claims` array, merge rather than replace existing keys, and preserve `claim_key` plus `claim_text` together on every ground `property_value`, `predicate`, or `rule` fact. Preserve the full `semantic_inventory` proposition ledger; an observation does not ground a claim. `kb_model` accepts semantic claim inputs such as `subjectKey`, `propertyKey`, and `existingLogicClaims` in `mode: "requirement"`; `mode: "predicates"` also accepts `existingLogicClaims`. `kb_upsert.properties` does not accept camelCase modeling inputs. For `kb_upsert`, use snake_case only: `logic_claims`, `claim_key`, `claim_text`, `subject_key`, `property_key`, `predicate_name`, `predicate_args`, `canonical_key`, `closed_world`, `value_type`, and one typed `value_*` field. ## Semantic advisor receipts `kb_upsert` with `dryRun: true` and successful `kb_upsert` responses may include semantic advisor receipts for requirements. The receipt contains `clauses` and `logic_coverage`, including expected, declared, missing, and unresolved claim keys. A receipt with `logic_readiness: needs_modeling` means at least one clause still needs work. Inspect `suggestions` for one of five reviewable paths: - `strict_property` — draft subject/property facts plus requirement relationships. - `predicate` — draft ontology predicate fact and relationship guidance. - `ambiguity_observation` — observation artifact when prose has competing interpretations. - `ontology_gap` — observation artifact plus a recommended predicate schema when the claim is logical but unsupported. - `rule` — a validated `kibi.logic.v1` rule, from a host interpretation or from a conditional clause ("only when", "only if", "must not ... unless") the advisor translated; link it with `requires_rule`. Suggestions are non-blocking and must be reviewed before applying; they are not enforcement receipts. Current deterministic coverage includes: - **Strict property suggestions:** multi-claim prose, cardinality, thresholds with units, retention/expiry durations, booleans, enum sets, and comparative numeric constraints. - **Ontology predicate suggestions:** permissions and prohibitions, defaults, uniqueness constraints, state memberships, state transitions, conditional behavior, temporal ordering, rate limits, exception rules, mutual exclusion, dependency rules, ownership, retry policies, escalation rules, availability SLAs, notification routing, idempotency, data residency, audit logging, consent prerequisites, lifecycle archive/delete/expiry rules, conflict-resolution strategies, fallback/degradation behavior, batch operations, cross-entity consistency/reference requirements, build constraints, environment-safety rules, schema invariants, coding standards, migration boundaries, absence/removal requirements, offline behavior, release gates, platform consistency, preservation rules, abstraction boundaries, security configuration, ordered strategies, refresh policies, scoped authorization, documentation standards, warmup policies, visual layout rules, enforcement-location rules, reconciliation rules, and throttling policies. - **Review artifacts:** ambiguity observations and ontology-gap observations when a claim is logical but not safely grounded by the current deterministic catalog. - **Bootstrap review facts:** `kb_plan_bootstrap` turns `intentClaims` declared with `kind: observation` or `kind: open_question`, and each declared `conflicts` entry, into `fact_kind: observation` facts that cite their source (`text_ref: :`). Open questions carry `review:open-question` and conflicts `review:conflict`; none of them is a requirement or enters the contradiction lane. Resolve them with the human, then author the outcome as a normal `req`. When an exact predicate suggestion exists, prefer its `applyPlan` and `requires_predicate` relationship guidance over generic prose notes. The receipt-level `candidate_lane` and `suggested_next_tools` are aligned to exact suggestions, so numeric-looking predicate claims such as lifecycle or batching rules can still correctly route to `kb_suggest_predicates` (call it as `kb_model` with `mode: "predicates"`; these receipt fields name catalog operations). After writes, run `kb_check` with `logic-coverage`, `predicate-verifiability`, `domain-contradictions`, `kb-consistency`, and `kb-consistency-unresolved`. `logic-coverage` verifies that every declared claim key has a matching linked ground fact and that linked ground facts appear in the manifest. It does not prove that an automatic clause split exhausts arbitrary natural language; that boundary remains an explicit review obligation. Exact `assert`/`deny` facts over the same predicate namespace, name, and ordered arguments do participate in `domain-contradictions`. `domain-contradictions` compares facts in pairs; `kb-consistency` also catches bounds that only contradict together, and `kb-consistency-unresolved` lists contexts it could not compare, which never count as consistent. Do not invent or copy a claim key between clauses. Kibi mutation and Markdown sync surfaces recompute the stable key from `claim_text` and reject mismatches; preserve the exact key returned by `kb_model` with `mode: "analyze"` for that atomic clause. If an upgrade changes how the advisor reads existing prose, `kibi sync` lists every requirement whose stored inventory no longer matches. Run `kibi migrate`: it re-derives those inventories, keeping each claim whose key and text still match (a modeled claim stays modeled with its grounding) and marking new or reclassified claims unresolved. It lists the requirements it cannot re-derive safely, with the exact commands to fix them. ## Origin Every entity can carry `origin: {kind, ref, approved_by, recorded_at}` (`kind` is `human`, `agent`, `migration` or `import`; typed fields are snake_case). Leave it out of `kb_upsert` unless you have something to add: a new entity is recorded as `{kind: agent, recorded_at}`, and an update without `origin` keeps whatever is stored. Set `ref` to the conversation, ticket or document the content came from. Record `origin.approved_by` only when a named person reviewed the content. An agent must not fill it in on its own; `agent-requirement-unapproved` lists agent-authored requirements nobody has approved yet. For an exception requirement, `approved_by` is what lets the exception exempt anything. When an agent records it, also set `approval_ref` to the decision record and `origin.approved_by` to the person who confirmed it; otherwise `exception-approval-self-attested` asks a human to confirm. ```json { "type": "req", "id": "REQ-quota-promo-exception", "properties": { "title": "Promotional accounts may exceed the upload quota", "status": "open", "approved_by": "Dana Lee", "approval_ref": "DEC-quota-promo", "origin": { "kind": "agent", "ref": "session 2026-10-01", "approved_by": "Dana Lee" } } } ``` ## Quality diagnostics lane `kibi check`, MCP `kb_check`, staged impact checks, coverage reports, and OpenCode scheduled checks can surface non-blocking `qualityDiagnostics[]` alongside hard `violations[]`. Treat `violations[]` as correctness failures to fix before handoff. Treat `qualityDiagnostics[]` as audit review guidance unless `blocking: true` or `severity: "error"` is present. Common review diagnostics map to modeling actions: - Broad requirement or multi-requirement symbol: split the requirement/symbol into one observable behavior per anchor, or document a valid umbrella/module rationale. - Logical coverage review: decompose the complete requirement, use `kb_model` (`mode: "requirement"` or `"predicates"`) per clause, and validate the claim manifest. - Coverage-depth review: add typed `verification_scope` / `verification_perspective` fields to test entities and prefer direct/scenario e2e evidence when the behavior crosses an external boundary. - Duplicate coordinate review: refresh symbol coordinates through the CLI sync workflow and keep modeled symbol IDs distinct enough to identify the behavioral anchor. --- # Keep every coding agent on the same requirements URL: https://getkibi.dev/guide/consistent-agents.html > Use Kibi to keep Claude Code, Cursor, Codex and other coding agents consistent with the same project requirements, across sessions, tools and branches. Teams rarely use one coding agent. One person works in Claude Code, another in Cursor, a cloud agent picks up an issue overnight, and each session starts with an empty context window. Rules written into one tool's configuration do not reach the others, and a decision agreed in yesterday's chat is gone by tomorrow. Kibi keeps one set of requirements in the repository and gives every agent the same way to read and check it. ## The problem - **Each host has its own rules file.** `CLAUDE.md`, `.cursor/rules`, `AGENTS.md` and `GEMINI.md` drift apart, and none of them is checked against the code. - **Sessions forget.** The reason behind a change ("we cap retries at three because the payment provider bills per attempt") lives in a chat that the next agent never sees. - **Nothing stops a contradiction.** Two agents can implement opposite rules in two files, and both changes look fine in review. ## How Kibi keeps them consistent **One source, in the repository.** Requirements, the reasons behind them, scenarios, tests and links to the code live in `.kb/` beside the code. Every agent, on every machine, reads the same files, and each Git branch has its own snapshot, so a feature branch's decisions stay with that branch. See [how Kibi works](how-it-works.md). **One interface for every host.** The project-local `kibi-mcp` server gives Antigravity, Claude Code, Cursor, Codex, OpenCode, Mistral Vibe, ZCode, VS Code and any other MCP client the same tools, and agents without MCP call the same operations through the `kibi` CLI. [Connect your coding agent](connect-an-agent.md) lists the setup for each host. **The rule appears where the work happens.** With a Kibi plugin, reading or searching code shows the requirements that own it, and before an edit the hook names the requirement the file implements, what it must keep true and why it exists. The agent does not have to remember to look. **Fresh clones find it too.** `kibi init` writes a Kibi section into `AGENTS.md` (imported from `CLAUDE.md` and `GEMINI.md`), so a teammate's agent or a cloud agent working on a fresh clone learns that the knowledge base exists and how to use it. **Contradictions are refused, not merged.** When an agent tries to record a rule that conflicts with a current one, such as an allow and a deny for the same actor and action, Kibi refuses the write and names the conflict. The commit gate runs the same checks before anything is committed. The [inference rules](../reference/inference-rules.md) list what is checked. ## What you do 1. Run the [quick start](quick-start.md) once per repository. The setup prompt works in any agent that can run commands. 2. Connect each agent your team uses, or install its plugin. 3. Keep prompting as usual. When an agent's change conflicts with a recorded requirement, it asks you instead of silently picking one. ## Related - [Enforce the rules in AGENTS.md](use-case-agents-md.md) - [Prove that an agent's change meets a requirement](use-case-prove-changes.md) - [Kibi compared with other approaches](compare.md) --- # Enforce the rules in AGENTS.md URL: https://getkibi.dev/guide/enforce-agents-md.html > Turn the rules you keep in AGENTS.md, CLAUDE.md or Cursor rules into requirements that Kibi links to the code, shows before every edit and checks before every commit. `AGENTS.md` and its relatives (`CLAUDE.md`, `.cursor/rules`, `GEMINI.md`) are a good place to tell an agent how to work. They are a weak place to keep product rules. The file is prose that the agent may or may not read, it grows until the important line is lost, and nothing checks that the code still does what it says. Kibi keeps the instruction file short and moves the rules that must hold into requirements it can check. ## Instructions versus requirements - **Instructions** describe how to work: run the tests, use the project's formatter, open a pull request against `develop`. These stay in `AGENTS.md`. - **Requirements** describe what the software must keep doing: "a user owns at most five workspaces", "password reset signs out every other session". These belong in Kibi, where each one is linked to the code that implements it and the tests that verify it. ## What Kibi adds to a rule **It is shown at the moment it matters.** With a Kibi plugin, the hook before an edit names the requirement the file implements, what it must keep true, why it exists and the decision behind it. The rule reaches the agent even when the instruction file was never read. **Your rules cannot be quietly rewritten.** A rule you stated is recorded as `firm` and points at your words. Only another firm decision can replace it, so the agent is told to ask you first. A choice the agent made is a `default` that a later agent may replace with evidence. When your request conflicts with any recorded rule, the agent names it and asks. **It is checked, not just read.** `kibi check` and the pre-commit gate report code that no requirement owns, requirements that contradict each other and scenarios a current requirement forbids. With the `test` [Kibi level](../reference/cli.md#kibi-level), a requirement also needs a test with fresh evidence before it counts as tested. **The instruction file stays in step.** `kibi init` adds a short Kibi section to `AGENTS.md` that tells every agent the knowledge base exists, to search it before changing behaviour, and to record a rule you state. It does not copy the requirements into the file. ## Moving existing rules into Kibi Bootstrap reads the sources you point it at, which can include `AGENTS.md`, your wiki and your issue tracker. It proposes requirements that each cite where they came from, and writes nothing until you approve the plan. Start with the [quick start](quick-start.md), and see [modeling requirements](modeling.md) for how a rule becomes requirements, scenarios and facts. ## Related - [Keep every coding agent on the same requirements](use-case-consistent-agents.md) - [Prove that an agent's change meets a requirement](use-case-prove-changes.md) - [Kibi compared with other approaches](compare.md) --- # Prove that an agent's change meets a requirement URL: https://getkibi.dev/guide/prove-agent-changes.html > Use Kibi to show that code an AI coding agent wrote still meets the requirement it implements, with fresh end-to-end evidence bound to the current code and a report anyone can read. An agent says "done" and the tests pass. That does not tell you which requirement the change was for, whether a test actually checks that behaviour, or whether the evidence is from this version of the code. Kibi answers those three questions for every requirement, in the repository and in a report you can publish. ## From requirement to evidence Each requirement is linked to the scenarios that describe it, the tests that verify those scenarios and the code symbols that implement it. A requirement counts as **tested** only when a test that claims to verify it has fresh, passing end-to-end evidence for the current code. A passing unit test somewhere else, a coverage percentage or an old result does not count. [How Kibi works](how-it-works.md#why-coverage-is-not-proof) explains why. Evidence comes from the test runner you already use. `kibi prove` runs the proof-bearing tests through an integration for Playwright, pytest or JUnit XML, Go or TAP, or any command with an exit code, and binds the result to the current snapshot of the code. Change the code, and the old evidence stops counting. The [proving requirements reference](../reference/proving.md) has the details. Some claims can go further than a test. Kibi reserves **proved** for a claim a checker established for every case, such as every state of a state machine or every route of an API, with a certificate a second program can re-check. ## While the agent works - After each edit, the plugin hook asks the agent to run `kb_check` on the changed files. It reports what the commit gate will report, before anything is staged. - A change to a function that no requirement owns is named, so the agent records what the code now does. - A requirement whose evidence went stale is listed, so the agent reruns the tests that prove it with `kibi prove --stale`. ## What you see The health report shows every requirement with its evidence level (proved, tested, asserted or unverified), which evidence is stale and which requirements contradict each other. Publish it on GitHub Pages with a badge, so a pull request shows whether proof still holds. See [reading the report](reading-the-report.md), [the proof ladder](proof-ladder.md) and [publishing requirement health](github-integration.md). Kibi publishes [its own report](https://getkibi.dev/kibi-report/) the same way. ## Related - [Keep every coding agent on the same requirements](use-case-consistent-agents.md) - [Enforce the rules in AGENTS.md](use-case-agents-md.md) - [Kibi compared with other approaches](compare.md) --- # Kibi compared with other approaches URL: https://getkibi.dev/guide/compare.html > How Kibi compares with rules files such as AGENTS.md, memory tools for coding agents, spec-driven development workflows and requirements-traceability tools, and when each one is enough. Kibi is a requirements framework for AI coding agents. It records the reasoning behind your code as requirements in your repository, links them to code and tests, and makes every later agent respect them. Other approaches cover parts of that. This page says what each one does well and where Kibi differs, so you can tell whether you need it. ## At a glance | | Rules files | Memory tools | Spec-driven | Traceability tools | Kibi | | --- | --- | --- | --- | --- | --- | | Knowledge lives in | A prose file per host | A memory store | Specs written first | Requirement documents | Typed requirements in `.kb/`, per branch | | Written by | You | The agent | You, then the agent | People | The agent; you approve product calls | | Linked to code | No | No | Via the task plan | By hand | Per symbol, checked on commit | | Shown before an edit | If read | If searched | If opened | No | Yes, by hooks | | Contradictions caught | No | No | No | Rarely | Refused before storing | | Evidence it still holds | No | No | Agent-written tests | Trace reports | Fresh end-to-end evidence | Rules files means `AGENTS.md`, `CLAUDE.md`, Cursor rules and similar instruction files. ## Rules files A short `AGENTS.md` that says how to work in the repository is the right tool for build commands, style and process. Keep it. It is not enough when the rules are about product behaviour: the file is not checked against the code, it grows until important lines are lost, and each host reads a different file. Kibi keeps those rules as requirements and adds a short section to `AGENTS.md` that points agents at them. See [Enforce the rules in AGENTS.md](use-case-agents-md.md). ## Memory tools Memory tools help an agent remember what happened in earlier sessions. They store what was said; they do not check it. A remembered rule can be outdated, contradict another one or no longer match the code, and the agent will not know. Kibi differs in three ways: requirements are linked to the code that implements them, conflicting requirements are refused, and evidence shows whether the code still does what the requirement says. Memory remembers; Kibi enforces. ## Spec-driven workflows Spec-driven development writes a specification first and has the agent implement it. That works well for a new feature with a clear plan. Kibi does not ask you to write specs up front: requirements are captured from the work itself, from your prompts and the sources you point bootstrap at, and they stay attached to the code after the feature ships, so the next agent that touches it is held to the same intent. The two can work together: a spec can be the source a requirement cites. ## Requirements-traceability tools Traditional traceability tools link requirements to code and tests, mostly for audits, and depend on people keeping the links current. Kibi gives that job to the agent and checks it: code no requirement owns, a requirement with no test and stale evidence are all reported by `kibi check` and the commit gate, and Prolog rules check the requirements themselves for contradictions. See [the proof ladder](proof-ladder.md) and the [inference rules](../reference/inference-rules.md). ## When Kibi is more than you need If your project is small, one person works on it in one agent, and the rules fit on a screen, a rules file is enough. Kibi's `remember` [level](../reference/cli.md#kibi-level) is a lighter start when you want requirements, reasons, code links and contradiction checks without scenarios, tests and proofs. ## Next - [What is Kibi?](welcome.md) - [Quick start](quick-start.md) - [Keep every coding agent on the same requirements](use-case-consistent-agents.md) - [Prove that an agent's change meets a requirement](use-case-prove-changes.md) --- # Publish requirement health URL: https://getkibi.dev/guide/github-integration.html > Publish the requirement-health report and badge on GitHub Pages so proof status is visible on every pull request. Publish a continuously updated Kibi requirement-health report on GitHub Pages, with a clickable `% tested` badge in the repository README. Badge and report are one feature. Someone who sees `87% tested` needs to open the report to see what that percentage represents and which requirements are missing proof. Kibi does not host badges or reports; GitHub Pages is the expected publisher. Knowledge stays in the repository's `.kb/` directory. ## What the badge means A badge such as `kibi | 87% tested` is the share of **applicable current** Kibi requirements that have current proof. Non-current (for example superseded) requirements are excluded, as are requirements marked not applicable to proof. The published HTML report is the place to inspect: - which requirements are tested end to end - which are missing proof - contradictions - stale verification state - other requirement-health details already exposed by `kibi report` The badge and `index.html` always come from **one** `kibi report` coverage snapshot. Do not compute a separate GitHub-only percentage. ## Recommended flow: badge + full report ### 1. Enable GitHub Pages In GitHub: ```text Settings → Pages → Source → GitHub Actions ``` This is the only expected GitHub UI step. Kibi does not change repository settings for you. ### 2. Add the Kibi workflow Copy the canonical workflow to: ```text .github/workflows/kibi-report.yml ``` The file to copy is [docs/examples/github/kibi-report.yml](examples/github/kibi-report.yml). It is byte-identical to the template shipped in `kibi-cli`. One `build-report` job generates the report. Pull requests validate that generation and upload the candidate site as an ordinary workflow artifact. Only the repository **default branch** (it does not assume the branch is named `main`) and `workflow_dispatch` may deploy GitHub Pages. A `pull_request` event never deploys Pages, never replaces the canonical report or badge, and never receives `pages: write` or `id-token: write`. The workflow uses `pull_request`, not `pull_request_target`, with repository-level `contents: read`. GitHub Actions checkouts are detached, so the workflow sets `KIBI_BRANCH` to the pull-request head ref or the pushed/dispatched branch name before `kibi sync` and `kibi report`. The generate job: 1. checks out the candidate GitHub Actions ref (the PR merge commit on pull requests, otherwise the pushed or dispatched commit) 2. sets up Node.js 3. installs project dependencies with npm (SWI-Prolog arrives with them as the bundled `kibi-swipl-linux-x64-gnu` package, so there is no separate install step) 4. runs `kibi sync` 5. runs `kibi report --output kibi-report` (the job fails if this fails) 6. on `pull_request`, uploads the `kibi-report/` directory as the `kibi-pr-report` artifact (HTML report plus badge) 7. on the default branch or `workflow_dispatch`, copies that output under `pages/kibi-report/` so the public path is `/kibi-report/` and uploads it as a GitHub Pages artifact The `deploy-report` job then deploys that Pages artifact. It does not run for pull requests. Pushes to non-default branches start the workflow and skip both jobs. The workflow does not build or test the rest of the application, does not commit generated files, and does not use an orphan `gh-pages` branch. ### 3. Add the clickable badge ```markdown [![Kibi requirement health](https://OWNER.github.io/REPOSITORY/kibi-report/badge.svg)](https://OWNER.github.io/REPOSITORY/kibi-report/) ``` Replace `OWNER` with the repository owner (lower case is fine, since the `*.github.io` host is case-insensitive) and `REPOSITORY` with the repository name exactly as GitHub spells it. The project-site path is case-sensitive, so `MyRepo` and `myrepo` are different URLs. Clicking the badge must open the report. Files are published under `/kibi-report/` so Kibi does not occupy the Pages site root. This workflow still **replaces** the GitHub Pages deployment. If the repository already publishes a site, copy `kibi-report/` into that site's output instead of using this workflow as the only deploy. ### Expected URLs | Repository | Report | Badge | | --- | --- | --- | | `OWNER/REPOSITORY` | `https://OWNER.github.io/REPOSITORY/kibi-report/` | `https://OWNER.github.io/REPOSITORY/kibi-report/badge.svg` | | `Owner/MyRepo` (mixed case) | `https://owner.github.io/MyRepo/kibi-report/` | `https://owner.github.io/MyRepo/kibi-report/badge.svg` | | `OWNER/OWNER.github.io` (owner site) | `https://OWNER.github.io/kibi-report/` | `https://OWNER.github.io/kibi-report/badge.svg` | The image URL must be anonymously reachable for GitHub to render it in a public README. For a private report, publish both files to an authenticated static host that your intended audience can access. GitHub Actions artifacts expire and are not a stable badge URL. Do not commit generated `kibi-report/` files. ## CLI shortcut `kibi init --github` performs normal `kibi init` behavior, then scaffolds the **same** documented integration: ```bash kibi init --github ``` It: - writes `.github/workflows/kibi-report.yml` from the packaged template - adds the clickable badge to an existing root README when a github.com remote can be determined - adds `kibi-report/` to `.gitignore` when missing - prints the Pages enable instruction It is safe to run more than once. Matching workflows are left as already configured. Customized workflows are **not** overwritten. An existing Kibi badge is not duplicated. If no README exists, the workflow is still written and the badge Markdown is printed. If owner/repository cannot be determined from a github.com remote, the workflow is still written and placeholder badge Markdown is printed instead of inventing a URL. ## Package-manager adaptations The canonical workflow uses npm because that matches the documented Kibi install (`npm install --save-dev kibi-cli ...` and `npm exec -- kibi`). Change **only** the Node setup cache and the install/exec commands: **pnpm** ```yaml - uses: actions/setup-node@v5 with: node-version: 24 cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm exec kibi sync - run: pnpm exec kibi report --output kibi-report ``` Install the pnpm action (`pnpm/action-setup`) before `setup-node` if the runner does not already have pnpm. **Yarn** ```yaml - uses: actions/setup-node@v5 with: node-version: 24 cache: yarn - run: yarn install --frozen-lockfile - run: yarn kibi sync - run: yarn kibi report --output kibi-report ``` **Bun** ```yaml - uses: oven-sh/setup-bun@v2 - run: bun install --frozen-lockfile - run: bunx kibi sync - run: bunx kibi report --output kibi-report ``` Keep `kibi-cli` as a project dependency so CI uses the version the repository pinned. Do not add application `build` or `test` steps just to generate the report. ## Badge-only opt-out Prefer the full report. To publish only the badge: ```bash kibi init --github --badge-only ``` Or copy [docs/examples/github/kibi-badge.yml](examples/github/kibi-badge.yml) to `.github/workflows/kibi-badge.yml`. That workflow still runs `kibi report` (same snapshot, same `% tested`). Pull requests upload the generated report directory as `kibi-pr-report` and still do not deploy Pages. Default-branch and `workflow_dispatch` publishes only `badge.svg` under `/kibi-report/`. The README link should point at this section rather than pretending a report exists: ```markdown [![Kibi requirement health](https://OWNER.github.io/REPOSITORY/kibi-report/badge.svg)](https://getkibi.dev/guide/github-integration.html#what-the-badge-means) ``` `--badge-only` without `--github` is rejected. `--github` by itself always means badge + full report. ## Merge conflicts in Kibi manifests Two branches that each add symbols both append to the end of `.kb/symbols.yaml` (and sometimes to the same `.kb/relationships/*.yaml` shard), so Git reports a conflict even though the additions are independent. `kibi merge-driver` is a Git merge driver that merges these manifests by record id instead of by line: - records added on either side are kept (ours first, then theirs) - an edit made on only one side wins over the unchanged other side - a deletion on one side is kept when the other side left the record unchanged - relationships and links that both sides added to one symbol are unioned - anything else both sides changed differently (for example two different `status` values) is a real conflict: the driver names it, leaves ordinary conflict markers, and exits non-zero so the file stays unmerged `.kb/symbol-coordinates.yaml` is a gitignored local cache derived by every `kibi sync`, so it never takes part in a merge. ### Locally Declare the driver in the repository's `.gitattributes`: ```text .kb/symbols.yaml merge=kibi .kb/relationships/*.yaml merge=kibi ``` Then each clone opts in once (Git never runs a driver from repository content alone): ```bash git config merge.kibi.driver "npm exec --no -- kibi merge-driver %O %A %B" ``` Without that setting Git ignores the attribute and falls back to its normal line merge, so declaring it is safe for contributors who do not use Kibi. ### Keep pull requests mergeable in CI GitHub decides whether a pull request can merge with its own merge, which never runs a custom driver (Git only runs a driver that each clone configures, and GitHub runs no program from repository content). So as soon as one pull request that added symbols merges, every other open one that also added symbols shows a conflict in `.kb/symbols.yaml`, even though `kibi merge-driver` would merge it cleanly. The **Kibi KB merge** action closes that gap: it does the merge GitHub cannot do and pushes the result to the pull request branch. #### Set it up 1. Declare the driver in `.gitattributes` as shown above, and commit a `kibi-cli` dependency (any version with `kibi merge-driver`) on the default branch. 2. Copy [docs/examples/github/kibi-kb-merge.yml](examples/github/kibi-kb-merge.yml) to `.github/workflows/kibi-kb-merge.yml`. Replace `@master` with a full commit SHA of `Looted/kibi` so the action only changes when you update it. 3. Create a token so the merge commits start your checks (see [Tokens and permissions](#tokens-and-permissions)) and save it as the repository secret `KIBI_MERGE_TOKEN`. Without it the workflow still pushes merges with `GITHUB_TOKEN`, but your pull request checks do not re-run on them. 4. Optional: change the `check` input to the gate your repository runs before merging, for example `npm run kb:gate`. It runs in the merged tree, and the merge is pushed only when it exits 0. For pnpm, Yarn or Bun, change the `setup-node` and `npm ci` steps and point the `kibi` input at the installed binary (for example `node_modules/.bin/kibi`, or `bunx kibi`). #### What it does The workflow runs on every push. A push to the default branch checks every open pull request into it; a push to any other branch checks only that branch's pull request, so a branch that adds records after the default branch moved is merged at once. (GitHub does not start `pull_request` workflows while a pull request has conflicts, so `push` is the trigger.) For each candidate pull request the action: 1. test-merges the default branch into the pull request head with `git merge-tree`, exactly as GitHub does, and stops if it merges cleanly; 2. stops and leaves the pull request for a person if any file outside `.kb/symbols.yaml` and `.kb/relationships/*.yaml` conflicts; 3. merges the default branch into the head in a scratch worktree with `kibi merge-driver`, using the default branch's install of Kibi (never the pull request's, so a branch opened before the driver existed still merges); 4. runs `kibi sync` on the merged tree and refuses the merge if sync would change a tracked file, then runs the `check` command; 5. pushes the merge commit only when both passed. If someone pushed to the branch meanwhile, the push is refused and the action starts again from step 1 on the new tip (three attempts by default, see `attempts`). A branch that still tracks `.kb/symbol-coordinates.yaml` from before KB schema 13 has it removed in that merge. The job summary lists each branch with what happened, and the action's outputs `merged`, `blocked` and `failed` hold the same lists as JSON. The job fails only for a branch the driver should have handled but whose merge failed `kibi sync`, the check, or the push. #### What it does not resolve - **Real conflicts inside a manifest.** When both sides changed the same field of one record differently (for example two `status` values), `kibi merge-driver` leaves conflict markers and the pull request is left for a person, with a warning in the job log. - **Conflicts in any other file**, including requirement, scenario and test Markdown under `.kb/`. Those are documents a person should reconcile. - **Fork pull requests.** A workflow cannot push to a fork's branch, so they are skipped. Their authors merge the default branch locally with the driver configured (see [Locally](#locally)). - **Pull requests into other branches.** Only pull requests into the default branch are checked; set the `base` input to keep another branch's pull requests mergeable instead. - **Merges that break the check.** A merge that fails `kibi sync` or the check is not pushed; the pull request keeps its conflict until a person merges. #### Tokens and permissions The workflow needs `contents: write` (to push merge commits) and `pull-requests: read` (to list pull requests). It pushes with the credentials of its checkout of the default branch, which is why the example passes `token: ${{ secrets.KIBI_MERGE_TOKEN || github.token }}` to `actions/checkout`. Pushes made with the default `GITHUB_TOKEN` do not start other workflows, so the pull request's checks would not re-run on the merge commit. Use a fine-grained personal access token or a GitHub App token limited to the repository, with **Contents** and **Workflows** set to read and write, as `KIBI_MERGE_TOKEN`. Workflows access is needed because a merge that brings in changes under `.github/workflows/` is rejected without it; the default `GITHUB_TOKEN` can never push those merges. An expired secret fails the job rather than falling back to `GITHUB_TOKEN`, so renew it or delete the secret. The bot's own merge push starts the workflow again; that run finds the branch clean and does nothing. Git hooks installed in the checkout (for example by `npm ci`) do not run for the action's merge commit or push; the `check` input is the gate. #### Action reference `uses: Looted/kibi/actions/kb-merge@` | Input | Default | Meaning | | --- | --- | --- | | `base` | repository default branch | Branch whose pull requests are kept mergeable. | | `branches` | every open pull request | Head branches to consider: newline or space separated, or a JSON array. | | `list-only` | `false` | `true` only lists the branches whose sole conflicts are Kibi manifests (output `branches`) and changes nothing. | | `kibi` | `node_modules/.bin/kibi` | Command that runs the default branch's Kibi. A relative path resolves from the workspace. | | `check` | `$KIBI check` | Shell command run in the merged tree before the push. `$KIBI` and `$KIBI_BRANCH` are set; `GH_TOKEN`, `MERGE_TRAIN_CHECKS_TOKEN`, `GITHUB_TOKEN` and the Actions runtime tokens are not, since the tree holds pull request content. Point a script at the base checkout (`sh ${{ github.workspace }}/scripts/gate.sh`) so the tree's copy never runs. `""` runs none. | | `attempts` | `3` | Tries per branch when the branch moves while it is being merged. | | `skip-label` | `""` | Pull requests with this label are left alone. Set it to your merge train's label (`train`): the train merges the manifests itself, and a push to a boarded pull request would restart its checks. | | `github-token` | `github.token` | Token `gh` uses to list pull requests. | The action needs `git` 2.38 or newer, `gh` and `jq`, which GitHub-hosted runners have. Outside GitHub Actions the same logic is `actions/kb-merge/kb-merge.sh`, configured through `KB_MERGE_*` environment variables described at the top of the script. ## Land pull requests in a merge train Merging pull requests one at a time, each re-proven against the latest default branch, takes one full proof run per pull request. The **Kibi merge train** action proves a batch once. Every commit it adds to the default branch's first-parent history is a merge commit whose tree is exactly the tree its checks passed on. ### How it works - **Boarding.** A person adds the `train` label to a pull request. A pull request boards only when it carries the label, is not a draft, comes from this repository, and every check in `checks` passed on its current head. Pull requests board in pull request number order, up to `max` per train. - **Assembly.** From the default branch tip, the action merges each boarded head into a `merge-train/` branch with `kibi merge-driver`. After each merge it runs `kibi sync`, refuses a sync that rewrites a tracked file, and runs the `check` command. A pull request that conflicts or fails is ejected with a comment before any expensive run. The branch is opened as a pull request into the default branch, so your usual workflows run on it. - **Landing.** The train merges, as a merge commit, only when every check in `checks` and `train-checks` passed on the exact head it assembled and the default branch has not moved since. The default branch then has the proven tree, and GitHub marks each boarded pull request merged. - **Failure.** A failed train re-runs its failed jobs once. If it fails again, it is closed and each half is proven as its own train. Only a train of one pull request that fails twice ejects that pull request, so no pull request is removed without evidence that it fails. - **Moves.** A train is closed and assembled again on the new tip when the default branch moves, its branch moves, or a member loses its label or its passing checks. ### Run a slow check once per train A check too slow to run on every pull request, such as a full proof that takes hours, can run only on train branches: trigger it in your workflow for pull requests whose head branch starts with `merge-train/`, and name its check in `train-checks` instead of `checks`. A pull request then boards on its own checks, and the train lands only after the slow check also passed on its assembled head. A failed slow check is re-run once and bisected like any other required check. Each run takes one step and exits. Run it when your check workflows finish, when the label is added, and on a schedule as a backstop, as the example does. ### Don't prove a landed train twice When a train lands, the push to the default branch would start the proof again on a tree the train already proved. Kibi's own proof workflow skips that run. On a push, `bun scripts/ci-proof-reuse.ts decide-train` reuses the train's proof only when all of these hold: - the pushed commit is a merge whose parents are the previous tip and a `merge-train/` head from this repository; - exactly one successful proof run exists for that head, from a pull request in this repository; - that run's attestation names the same head and base commits; and - the canonical Kibi snapshot of the pushed commit equals the attested one. Otherwise the push runs the full proof. A push that reuses the train's proof publishes the train's report and attests it, naming the train run it came from, so a later pull request can reuse it in turn. ### A train of one pull request that is already up to date Most trains hold a single pull request whose head already contains the current tip of the default branch, so the merge commit the train creates has the same git tree the pull request's checks just tested. Kibi's own CI, proof and release-pack workflows reuse those results instead of spending another twenty minutes on them. The train pull request still opens, and its required checks still report, but they finish in about two minutes. Reuse happens only when every one of these holds. Anything else runs the workflow in full: - the train body and the merge commit agree that the train holds exactly one pull request, and the commit is that pull request merged into the base the train recorded; - the train commit's tree, the member commit's tree, and the tree the workflow would actually test (the pull request's merge with the current base) are the same git tree. A rebase onto a newer base, or any other change of content, makes the trees differ and the checks run; - the member's latest run of that same workflow, on that exact commit, from this repository and not from another train, completed successfully, and its attestation names that commit and that tree; - for CI and proof, the aggregate check (`ci-required`, `proof-required`) is a completed success on that commit; - for proof, the canonical workspace snapshot matches as well. The train then attests that snapshot and names the member run, so the push to the default branch can still reuse the proof. A snapshot that does not match is proved again. There is no path that reports a proof without one of those two. A failed lookup, a missing attestation, or an ambiguous run listing is a full run, never a pass. Pull requests merged by this change start attesting the tree they tested; a train whose member was proved before that attestation existed runs the proof. ### Set it up 1. Copy [docs/examples/github/kibi-merge-train.yml](examples/github/kibi-merge-train.yml) to `.github/workflows/kibi-merge-train.yml`. Pin the action to a full commit SHA of `Looted/kibi`. 2. Set `checks` to the checks your ruleset requires. One aggregate job per workflow that needs every other job and fails on a failed, skipped or cancelled one is easiest, because a renamed or split job then never leaves the ruleset waiting. 3. Save a token as `KIBI_MERGE_TOKEN`: a fine-grained personal access token or GitHub App token limited to the repository, with **Contents**, **Pull requests**, **Issues**, **Actions** and **Workflows** set to read and write. Pull requests and pushes made with the default `GITHUB_TOKEN` start no workflows, so the train's checks would never run. A fine-grained token cannot read check runs, so the train reads them with the workflow's own token: give the job `checks: read`. 4. In the default branch's ruleset, require the checks, but do not enable "Require branches to be up to date before merging": the train already proves the exact tree that lands. To make the train the only way in, restrict updates to the default branch to the train's token identity. ### Action reference `uses: Looted/kibi/actions/merge-train@` | Input | Default | Meaning | | --- | --- | --- | | `base` | repository default branch | Branch the trains merge into. | | `checks` | required | Required check names, one per line, or comma separated on a single line. A check name with a comma needs one name per line. | | `train-checks` | `""` | Checks a train must also pass before it lands, but a pull request does not need to board. | | `label` | `train` | Label that boards a pull request. | | `max` | `8` | Most pull requests in one train. | | `kibi` | `node_modules/.bin/kibi` | Command that runs the default branch's Kibi. `""` skips `kibi sync`. | | `check` | `$KIBI check` | Shell command run in the train after each merge. `$KIBI` and `$KIBI_BRANCH` are set; `GH_TOKEN`, `GITHUB_TOKEN` and the Actions runtime tokens are not, since the train holds pull request content. Point a script at the base checkout (`sh ${{ github.workspace }}/scripts/gate.sh`) so the train's copy never runs. `""` runs none. | | `prefix` | `merge-train/` | Branch prefix of train branches. | | `github-token` | `github.token` | Token `gh` uses, except to read check runs. | | `checks-token` | `github.token` | Token `gh` reads check runs with. Fine-grained personal access tokens cannot read them; the job needs `checks: read`. | The action needs Node.js 22.6 or newer, `git` and `gh`. Outside GitHub Actions the same logic is `actions/merge-train/merge-train.mts`, configured through the `MERGE_TRAIN_*` environment variables described at the top of the file. ## Troubleshooting **The workflow succeeds but `https://OWNER.github.io/REPOSITORY/kibi-report/` is 404.** Enable **Settings → Pages → Source → GitHub Actions**. Until that is set, Pages deployments do not go live. The report is not at the Pages site root. **The badge image is a broken picture in the README.** The SVG URL must be anonymously reachable. Private Pages sites will not render in public READMEs. Confirm `/kibi-report/badge.svg` loads in a logged-out browser. **The workflow is skipped on every feature-branch push.** Report generation runs on `pull_request`, `workflow_dispatch`, or a push to the repository **default** branch. Pushes to other branches start the workflow and then skip the jobs. Open a pull request to validate a candidate report, change the GitHub default branch, or use **Run workflow** for a one-off publish. GitHub Pages still deploys only from the default branch or `workflow_dispatch`. **`kibi: command not found` or `npm exec -- kibi` fails.** Install `kibi-cli` as a project dependency and commit the lockfile. The workflow does not install Kibi globally. **`Kibi could not find a usable SWI-Prolog`.** The workflow relies on the bundled runtime that `npm ci` installs on `ubuntu-latest` (Linux x64, glibc). It is missing when the install skipped optional dependencies (`--omit=optional`, `--no-optional`, pnpm `supportedArchitectures` that excludes the runner's platform) or the lockfile lacks the platform package. Install with the package manager's defaults, or add `kibi-swipl-linux-x64-gnu` explicitly. On a runner without a bundled build (Alpine/musl containers, self-hosted Windows arm64 runners), install SWI-Prolog 9.0+ from the [SWI-Prolog PPA](install.md#ubuntu-recommended) or your platform package manager and put `swipl` on `PATH`; see [Installation](install.md#which-swi-prolog-kibi-uses). **Pages published the wrong site / two Kibi workflows.** A repository can host one Pages site. Keep either `kibi-report.yml` or `kibi-badge.yml`, not both. **`kibi init --github` did not overwrite my workflow.** If `.github/workflows/kibi-report.yml` already exists and differs from the template, Kibi leaves it in place. Compare it with [docs/examples/github/kibi-report.yml](examples/github/kibi-report.yml). **Owner/repository could not be determined.** `kibi init --github` only parses `github.com` remotes (HTTPS or SSH). GitHub Enterprise hosts are not auto-filled. The workflow is still written; paste the printed badge Markdown after replacing `OWNER`/`REPOSITORY`. --- # Troubleshooting URL: https://getkibi.dev/guide/troubleshooting.html > Recovery procedures for setup problems and broken Kibi state. ## Upgrading and branch recovery Kibi is in beta. Package upgrades do not require deleting the knowledge base. `kibi migrate` previews a structured plan and applies approved schema and storage updates. `kibi status` reports when the current branch is waiting on that plan. 1. **Check the branch:** ```bash kibi status ``` 2. **Preview the migration:** ```bash kibi migrate --dry-run ``` 3. **Apply it.** `--yes` applies the plan without a prompt. `--apply-safe` applies only approved deterministic actions and requires the plan hash from the preview. See [kibi migrate](cli-reference.md#kibi-migrate). ```bash kibi migrate --yes ``` Migration upgrades entity schemas and the on-disk layout, including a leftover `documentation/` tree or `.kb/config.json`. It keeps authored knowledge. It does not wipe `.kb/`. When it rewrites or moves `.kb/symbols.yaml` it also refreshes the local `.kb/symbol-coordinates.yaml`; stage `.kb/symbols.yaml` with the migration. The schema 13 step removes `.kb/symbol-coordinates.yaml` from the Git index and gitignores it; commit that removal too. The pre-commit hook does not count symbols that only the migration changed (legacy-link marks) as changed by that commit; it says so in a `Migration commit:` line. When a predicate fact is in the wrong namespace or still uses an old argument spelling, the same plan can move it to the only matching schema and rewrite that spelling to the declared constant. Review the plan hash before applying. Repairs that need a judgment stay as review items. If the compiled store for this branch is incomplete or unreadable, preview a rebuild before applying it. Recovery recompiles that store from authored sources and moves the previous bytes under `.kb/recovery/`. See [kibi branch](cli-reference.md#kibi-branch). ```bash kibi branch recover kibi branch recover --apply ``` `kibi sync` recompiles the branch store from the authored Markdown and manifests. Use it after you have fixed those sources. It is not the upgrade command, and deleting `.kb/branches` is not the upgrade path. ## Symbol Coordinates `.kb/symbol-coordinates.yaml` holds the source spans of your symbols. It is a gitignored local cache: every `kibi sync` re-extracts the symbols whose identity or source file changed, and a fresh clone builds it on its first sync. Never stage it. **`symbols_manifest_stale` from `kibi check --staged`:** a declaration the commit adds or changes has no `.kb/symbols.yaml` entry, the commit removed an entry, or an entry the commit adds, changes or orphans names a declaration that is gone. The Detail lines name them. Author the missing entries (`kibi upsert`, each with a `symbol_role`; only behavioral code needs `implements`), re-point or retire the orphaned ones, stage `.kb/symbols.yaml`, and retry. A declaration that only moved is never a finding, and unrecorded declarations the commit did not touch only print a non-blocking `Symbol records:` note. **`kibi check-generated --staged` says `.kb/symbol-coordinates.yaml` is staged:** the repository still tracks it from before schema 13. Run `kibi migrate --yes` (or `git rm --cached .kb/symbol-coordinates.yaml` and add it to `.gitignore`), then commit. **Coordinates look wrong locally:** `kibi sync --refresh-symbol-coordinates` rebuilds them from scratch. ## Dangling References If `kibi check` fails with `no-dangling-refs` violations: **Symptom:** - Check reports that entities reference IDs that don't exist - Relationships point to deleted or missing entities **Resolution:** 1. **Identify the dangling references:** ```bash kibi check ``` Note the specific entity IDs and relationship types reported. 2. **Fix the source files:** - Update Markdown frontmatter to use correct entity IDs - Verify that all linked entities actually exist - Remove relationships to deleted entities 3. **Re-sync:** ```bash kibi sync ``` 4. **Re-check:** ```bash kibi check ``` ## New Branch Reports an Empty KB Kibi compiles one store per branch and never copies another branch's. A branch created without the `post-checkout` hook (or checked out before `kibi init` installed it) has no compiled store, so `kibi check` reports a single `branch-store-not-compiled` violation, `kibi status` reports the `branch_store_not_compiled` stale reason and `kibi doctor` fails its "Branch store" check. Compile the branch: ```bash kibi sync ``` Run `kibi init` once to install the hooks so later branches compile on checkout. ## Git Hook Issues ### Hooks Not Installing If `kibi doctor` reports missing git hooks: 1. **Reinstall hooks:** ```bash kibi init ``` This reinstalls the hooks (pre-commit, post-checkout, post-merge, post-rewrite) by default. 2. **Verify hooks are executable:** ```bash ls -la .git/hooks/ ``` The hooks should be executable files (not just `.sample` files). 3. **Manually check hook permissions:** ```bash chmod +x .git/hooks/pre-commit chmod +x .git/hooks/post-checkout chmod +x .git/hooks/post-merge chmod +x .git/hooks/post-rewrite ``` ### Hooks Not Running If git operations don't trigger kibi hooks: 1. **Check hook files exist:** ```bash ls -la .git/hooks/ | grep -E "pre-commit|post-checkout|post-merge|post-rewrite" ``` 2. **Check hook content:** ```bash cat .git/hooks/pre-commit ``` Should resolve the kibi binary into `KIBI_BIN` and then invoke it (e.g. `"$KIBI_BIN" check --staged`). ### `kibi: not found` Inside Git Hooks Git runs hooks with your shell's `PATH`, which does **not** include `node_modules/.bin`. Kibi-managed hooks handle this by resolving the binary themselves: they check `PATH` first (global installs) and then walk up from the repository root looking for `node_modules/.bin/kibi` (project-local installs, including monorepo workspace roots). If you still see `kibi: not found` (or `cannot locate the kibi CLI`) from a hook: 1. **Confirm how kibi is installed:** ```bash command -v kibi ls node_modules/.bin/kibi ``` At least one of these must exist. If neither does, install kibi globally or add it as a project dependency. 2. **Regenerate the hooks with the current template:** ```bash kibi init ``` Hooks generated by older kibi releases invoked bare `kibi` and fail for project-local installs; re-running `kibi init` replaces only the Kibi-managed section with the self-resolving template. 3. **Reinstall hooks:** ```bash kibi init ``` Re-running `kibi init` also refreshes `.gitignore` entries for `.kb/`. ### Hook Conflicts If you have existing git hooks that conflict with kibi: **Warning:** Re-running `kibi init` overwrites Kibi-managed hooks. Make sure to back up custom hook logic first. 1. **Backup existing hooks:** ```bash cp .git/hooks/pre-commit .git/hooks/pre-commit.backup cp .git/hooks/post-checkout .git/hooks/post-checkout.backup cp .git/hooks/post-merge .git/hooks/post-merge.backup cp .git/hooks/post-rewrite .git/hooks/post-rewrite.backup ``` 2. **Install kibi hooks:** ```bash kibi init ``` 3. **Manually merge (if needed):** Edit the hook files to combine both your existing hooks and kibi hooks. ## KB Corruption If `kibi sync` or `kibi query` produce errors: 1. **Check the environment:** ```bash kibi doctor ``` It confirms a usable SWI-Prolog 9.0+ (and whether it is the bundled build, `KIBI_SWIPL`, or `swipl` on `PATH`), the `.kb/manifest.json` shape, and any leftover `.kb/config.json` that `kibi migrate --yes` should retire. 2. **Clear stale engines and locks.** A crashed engine or a removed worktree can leave a daemon or branch-store lock behind. Preview first, then apply: ```bash kibi engine janitor kibi engine janitor --apply ``` 3. **Recover the branch store.** Recovery recompiles the store from authored sources and keeps the previous bytes under `.kb/recovery/`: ```bash kibi branch recover kibi branch recover --apply ``` ## `kibi: repaired branch store` on stderr Kibi releases before 2026.11.5 could save a branch store snapshot that held some triples twice. That showed up as superseded `kb_search` answers, `strict-fact-shape` reporting several value fields on one fact, doubled relationships, or fields missing from entities, and it came and went with SWI-Prolog's garbage-collection timing. The first time a current engine attaches such a store, it keeps one copy of each duplicated triple, rewrites the snapshot, prints ```text kibi: repaired branch store : removed duplicate copies of triples ( loaded) ``` on stderr and records the repair in the store's `.kibi-store-repair.json`. Nothing needs fixing. For seven days after the repair, `kb_status` lists a `branch_store_repaired` notice and `kibi doctor` shows its Branch store check as a warning, so that you can recheck answers or check results obtained before the repair. The notice and the warning go away on their own. ## One engine daemon for several clients CLI commands and MCP calls for one workspace and branch share one detached engine daemon, which exits after ten idle minutes (see [`kibi engine`](cli-reference.md#kibi-engine-statusstopjanitor)). A client uses the running daemon only when it was started with the same Kibi package versions, the same Prolog core (compared by a digest of its sources) and the same SWI-Prolog; otherwise the client stops that daemon and starts its own. Two installs of the same release, such as a project-local and a global one, therefore share a daemon, while an older install started from a git hook is replaced by the newer one. - `kibi engine status` shows the daemon that serves this workspace and branch, and `kibi doctor` reports its package versions. - A `rdf/lock` file while a daemon is alive is expected, not stale. `kibi engine stop` releases it now; a lock whose process is gone is reclaimed by the next engine, and `kb_status` then lists a `store_lock_taken_over` notice for 24 hours. - Clients find the daemon through a socket in `KIBI_RUNTIME_DIR`, else `XDG_RUNTIME_DIR`, else a per-user temp directory. Two processes with different values (for example an agent sandbox and your terminal) cannot see each other's daemon and contend for the store lock; give them the same runtime directory. ## Configuration Issues Kibi does not accept user-configured entity paths or persistent check disabling. Knowledge lives under canonical `.kb/` lanes (`requirements/`, `scenarios/`, `tests/`, `facts/`, `adr/`, `flags/`, `events/`, plus `symbols.yaml`). If `kibi sync` doesn't find your documents: 1. Confirm they are under `.kb//`, not a relocated `documentation/` tree. Legacy `documentation/` knowledge is migrated with `kibi migrate --yes`. 2. Executable e2e harnesses stay outside the knowledge lanes (for example `documentation/tests/e2e/`). Only `TEST-*.md` belongs in `.kb/tests/`. 3. `--rules` on `kibi check` is an invocation-time diagnostic filter only; it does not persist. ## Environment Diagnostics Run comprehensive diagnostics: ```bash kibi doctor ``` This checks: - SWI-Prolog runtime: its source (bundled, `KIBI_SWIPL`, or `PATH`), path, version, and that every required library loads - `.kb/` directory existence - `.kb/manifest.json` validity - leftover `.kb/config.json` that still needs migration - Git repository presence - Git hooks installation ## Agent CLI JSON route failures The dedicated CLI JSON routes are peer operation access for agents that do not have visible MCP tools. - Exit `2` means invocation or input validation failed. Confirm `--input ` is present, the JSON root is an object, and no business flag or positional argument is mixed with JSON mode. - Exit `1` means validated operation execution failed. Inspect `Error [CODE]: detail` on stderr, then check SWI-Prolog, branch freshness, filesystem permissions, or network availability as appropriate for that operation. - Exit `0` writes one structured JSON value to stdout. If an integration expects a table or prose, use the human flag mode instead of `--input`. Use a project-local binary (`npm exec -- kibi`, `pnpm exec kibi`, or `yarn exec kibi`) so CLI and MCP resolve the same package versions. ## OpenCode shows "workspace needs Kibi bootstrap" before the TUI ### Symptom When launching OpenCode in a workspace that already has a canonical `.kb/` layout, you see a red error message saying "workspace needs Kibi bootstrap" before the TUI appears. ### Root Cause Health is determined by `.kb/manifest.json` plus the canonical knowledge lanes under `.kb/`. Relocated `kibi-docs/*` paths in leftover `.kb/config.json` are ignored. The false positive usually means the cached `kibi-opencode` plugin is older than the canonical-layout build, or the repo still needs `kibi migrate --yes`. ### Inspection Commands Check the cache plugin version: ```bash cat ~/.cache/opencode/node_modules/kibi-opencode/package.json ``` ### Recovery Run `kibi migrate --yes` if knowledge still lives under `documentation/` or leftover `.kb/config.json` is present. Then clear only the `kibi-opencode` plugin cache: ```bash rm -rf "$HOME/.cache/opencode/node_modules/kibi-opencode" "$HOME/.cache/opencode/bun.lock" ``` Then restart OpenCode. ### Verification After clearing the cache and restarting OpenCode, run from your workspace: ```bash timeout 20s opencode >/tmp/opencode-start.stdout 2>/tmp/opencode-start.stderr grep -i "bootstrap" /tmp/opencode-start.stderr ``` If the grep returns nothing, the issue is resolved. ### If the Problem Persists If the false warning returns after clearing the cache, the published npm package may still contain the bug. Check for a newer version: ```bash npm view kibi-opencode versions ``` If you're on an old version, upgrade when a patch is available. Do not repeatedly clear the cache on the same broken version. ## MCP startup resolves a stale kibi-mcp path ### Symptom MCP startup fails with a path resolution error pointing to an old `kibi-mcp` version, such as an older `node_modules/.pnpm/kibi-mcp@` directory. This happens after upgrading `kibi-mcp` in a project that previously used pnpm or `npx -y`. ### Root Cause The MCP configuration or a package manager cache still references a stale path. `npx -y`, `pnpm dlx`/`pnx`, `yarn dlx`, and `bunx` without `--no-install` can mix local dependency resolution, registry fetches, and package-manager cache behavior in ways that produce ambiguous or outdated paths. Project-local execution avoids this by resolving only what is already installed in the project (`npx --no-install` / `npm exec --no -- ...` for npm, `pnpm exec` for pnpm, `yarn exec` for Yarn, or `bunx --no-install` for Bun). These commands only control package resolution. They do not make parallel agents share or isolate an MCP process; the MCP client starts and owns the stdio server subprocess according to its own lifecycle. ### Evidence-First Recovery Do NOT delete all caches or `node_modules` as a first step. Capture evidence, inspect, and clean only what the evidence points to. 1. **Capture resolution evidence:** ```bash npx kibi-mcp --print-resolution ``` This prints the resolved binary path and version. If it points to a version older than what your `package.json` declares, the cache or config is stale. 2. **Inspect project lockfile and MCP config:** ```bash grep "kibi-mcp" pnpm-lock.yaml cat .vscode/mcp.json # or opencode.json ``` Confirm the lockfile lists the expected version and that the MCP config uses the local runner for your package manager, not an auto-install/hot-load command such as `npx -y` or `pnpm dlx`. For workspaces that intentionally run Kibi from a local checkout, also confirm the MCP config points at the checkout wrapper or binary directly. A command such as `pnpm exec kibi-mcp` resolves the application repository's installed `node_modules` package, not an external Kibi checkout. 3. **Targeted cleanup (only if evidence confirms a stale cache):** ```bash rm -rf "$HOME/.cache/opencode/node_modules/kibi-opencode" "$HOME/.cache/opencode/bun.lock" ``` Then restart your editor or OpenCode session. ### Verification After cleanup, rerun the evidence capture: ```bash npx kibi-mcp --print-resolution ``` The path should now match the version in `pnpm-lock.yaml` or `package-lock.json`. --- ### Interpreting Sync Failures in OpenCode When a background sync fails in OpenCode, the plugin logs an operational error with diagnostic metadata. To debug these failures, check the structured logs for the following fields: - `syncStdout`: The captured standard output from the kibi sync command. - `syncStderr`: The captured standard error from the kibi sync command. Often contains SWI-Prolog errors or file permission issues. - `syncErrorMessage`: The underlying system error message if the command failed to execute. **Idle Sync Suppression**: To prevent terminal noise, the plugin suppresses background sync attempts triggered by session idle after a `scheduler_sync_failed` event is latched for the session. Syncs will still be attempted when you edit files or execute tools, which provides opportunities for recovery once the underlying issue is fixed. To verify behavior or capture detailed logs, start OpenCode with stderr redirection: ```bash opencode 2> opencode-debug.log ``` Look for entries prefixed with `[kibi-opencode]` and check for the `scheduler_sync_failed` cause in the runtime overlay metadata. ## Recovery Steps Summary For installation issues, see the [install guide](install.md). | Issue | First Try | If That Fails | |--------|-----------|----------------| | Errors after an upgrade | `kibi migrate --dry-run`, then `kibi migrate --yes` | `kibi branch recover --apply` | | Stale engine or lock | `kibi engine janitor` | `kibi engine janitor --apply` | | Dangling references | Update source files with correct IDs | Verify and `kibi sync` | | Hooks not working | `kibi doctor` | `kibi init` | | Sync finds no docs | Confirm knowledge lives under `.kb//` | Run `kibi migrate --yes` if leftover `documentation/` still holds knowledge | | SWI-Prolog errors | `kibi doctor` | Add the missing `kibi-swipl-` package, set `KIBI_SWIPL`, or install SWI-Prolog 9.0+ per the [install guide](install.md) | --- *For CLI command syntax and options, see [CLI Reference](cli-reference.md)* --- # Usage telemetry URL: https://getkibi.dev/guide/telemetry.html > What anonymous usage statistics Kibi sends, what it never sends, and how to turn it off. Kibi sends anonymous usage statistics so its maintainers can see which operations people run, how long they take and how they fail. It is on by default, tells you so the first time it runs, and is easy to turn off. ## Turning it off Any one of these turns telemetry off: - `kibi telemetry disable`, which saves the choice for your user account and deletes any events still waiting to be sent. `kibi telemetry enable` turns it back on, and `kibi telemetry status` shows the current state and why, the channel events carry and where it comes from, and the host (`--format json`: `channel`, `channelSource` and `host`). - `KIBI_TELEMETRY=0` in the environment. - `DO_NOT_TRACK=1` in the environment. Telemetry is also off in CI and under test runners, even after `kibi telemetry enable`. Kibi treats a run as CI when `CI`, `CONTINUOUS_INTEGRATION`, `GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`, `CIRCLECI`, `TRAVIS`, `TF_BUILD`, `JENKINS_URL`, `TEAMCITY_VERSION`, `BITBUCKET_BUILD_NUMBER`, `CODEBUILD_BUILD_ID`, `DRONE`, `APPVEYOR`, `SEMAPHORE`, `BUILDKITE_BUILD_ID`, `CF_BUILD_ID` or `HEROKU_TEST_RUN_ID` is set, and as a test run when `NODE_ENV=test`, `JEST_WORKER_ID`, `VITEST`, `VITEST_WORKER_ID` or `NODE_TEST_CONTEXT` is set. It is off as well when the home directory (`HOME`) lies inside the system temp directory, which is how eval, packaging and end-to-end harnesses isolate each run. Only an explicit `KIBI_TELEMETRY=1` sends from those environments. The daily update check is separate from telemetry: it only reads `kibi-cli/latest` from the npm registry and sends no events. `KIBI_UPDATE_CHECK=0` or `NO_UPDATE_NOTIFIER=1` turns it off (see [Update notices](install.md#update-notices)). ## What is sent Kibi sends two kinds of event to its PostHog project in the EU region: - `kibi_operation`, once for each MCP tool call and each CLI command. It contains the interface (`mcp` or `cli`), the registered tool or command name (for example `kb_search` or `storage compact`), its outcome, its duration, the CLI exit code, and for a failure a fixed category: an error code such as `tool_timeout`, `stale_snapshot` or `upsert_dry_run_invalid`, or the names of the failing checks for `kibi doctor` (for example `doctor:git_hooks`). A category that isn't a fixed identifier is sent as `unclassified`. The outcome is `success`, `rejected` when Kibi refused the request on purpose (an invalid payload, check findings, a contradiction, a firm decision, a missing entity), or `error` when Kibi itself failed. For an `error`, the event also names the JavaScript class of the thrown error (for example `TypeError` or `SyncError`) when it is a plain identifier, never its message. It also says whether the workspace has a Git repository (`vcs`: `git` or `none`) and, without one, why (`vcs_reason`: `not_a_repository` or `git_unavailable`), so work without version control counts as a success rather than a failure. To show where agents struggle, `kibi_operation` events can also carry these signals, each a fixed name, a range or a yes/no: - for a refused payload, the rule it broke (a JSON Schema keyword such as `enum` or `required`, or a Kibi check such as `inventory_missing`), the field as a Kibi schema path with list positions as `*` (for example `relationships.*.type`; a field name no Kibi schema defines is sent as `other`), and how many issues it had (1, 2, 3 or 4+). For a dry run, the code of the refusal (for example `incomplete_propositions`). When the Kibi engine failed to start (`engine_start_failed`), the same field carries a fixed reason instead: the failing error's own code (for example `swipl_not_found`), `already_listening`, `store_locked`, `journal_unreadable`, `prolog_module_load_failed`, `branch_attach_failed`, `invalid_branch`, `daemon_exited`, `diagnostic_unreadable` or `daemon_error`; - for an upsert, whether it was a dry run, how many relationships it carried (0, 1, 2-5 or 6+), and which attempt it was on the same entity within 10 minutes (1, 2, 3 or 4+) with how the previous attempt ended; - for a search, how many results it found (0, 1, 2-5, 6-10 or 11+), whether it abstained, whether it showed concept hints, and whether another search ran in the same workspace in the previous 2 minutes; - whether a Kibi skill (for example `kibi-usage`) was loaded in the same workspace in the last 30 minutes, through a host hook, the CLI or the MCP server. The workspace is the Kibi or git root the operation ran in (for the MCP server, the workspace that answered the call); a load in a parent directory does not count for the repositories below it; - for an `error`, where in Kibi's own code it happened: the top stack frame inside a Kibi package as `package/module#function` (for example `kibi-cli/dist/commands/sync#syncCommand`), and a short fingerprint of the error class and the top three Kibi frames. Frames outside Kibi's packages, file paths, line numbers and messages are dropped. Retries, repeated searches and skill loads are recognised from one-way hashes of the workspace path and the entity's type and id, kept in `telemetry-recent.json` next to the queue for at most 30 minutes. The hashes never leave your machine. - `kibi_hook`, once for each Kibi hook decision in Claude Code, Codex, Cursor, ZCode or OpenCode. It contains the hook event, the action Kibi took (for example `read_snippet` or `edit_silent`), the kind of path touched (`source`, `test`, `kb`), the Kibi operation a tool call ran, whether Kibi had already been used in the session, and how many requirements the touched file implements. When a tool call loads a Kibi skill, the action is `skill_loaded` and the event names the skill (one of Kibi's own skills, else `other`). Every event also carries: - the Kibi package and its version, and the host agent (for example `claude-code` or `cursor`). Hook events name the host whose hook ran. The MCP server takes it from the launcher's `KIBI_MCP_HOST` or the client name the MCP host sends. The CLI takes it from `KIBI_HOST`, else from the variables hosts set for the processes they start (`CLAUDECODE`, `CURSOR_AGENT`, `CODEX_SANDBOX`, `GEMINI_CLI`, `OPENCODE`, `AI_AGENT`). Those variables are inherited, so a shell started from an agent's terminal, or a harness that runs inside one, counts as that agent; the CLI cannot tell it apart from the agent's own commands. Set `KIBI_HOST` to name the host yourself. `kibi telemetry status` shows the host and channel this shell's events carry; - whether it runs in a hosted cloud workspace (`CLAUDE_CODE_REMOTE`, GitHub Codespaces or Gitpod); - the channel the run comes from: `release` for an installed Kibi package, `source` when Kibi runs from a checkout of its own repository (Kibi's development, its own hooks and test rounds built from source), or the value of `KIBI_TELEMETRY_CHANNEL` when a harness sets one (for example `agent-test`), so that test and development runs can be told apart from real usage; - the operating system, CPU architecture, and JavaScript runtime with its major version; - the event format version (`telemetry_version`, currently 2; events without it come from Kibi versions that counted refusals as errors and sent none of the signals above); - a random install id, created on first use and stored only on your machine; - a one-way hash of the host's session id, so events from one agent session can be grouped. Hooks take it from the host's hook input. The CLI and MCP server take it from `KIBI_SESSION_ID`, `CLAUDE_CODE_SESSION_ID` or `CODEX_THREAD_ID` when the host sets one; otherwise they use the session a Kibi hook reported for the same workspace in the last 30 minutes. Hooks keep that link in `telemetry-sessions.json` next to the queue, as hashes of the workspace path and the session id only. Without a host, events carry no session. ## What is never sent Kibi never sends source code, file paths, file names, search queries, entity ids or titles, requirement text, KB content, error messages, repository or branch names, or anything else you typed. Events don't create PostHog person profiles, and GeoIP lookup is disabled. The detailed diagnostic log that `KIBI_DIAGNOSTIC_MODE` writes to `.kb/usage.log` is separate. It stays in your workspace and is never sent. ## How it is sent Events are appended to a queue file in your user state directory (`$XDG_STATE_HOME/kibi` or `~/.local/state/kibi`; `%LOCALAPPDATA%\kibi` on Windows). They are sent in batches: - by the MCP server every minute and when it shuts down; - by every host's Kibi hook once a batch is due, and right away at the end of a turn (Claude Code's `Stop`, Codex's and ZCode's `Stop`, Cursor's `stop`); - by the CLI once a batch is due (20 events, or the oldest is five minutes old). A send waits at most 1.5 seconds. If it fails, the events are kept for the next attempt, and they are dropped once they are older than seven days. Telemetry never changes a command's output or exit code. `KIBI_TELEMETRY_DIR` moves the queue and settings. `KIBI_TELEMETRY_HOST` and `KIBI_TELEMETRY_KEY` send to another PostHog project, such as your own. --- # CLI reference URL: https://getkibi.dev/reference/cli.html > Every kibi CLI command, flag, and dedicated JSON operation route, command by command. This document provides complete command-by-command documentation for the kibi CLI. The CLI is both a human-facing command surface and an agent-accessible peer of MCP. ## Dedicated JSON operation routes The CLI exposes the canonical public operation catalog as a peer to MCP. Every route accepts one JSON object through `--input `, where a path is resolved from the current working directory and `-` reads standard input exactly once. JSON mode writes one structured JSON value followed by a newline to stdout. Every route also takes `--schema`, which prints the JSON Schema its input is validated against, with each field and its allowed values. When a route rejects its input with `VALIDATION_FAILED`, the message names each failing field and points at `--schema`. Commands that accept `--format json` also accept `--json` as an alias; combining `--json` with another `--format` value is an error. ```bash # Read an input object from a file kibi query --input request.json # Read the same object from stdin printf '%s\n' '{"query":"login","limit":10}' | kibi search --input - ``` The input root must be a JSON object that matches the corresponding operation schema. In JSON mode, do not also pass business flags or positional arguments; mixed input is rejected. Optional `_diagnostic_telemetry` is transport metadata and is removed before business-schema validation. Add the global `--diagnostic-mode` flag to append the operation outcome to `.kb/usage.log`; supplied opaque `session_id` and `actor_id` fields are preserved for workflow correlation. | Operation | Dedicated CLI route | | --- | --- | | `kb_skills_list` | `kibi skills-list --input ` | | `kb_skills_load` | `kibi skills-load --input ` | | `kb_skills_read` | `kibi skills-read --input ` | | `kb_skills` | `kibi skill --input ` | | `kb_query` | `kibi query --input ` | | `kb_search` | `kibi search --input ` | | `kb_status` | `kibi status --input ` | | `kb_find_gaps` | `kibi find-gaps --input ` | | `kb_coverage` | `kibi coverage --input ` | | `kb_graph` | `kibi graph --input ` | | `kb_semantic_advisor` | `kibi semantic-advisor --input ` | | `kb_model_requirement` | `kibi model-requirement --input ` | | `kb_suggest_predicates` | `kibi suggest-predicates --input ` | | `kb_model` | `kibi model --input ` | | `kb_plan_bootstrap` | `kibi plan-bootstrap --input ` | | `kb_compile_intent` | `kibi compile-intent --input ` | | `kb_apply_plan` | `kibi apply-plan --input ` | | `kb_ingest_proof` | `kibi ingest-proof --input ` | | `kb_validate_upsert` | `kibi validate-upsert --input ` | | `kb_upsert` | `kibi upsert --input ` | | `kb_record` | `kibi record --input ` | | `kb_delete` | `kibi delete --input ` | | `kb_check` | `kibi check --input ` | | `kb_review_firm_edit` | `kibi review-firm-edit --input ` | | `kb_prepare_impact_review` | `kibi prepare-impact-review --input ` | | `kb_author_impact_review` | `kibi author-impact-review --input ` | | `kb_sparql_remote` | `kibi sparql-remote --input ` | The MCP catalog has 19 tools rather than one per operation, and a session lists all of them at level `test` unless the `core` profile is chosen (at level `remember`, `full` lists only the knowledge tools; see the [MCP reference](mcp-reference.md#tool-list)); under `core` or `remember`, the rest run through the routes above with the same input. The consolidated routes `kibi skill` and `kibi model` match the MCP tools `kb_skills` and `kb_model`, and the narrower routes stay available: - `kibi skill` takes `action: "list" | "load" | "read"` plus `id` and `resource`, and returns the routed operation's payload with `action`. - `kibi model` takes `mode: "analyze" | "requirement" | "predicates"` plus the inputs of `semantic-advisor`, `model-requirement`, or `suggest-predicates` (`text` is always required), and returns that operation's payload with `mode`. - `kibi upsert` refuses a fact write that makes two current requirements grounded on the fact contradict where they did not before, and lists the other current requirements on the quantity a value fact write changes under `siblings`, each also a warning and a required `nextActions` entry; the dry run does both without writing. `kibi apply-plan` runs the contradiction check once after every step. See [Writes the contradiction check refuses](inference-rules.md#writes-the-contradiction-check-refuses). - `kibi upsert` accepts `"dryRun": true`: it runs the `validate-upsert` checks, writes nothing, and returns the validation payload plus `dryRun: true` and `skippedEffects`. With `"plannedFacts": [...]` (the `applyPlan` entries of `kibi model`) the dry run stages those fact writes first, so a grounding link to a fact that does not exist yet validates and the contradiction preview sees the KB as it would be after the batch (`stagedFacts`, `whatIf`). `plannedFacts` without `dryRun` is rejected. - `kibi record` records a stated rule (`statement`, `why`, `saidBy`, `quote`, `code`, `test`) as one `kibi upsert` payload, then runs `kibi check --changed` over the files `code` names and returns the payload, the write result, the verdict (`commitAllowed`, findings with `blocks`) and the remaining `nextActions`. `"dryRun": true` returns the payload and writes nothing. Other fields are refused with a pointer to `kibi upsert`. See the [MCP reference](mcp-reference.md#kb_record). - `kibi delete` accepts `"dryRun": true`: a relationship or direct entity delete runs its preflight, writes nothing, and returns `outcome: "dry_run"` with `wouldDelete`, the `sourceWrites` a commit would make, and `skippedEffects`. An id authored in a Markdown or YAML source is never deleted directly: the route writes nothing and returns `outcome: "plan_returned"` with `deletionPlan` and a `nextActions` entry whose `input` is the exact `kibi apply-plan` input (`{"plan": …, "approvedPlanHash": …}`). Pass that unmodified, or rerun `kibi delete` with the same `ids` and `"approvedPlanHash"` set to `deletionPlan.planHash` to apply it in one call (a stale or different hash fails with `DELETE_PLAN_HASH_MISMATCH` and writes nothing). An authored requirement returns `outcome: "supersession_required"` and a `kb_upsert` supersession next action instead. See the [MCP reference](mcp-reference.md#kb_delete) for every field. - `kibi apply-plan` with `"recoveryJournalId": "bootstrap-…"` resumes a bootstrap plan whose process died mid-action without journal edits: the interrupted action is re-applied and a source lock left by the dead process is reclaimed and recorded in the journal. The MCP-only `async` field is ignored; the CLI always applies synchronously. ```bash printf '%s\n' '{"action":"load","id":"kibi-usage"}' | kibi skill --input - printf '%s\n' '{"mode":"predicates","text":"Admins may export audit logs."}' | kibi model --input - printf '%s\n' '{"type":"req","id":"REQ-auth-session-timeout","properties":{"title":"Session timeout","status":"open"},"dryRun":true}' | kibi upsert --input - printf '%s\n' '{"statement":"Sessions must expire after 30 idle minutes.","why":"Reason not stated","saidBy":"agent","code":[{"file":"src/session.ts","symbol":"expire"}],"dryRun":true}' | kibi record --input - ``` See the [MCP reference](mcp-reference.md#catalog-operations-mcp-calls-and-cli-routes) for the full catalog operation to MCP call to CLI route table. ### JSON-route exit codes | Exit code | Meaning | | --- | --- | | `0` | Input validated and the operation completed successfully. | | `1` | The operation started but failed, including Prolog, filesystem, network, or other runtime failures. | | `2` | Invocation or input error, including missing/unreadable input, malformed JSON, a non-object root, conflicting flags/positionals, unknown operations, or schema validation failure. | A failed route writes its JSON result with `status: "error"` and `error.code`, `error.message` on stdout, and one line on stderr naming the code and pointing to that message (`Error [CODE]: see error.message in the JSON result on stdout`), so the message is printed once. An input error found before the route runs (a missing or conflicting `--input`, unreadable or malformed JSON) has no JSON result and is written to stderr as `Error [CODE]: detail`. Failed routes do not write a success JSON object. ## `kibi init` Initializes Kibi repository infrastructure in the current directory. It does not infer or write product knowledge. Outside a Git repository `kibi init` sets up a workspace without version control: it writes `.kb/` and the agent instructions (which say to finish each change with `kibi check`, since there is no commit gate), installs no Git hooks and prints the `no_git_repository` advisory. After `git init`, run `kibi init` again to install the hooks; the knowledge recorded so far carries over. See [Working without Git](error-reference.md#working-without-git-no_git_repository-git_required). **Behavior:** - Creates `.kb/` directory structure with canonical knowledge lanes (`requirements/`, `scenarios/`, `tests/`, `facts/`, `adr/`, `flags/`, `events/`) - Installs git hooks (pre-commit, post-checkout, post-merge, post-rewrite) by default, into the directory Git reads hooks from (`git rev-parse --git-path hooks`), so linked worktrees and `core.hooksPath` are honored. Re-running `kibi init` refreshes only the kibi-managed section of each hook. A hook without a kibi-managed section (hand-written, husky, lefthook, ...) is never edited: init reports it as skipped and points at `--print-hook` so you can delegate from it yourself. When the repository uses a hook manager (lefthook, husky or the pre-commit framework), init installs no hooks at all and prints the manager configuration for every hook it does not visibly run Kibi's commands for yet; see [existing Git hooks and hook managers](install.md#existing-git-hooks-and-hook-managers). Hooks resolve the `kibi` binary at run time (PATH first, then `node_modules/.bin` walking up from the repository root), so they work with both global and project-local installs even though git does not put `node_modules/.bin` on the hook's `PATH`. - Ignores derived `.kb/` runtime state in `.gitignore` (`.kb/branches/`, `.kb/recovery/`, `.kb/proof/runs/`, `.kb/briefs/`, `.kb/migrations/`, `.kb/symbol-coordinates.yaml`, `.kb/usage.log`). Authored knowledge under `.kb/` stays tracked. `kibi migrate` also removes the pre-canonical blanket `.kb/` ignore stanza so migrated knowledge files are not left Git-ignored. - Creates Kibi-owned `.kb/manifest.json` (lifecycle metadata only; not a user configuration file) - Creates `.kb/symbols.yaml` (authored, committed) and the local `.kb/symbol-coordinates.yaml` cache when they do not already exist - Leaves `.kb/manifest.json` and `.kb/symbols.yaml` alone when a legacy `.kb/config.json` is present and points to `kibi migrate --yes`, which moves the existing knowledge and runs every schema step from the legacy version - Sets up what a fresh clone of the repository needs, following the [setup choices](#setup-choices) recorded in the project: a Kibi section in `AGENTS.md`, an `@AGENTS.md` import in `CLAUDE.md` and an `@./AGENTS.md` import in `GEMINI.md`, and a step in the root `package.json` `prepare` script that installs Kibi's git hooks on every dependency install **Flags:** - `--no-hooks` - Skip git hook installation (hooks are installed by default) - `--github` - Scaffold the documented GitHub Pages badge + full report integration (workflow, README badge, `kibi-report/` gitignore entry) - `--badge-only` - With `--github` only: publish the badge without the HTML report. Rejected if used alone. - `--print-hook ` - Print a copy-paste snippet that wires Kibi into an existing hook, then exit without writing anything. `` is one of `pre-commit`, `post-checkout`, `post-merge`, `post-rewrite`, or `all`. The shell snippet resolves the `kibi` binary the same way the managed hooks do (PATH, then `node_modules/.bin`), so it works with project-local installs, and runs the same commands as the managed template with failures propagated. For `pre-commit` that is `kibi check-generated --staged --changed-only` followed by `kibi check --staged`. - `--format ` - With `--print-hook` only: `shell` (default), `lefthook` (entries to merge into `lefthook.yml`), `husky` (one shell snippet per `.husky/` file) or `pre-commit` (local hooks for `.pre-commit-config.yaml`). Every format runs the same commands under the same conditions as the managed hooks. - `--auto-sync` / `--no-auto-sync`, `--prepare-hooks` / `--no-prepare-hooks`, `--agent-instructions` / `--no-agent-instructions`, `--ci-gate` / `--no-ci-gate` - Set and record a [setup choice](#setup-choices). A flag left out keeps the recorded choice. - `--level ` - Set and record the [Kibi level](#kibi-level): `test` or `remember`. An unknown level is refused before anything is written. Without it, a project that already records a level keeps it; otherwise init asks at a terminal (test recommended) and records `test` without one (CI, an agent's shell, a pipe). Changing an already-recorded level to a different value non-interactively requires `--change-level`. - `--change-level` - Explicitly confirm changing an already-recorded Kibi level when passing `--level ` non-interactively. ```bash kibi init --print-hook pre-commit >> .husky/pre-commit kibi init --print-hook all --format lefthook ``` ### Setup choices Git never clones `.git/hooks` or the compiled branch store, and agent plugins are installed per user, so a fresh clone gets Kibi's knowledge but nothing that tells an agent to use it. Four choices decide how much of that Kibi sets up on its own. The first `kibi init` records them in `package.json` under `kibi.setup` (or in `.kb/setup.json` when the repository has no root `package.json`; Kibi never creates one), and every clone, agent host and CI job reads the same answer. The bootstrap skill asks about them once. | Choice | Default | What it does | | --- | --- | --- | | `autoSync` | on | A query, check or write that finds this branch's store never compiled or out of date with tracked `.kb/` sources or the compiler contract compiles it first (a compile that writes nothing Git tracks), instead of answering from an empty or stale store. `KIBI_AUTO_SYNC=0` turns it off for one environment. | | `prepareHooks` | on | Adds a step to the root `package.json` `prepare` script that runs `kibi hooks install --quiet`, so installing the project's dependencies installs the hooks. The step does nothing when `kibi-cli` is not installed (a production `npm ci --omit=dev`), in CI, or outside a Git work tree, and never fails the install. It is not added when a hook manager owns the hooks or there is no root `package.json`. Yarn 2+ does not run `prepare` on install; there, run `kibi hooks install` after cloning. | | `agentInstructions` | on | Keeps a marked Kibi section in `AGENTS.md` (read by Codex, Cursor, OpenCode, ZCode and most other agents) an `@AGENTS.md` import in `CLAUDE.md` for Claude Code, and an `@./AGENTS.md` import in `GEMINI.md` for Gemini CLI. Text outside the markers is never touched, and neither is a file that is a symlink leaving the repository. | | `ciGate` | off | Adds `.github/workflows/kibi-check.yml` ([example](examples/github/kibi-check.yml)), which runs `kibi check` on every pull request. It can fail pull requests of a repository whose KB already has violations, so it is offered rather than defaulted. | `kibi doctor` reports a recorded choice that is not in place under "Fresh-clone setup"; `kibi init` applies it. ### Kibi level The Kibi level says how hard Kibi holds the coding agent to the requirements it records. It is a person's choice, recorded in `package.json` as `kibi.level` (or as `level` in `.kb/setup.json` when the repository has no root `package.json`). Only `kibi init` writes it; no MCP tool or JSON route does. | Level | What Kibi asks for | | --- | --- | | `test` (default) | Everything `remember` does, plus the scenarios and linked tests that show each requirement holds: `kibi check` and the commit gate run the verification rules (`evidence-floor`, `symbol-coverage`, `must-priority-coverage`, `must-positive-scenario`, `proof-contract-claims`, `proof-contract-symbols`). | | `remember` | Requirements, code links, capture, hooks, the firm-edit guard, the commit gate and the contradiction checks. No scenario, test or proof is asked for. | A project that sets no level is at `test`, which is what Kibi ran before levels existed. A value that is neither is read as `test`, and `kibi check` reports it as a `CONFIG_WARNING` diagnostic. At `remember`: - A current requirement whose `required_evidence` is `tested` or `proved` is reported by the advisory `required-evidence-above-level` rule (non-blocking) instead of enforced, and `kb_upsert`/`kb_record` refuse a write that raises `required_evidence` to `tested` or `proved`: a person chooses `test` first. - A requirement write's `nextActions` ask for the pair reviews and the `kb_model` step of its unmodeled claims (as at every level) and for no scenario, test or proof. - The MCP server does not list `kb_ingest_proof`, and `kb_skills` (and `kibi skills list`) does not offer `kibi-provable-code`, which still loads by id. The server lists only the knowledge tools, and names `kb_find_gaps`, `kb_coverage` and the planning tools as CLI commands instead (see the [MCP reference](mcp-reference.md)). The bootstrap skill has the agent ask the person for the level before it runs `kibi init --level `. **GitHub integration:** - `--github` by itself always means **badge + full report**. It copies the canonical workflow from the `kibi-cli` package (the same file as [docs/examples/github/kibi-report.yml](examples/github/kibi-report.yml)). That workflow generates the report on pull requests (artifact only) and deploys GitHub Pages only from the repository default branch or `workflow_dispatch`. - Re-running is safe: matching files are left as already configured; customized workflows are not overwritten; an existing Kibi badge is not duplicated. - If no README exists, the workflow is still written and the badge Markdown is printed. - If a github.com owner/repository cannot be determined from git remotes, the workflow is still written and placeholder badge Markdown is printed instead of inventing a URL. - After scaffolding, enable **Settings → Pages → Source → GitHub Actions**. See [GitHub badge + report](github-integration.md). **Notes:** - Hooks are installed by default. Only use `--no-hooks` if you specifically don't want automated syncing. - The pre-commit hook blocks commits that stage `.kb/symbol-coordinates.yaml` (it is derived locally and never committed) or a `.kb/symbols.yaml` that is not in the layout sync writes. - The pre-commit hook also blocks behavior-changing source edits that lack staged Kibi impact evidence (KB entity docs, authored `.kb/symbols.yaml` entries, or a symbol manifest that already covers every declaration the commit adds or changes in the edited file). Test-only and docs-only edits are exempt. - The pre-commit hook also blocks a commit whose staged knowledge introduces a `domain-contradictions`, `scenario-feasibility`, `exception-claim-keys` or `kb-consistency` violation, the same finding full `kibi check` reports on that tree. A violation already present at the last commit does not block an unrelated commit. - The pre-commit hook also runs the requirement-scoped blocking rules on the entity documents the commit stages, from the KB schema that blocks each: `claim-subject-missing`, `claim-subject-undefined` and `subject-definition-missing` (schema 16), `must-positive-scenario` (schema 17, except requirements the upgrade recorded) `related-requirement-unmodeled` (schema 18, run only when a staged requirement has an unmodeled claim) and `quantity-duplicate` (schema 19; a pair counts when the commit stages one of its facts or the requirements grounding them, and a `distinct_from` entry naming no value fact counts on its fact). A finding on an entity the commit does not stage, or one the same entity already had at the last commit, does not block. - At [Kibi level](#kibi-level) `remember` the pre-commit hook runs no verification rule: no `evidence-floor`, `must-positive-scenario` or `symbol-coverage` on the staged change. At `test`, a requirement the commit adds while it is below its floor is reported as a non-blocking evidence floor finding, not refused, so it can land before the scenario and test that lift it. - The pre-commit hook also blocks a commit that adds a current requirement, or changes the fields that set its evidence floor (`status`, `priority`, `firmness`, `required_evidence`, `origin`), while that requirement is below its floor (`evidence-floor`) or is an implemented, unapproved agent-written must requirement past its grace period (`agent-requirement-unapproved-implemented`). The requirement's front matter and links are judged as staged: its evidence (tests, symbols, proof receipts) is read from the synced branch store, as `kibi check` reads it, through a private copy with the staged requirement document projected over the synced one, so an edit not synced yet (adding or removing `origin.approved_by`, say) is judged as it will be committed. A requirement the store does not hold yet is not judged; run `kibi sync` first. - The pre-commit hook also blocks a commit that adds or edits an entity document without the body context full `kibi check` requires (`entity-context-missing`). An entity that already lacked context at the last commit, or that the schema 8 migration acknowledged in `.kb/manifest.json`, does not block. - Idempotent: safe to run multiple times - After initialization, ask the coding agent to bootstrap the repository. The bootstrap planner owns discovery, approval, source-first application, and repair; `doctor` and `sync` are diagnostics/internal lifecycle operations. - After running, see the quick start guide in README.md for next steps ## `kibi hooks install` Installs Kibi's git hooks in this checkout, with the same guards as `kibi init`: only into a hooks directory inside the repository, never over a hook Kibi did not write, and not at all when a hook manager owns the hooks. It needs a repository where `kibi init` already ran. **Flags:** - `--quiet` - What the `prepare` script runs: print only when hooks were installed and always exit 0. It does nothing in CI (`CI` set), outside a Git work tree, before `kibi init`, or where a hook manager owns the hooks. ## `kibi sync` Extracts entities and relationships from project documents and updates the knowledge base. **Behavior:** - Extracts entities from Markdown files with frontmatter - Imports symbols from YAML manifests - Keeps the gitignored `.kb/symbol-coordinates.yaml` current: symbols whose identity or source file bytes changed since the last sync are extracted again and every other record is reused, so a no-op sync does no extraction. A fresh clone builds the file on its first sync. When extraction fails, sync warns and keeps the previous coordinates. - Rewrites a `.kb/symbols.yaml` whose `symbols` sequence is still in YAML flow layout (`symbols: [ { id: … }, … ]`, what kibi-cli before 2.18.0 produced by appending to the `symbols: []` that `kibi init` writes) in block layout once, keeping comments and order, so hook scanners and reviewers can read it; the summary line `Rewrote .kb/symbols.yaml in block layout` reports it - Updates KB for the current git branch - Runs validation rules on the updated KB - Prints a summary that opens with `KB Totals` (the entities the branch KB holds after the sync, by type) and `KB Relationships`, counted from the store, followed by `Imported This Sync (changed sources only)`: an incremental sync recompiles only changed sources, so that second block is a delta, not the size of the KB. Both blocks count distinct relationships: an edge stated in an entity's front matter and again in a symbol manifest or shard counts once. When the store cannot be counted, the summary shows the imported counts under `Entity Counts` as before **Flags:** - `--validate-only` - Perform validation without making mutations - `--rebuild` - Rebuild branch snapshot from scratch (discards current KB) - `--refresh-symbol-coordinates` - Re-extract every symbol's location into `.kb/symbol-coordinates.yaml` and rewrite `.kb/symbols.yaml` in its canonical layout. Plain sync already keeps coordinates current; use this to rebuild them from scratch or to normalize the manifest. Explicit refreshes are fatal on artifact errors, force coordinate-bearing symbols to persist even when normalized hashes match cached state, and only then advance the sync cache (version 2, workspace-root-relative keys; the artifact is a compiler dependency of `symbols.yaml`). A symbol that gets no coordinates is listed as `failed : `, and `kibi check` keeps reporting it under `symbol-coordinates-missing`. The refresh is refused (exit 1, stored coordinates kept) when a plugin activated for `kibi.symbol-extractor.v2` is not installed or is not the release-qualified build, the problems `kibi doctor` names. A TypeScript or JavaScript symbol whose title names a private class member (`Class.member` or a bare member name for a `private` or `#private` member) is never bound, because the symbol extractor that `kibi check --staged` uses skips private members; its reason says so and asks you to re-point the symbol to the public member or class that owns the behavior, or remove it. Full `kibi check` reports the same symbol under `symbol-granularity` when it has traceability links. Extraction misses are reported as failed, including Python and other files handled by the text heuristic. If a qualified symbol title cannot be located, query and validate/upsert a corrected title/sourceFile or an intentional `granularity_reason: extractor-miss` before refreshing. Coverage only offers automatic coordinate repair when current extraction or an explicit coarse anchor can produce coordinates. **Notes (sync + MCP):** - Rebuild with `--rebuild` replaces the on-disk branch KB snapshot while MCP can continue running. - A running MCP session detects same-branch snapshot replacement before serving affected operations. - If auto-refresh cannot complete during a transient publish conflict, MCP returns a recovery error; retry the tool call after the publish settles. **Notes:** - Supports these entity types: req, scenario, test, adr, flag, event, symbol, fact - **Modeling:** Use `flag` for runtime/config gates; record bugs and workarounds as `fact` entities, usually with `fact_kind: observation` or `meta`. **Strict facts** (subject, property_value) drive contradiction checks, while observation/meta facts are non-blocking notes. - Symbol manifests must be in YAML format - Changes are committed to the branch KB's audit log - A requirement whose stored semantic inventory no longer matches the current semantic advisor fails proposition-complete ingestion. Sync checks every requirement before it stops and lists all failing files in one error, then points at `kibi migrate`, which re-derives the inventories it can and lists the ones that need a manual fix. Normal sync is a delta compile into the running Node engine: unchanged source files are skipped, changed/deleted source entities are retracted and reasserted in the journal, and relationship shards are refreshed only when their content hash changes. `--rebuild` is the explicit generation-replacement path. ## `kibi engine status|stop|janitor` The engine is automatically started for CLI and MCP operations. `engine status` prints the workspace/branch daemon PID and journal status; `engine stop` asks it to flush and exit. A daemon is shared by all clients for the same canonical workspace path and branch and exits after ten minutes without clients. Clients find the daemon through a socket in `KIBI_RUNTIME_DIR`, else `XDG_RUNTIME_DIR`, else `/tmp/kibi-runtime` on Linux (the per-user `TMPDIR` on macOS). Processes that set these differently cannot see each other's daemon. The directory must be owned by you and private to you (`chmod 700`); when `KIBI_RUNTIME_DIR` names one that is not, Kibi prints a warning and uses a private directory under `/tmp` instead. When `engine stop` finds no daemon it says so, and names the pid still holding the branch store if there is one. `engine janitor` classifies stale engine daemons and branch-store locks left by crashed engines or removed worktrees. It only reports by default; `--apply` performs the cleanup, `--all` also sweeps daemon sockets from other workspaces, and `--format json|table` selects the output. It also reports stale-lock takeover records (`.kibi-lock-takeover.json`, kind `takeover-record`) older than the 24 hours `kb_status` shows them for, and `--apply` deletes them. ## `kibi storage status|compact|export` - `storage status` reports journaled mode, generation, commit sequence, and journal bytes. - `storage compact` explicitly compacts the RDF journal; idle engines also compact journals over 16 MiB. - `storage export --output ` writes derived legacy `kb.rdf` and `audit.log` files outside the active branch store. These exports are not authoritative and are never read by the engine. Node.js 22 or newer is required for both the CLI/MCP clients and the engine. Bun remains a repository build/test tool, but is not a supported runtime for the published Kibi packages. ## `kibi prove` Runs the configured proof producers and ingests valid `kibi.proof-run.v1` evidence. For each integration, the producer executes once (`shell: false`), the workspace snapshot is revalidated before and after, and the artifact is evaluated independently against every selected test's `kibi.proof-contract.v1` obligations. Derived `kibi.proof-receipt.v1` receipts append idempotently, and each append compacts that test's history to the receipts that can still decide proof (`kibi.proof-receipt-compaction.v1`): kept receipts are never edited or reordered, so coverage decisions do not change. ```bash kibi prove --all kibi prove --test TEST-checkout kibi prove --requirement REQ-checkout kibi prove --integration web-e2e kibi prove --integration web-e2e,api-tests kibi prove --all --integration-except heavy-suite kibi prove --stale kibi prove --requirement REQ-checkout --stale kibi prove --all --resume kibi prove --all --shard 2/3 kibi prove --all --list ``` Selectors: `--test`, `--requirement`, `--integration`, `--all` (default). `--stale` narrows the selection to tests without a current passing receipt (missing, stale, failed or contract-mismatched, judged as coverage judges them); when every selected test is current it runs nothing and says so. `--resume` skips integrations an interrupted run with the same selector already ingested at the current workspace snapshot (recorded in `.kb/proof/runs/prove-progress.json`); progress lines on stderr name each integration as it starts and is ingested. `--shard K/N` keeps the K-th of N disjoint parts of the selection (tests ordered by id and dealt out in turn, before `--stale` applies), so N parallel runs with `--shard 1/N` to `N/N` prove every selected test exactly once. `--list` prints the selected test ids as `{"tests": [...], "shard": "K/N"}` and runs nothing. With `--test`, `--requirement` or `--stale`, a `playwright` integration whose command is a direct `playwright test` invocation runs only the selected tests' `proof_bindings[].source_file` spec files; every producer also receives them as `KIBI_PROOF_SOURCE_FILES` (a JSON array). An integration that runs whole under these selectors is listed in the JSON summary's `notNarrowed` with the reason. `--integration` accepts one or more comma-separated integration ids. `--integration-except` is a modifier (it requires a selector such as `--all`) that skips tests bound to the listed integrations. A selector that matches no proof-bearing test is an error, so a typo cannot silently prove nothing. The last stdout line is a JSON summary: `passed` (passing receipts), `certified` (passing receipts whose certificate re-checked, the only ones that can support `proved`), `failed`, `unchanged`, and per-integration `runs` whose `results` carry each test's `kind`, `evidenceLevel` (`proved` or `tested`), `certificateRejection` and `claimBindings`. A certificate kind whose certificate does not re-check still passes, and stderr names it (`prove: TEST-x exhaustive: certificate rejected, `). Before this summary used `proved` for the passing count; that key is now `passed`. The exit code is non-zero when any proof fails or a producer errors. Producer child processes run with `KIBI_PROOF_RUN=1` (plus `KIBI_PROOF_OUTPUT`, `KIBI_PROOF_SNAPSHOT`, and other `KIBI_PROOF_*` variables). Runner configurations that need proof-run-aware behavior — disabling retries, for example — should branch on `KIBI_PROOF_RUN` instead of inferring a proof run from output-path variables. A `command` producer also receives `KIBI_PROOF_TEST_REPORT`. When it writes a `kibi.proof-test-report.v1` there, each test is evaluated against its own steps, so one failing step fails only the tests that own it. Each entry of the summary's `runs` then carries `attribution: "per_test"` and `failedSteps` (`testId`, `stepIndex`, `command`, `outcome`, `exitCode`). Without a usable report the run is evaluated as one unit (`attribution: "aggregate"`, with an `attributionReason`). See [per-test attribution](proving-requirements.md#per-test-attribution-for-command-integrations). Ctrl-C (or SIGTERM/SIGHUP) stops the producer's whole process group. ### `kibi proof run-steps [steps-source]` A ready-made `command` integration producer. Reads `{test_id, steps}` entries from the steps source: by default the `proof/steps` directory, with one `.json` file per test, or `proof/steps.json` (one JSON array) when that directory does not exist. A path argument may name either form. A file in the directory whose `test_id` differs from its file name is refused. It runs the steps of the tests `kibi prove` selected (`KIBI_PROOF_TEST_IDS`, or `--test ` when run by hand), each distinct argv once, and writes a `kibi.proof-test-report.v1` to `KIBI_PROOF_TEST_REPORT`. Exit code 0 when every step passed. Steps time out after `KIBI_PROOF_STEP_TIMEOUT_MS` (default 15 minutes). ```bash kibi proof run-steps # as an integration command kibi proof run-steps --test TEST-checkout ``` ## `kibi proof inspect` Detects languages, build systems, test frameworks (including `node --test` and `bun test` in the scripts of `package.json` and its workspaces), CI workflows, configured integrations, and the recommended integration level. Deterministic output for agents. While `.kb/proof/integrations.json` does not exist and a test runner is detected, the JSON also carries `proposedIntegration` (a `command` integration running the `package.json` `test` script, or the detected runner), `contractDefaults` for a test's `proof_contract`, and `integrationPlan`: a hash-bound `kibi.migration-plan.v2` that writes the file when applied with `kb_apply_plan` or `kibi apply-plan --input -` (pass `plan`, `approvedPlanHash` and `approvedActionIds`). `integrationPlanReason` says why there is no plan, or what applying it does. `--update ` plans adding or replacing one named integration in an existing file. `--command` proposes that command instead of the detected one (space-separated words, or a JSON array of argv strings; no shell quoting). Once the file exists, `currentIntegrations` lists each configured integration as `{ id, producer, command }` (the text output prints the command); `currentIntegration` keeps the comma-joined ids for older consumers. The integration only says how evidence is produced: whether a receipt counts toward `proofTested` depends on the test's `verification_scope` (see [proving requirements](proving-requirements.md)). A `command` integration is judged as one run: any failing test in it fails every proof obligation that names the integration. When the proposal runs the package's whole `test` script, `integrationPlanReason` says so and points at `--command` (with `--update ` once the file exists) to run only the proof-bearing tests, or at a `kibi.proof-test-report.v1` written to `KIBI_PROOF_TEST_REPORT` for per-test results. ```bash kibi proof inspect --json kibi proof inspect --update e2e --json kibi proof inspect --update unit --command "npx vitest run tests/e2e" --json ``` ### `kibi proof explain` Projects one requirement (`REQ-*`) or symbol (`SYM-*`) from the same `kibi.requirement-proof.v5` Proof that coverage uses. Human output labels `required_proofs`, `executable_for`, and `covered_by` as separate blocks so agents cannot treat them as one chain. `--json` emits the structured projection (primary plus optional secondary `covered_by` reasons). This command does not re-evaluate qualification. ```bash kibi proof explain REQ-EXAMPLE kibi proof explain SYM-EXAMPLE kibi proof explain --requirement REQ-EXAMPLE --json kibi proof explain --symbol SYM-EXAMPLE --json ``` See [proving requirements](proving-requirements.md) for the full workflow: proof contracts, integration configuration, the artifact reference, adapter authoring, and troubleshooting. Playwright is an optional first-party producer (`kibi-cli/playwright-reporter`); Kibi itself is runner-neutral. See [the proof ladder](proof-ladder.md) for what each proof stage and status means. ### `kibi proof compact` One-off migration for stores written before ingest compacted receipt histories. Applies the ingest policy (`kibi.proof-receipt-compaction.v1`) to every test against the live workspace snapshot and each test's current binding: it keeps the newest receipt, the newest passing receipt, and the newest receipt per scope and contract for the current binding and snapshot, so every coverage decision is unchanged. Only the `proof_receipts` block of each test document is rewritten. Histories that are not structurally valid are reported as skipped and left untouched. ```bash kibi proof compact --dry-run # report what would be removed kibi proof compact kibi proof compact --test TEST-E2E-EDITOR-001 --json ``` ### `kibi proof prune` Shrinks each test's `proof_receipts` history to its newest entries, keeping the newest `--keep ` (default 1) per test and reporting the before/after counts. Unlike `kibi proof compact`, prune counts receipts rather than asking which ones decide proof, so it can drop a receipt that coverage still selects. Pruned histories remain ordered, structurally valid evidence, and current-binding rules still apply to the newest receipt. ```bash kibi proof prune # keep the newest receipt per test kibi proof prune --keep 3 # keep the newest three kibi proof prune --test TEST-E2E-EDITOR-001 ``` ### `kibi proof migrate-legacy` Removes legacy `verification_receipts` frontmatter blocks from test documents that already carry a `proof_contract`. The old blocks contain stale snapshot hashes and make live-receipt greps error-prone. The block is spliced out of the authored document and the compiled property is dropped — nothing else in the document is rewritten. ```bash kibi proof migrate-legacy kibi proof migrate-legacy --test TEST-LEGACY-001 ``` ## `kibi query [type]` Queries entities from the knowledge base. **Syntax:** ```bash kibi query [type] [--id ID] [--tag TAG] [--source PATH] [--relationships ID] [--format json|table] [--limit N] [--offset N] ``` **Arguments:** - `[type]` - Optional entity type to query (req, scenario, test, adr, flag, event, symbol, fact) - `--id ID` - Query by exact entity ID - `--tag TAG` - Filter by tag - `--source PATH` - Filter by source file path substring - `--relationships ID` - Return relationships for a specific entity ID - `--format json|table` - Output format (default: json) - `--limit N` - Maximum number of results to return (default: 100) - `--offset N` - Number of results to skip (pagination) **Examples:** ```bash # List all requirements as table kibi query req --format table # Find specific test kibi query test --id TEST-mcp-search-discovery # Find all entities with "security" tag kibi query req --tag security --format table # Find entities linked to a source file path kibi query symbol --source src/auth/login.ts --format table # Show relationships for one entity kibi query --relationships REQ-cli-gc # Get paginated results kibi query scenario --limit 10 --offset 0 kibi query scenario --limit 10 --offset 10 ``` **Typed fact questions** use the JSON route (`kibi query --input -`) with the same fields as the `kb_query` MCP tool: `factKind` (`predicate_schema` lists the askable predicates), `predicate` with order-free `where` arguments, `polarity`, `scope`, `distinct`, or `subjectKey` with `propertyKey`. The answer carries the matching fact rows and a `factQuery` block with the schema, distinct counts, values that exist when nothing matched, warnings and the next call to run. ```bash printf '%s\n' '{"predicate":"permission_rule","where":{"actor":"admin"}}' | kibi query --input - printf '%s\n' '{"subjectKey":"user.role_assignment","propertyKey":"max_roles"}' | kibi query --input - ``` **Notes:** - Returns "No entities found" if query produces no results - Results are deterministically ordered - Type, ID, and tag filters can be combined ## `kibi search ` Asks the KB a question. Without `--type` (or `type`) it answers with five one-line decision cards for the requirements and ADRs that match best, ranked by the question's words, scope and supersession and, when the search-hints plugin is installed, by meaning too, with up to seven more decisions related by meaning in `queryAnalysis.hints`. A weak answer names no governing requirement and lists the words no card holds in `queryAnalysis.uncoveredTerms`. With a type (`fact`, `scenario`, `test`, `symbol`) it ranks those entities, ten rows by default. Both routes accept natural-language questions, host-agent facets and changed source locations, and add an answer layer; pass `"rankingMode": "legacy"` for lexical ranking. **Syntax:** ```bash kibi search [--type TYPE] [--format json|table] [--limit N] [--offset N] ``` **Notes:** - Searches markdown-backed knowledge and metadata - Does not search raw code file bodies - Use `kibi query` for exact follow-up lookups Intent mode is the default for `kibi search --input -`: ```bash printf '%s\n' '{ "query": "what governs downloading a report?", "semanticFacets": {"actions": ["export"], "objects": ["CSV file"]}, "sourceLocations": [{"path": "src/reports/export.ts", "line": 42}] }' | kibi search --input - ``` Typed intent results include `queryAnalysis` (with `ambiguous` read from `topRivalMargin`, the margin to the best match the top match is not linked to), matched semantic facets, source-location evidence (the requirements a located symbol `implements` match too), bounded traceability graph paths (with `fields: "full"` only), `count` (the whole ranking), `returned` (this page), `truncated`, and `abstained: true` when no result reaches `minScore` (default `0.18`). Superseded and deprecated entities are demoted, and a closed requirement ranks below a current one that matches as well (`demoted: closed`). Source paths must be workspace-relative. The host agent supplies facets; Kibi does not call a model. An abstained or weak first page that shows no hint also carries `nextActions` (a `kb_query` listing the requirement titles, `required: false`) and, when it abstained, `notes`; see the `kb_search` reference in [mcp-reference.md](mcp-reference.md). On the first page, `data.answer` (`kibi.search-answer.v1`, on by default; `"answer": false` turns it off) lists the current `governing` requirements with `via` and their linked `facts`, `scenarios`, `tests` (including scenario-backed tests, each with `via`), and `adrs`, plus each requirement's `verdict` (`contradiction`, `infeasible`, `unknown` or `none`, with the contradiction and scenario-feasibility `witnesses` that name it), `exceptions` (requirements that exempt it, with `approvedBy`) and `unknowns`; `rationale` ADRs with their `source` and a decision `excerpt`; `notGoverning` superseded or deprecated requirements with `supersededBy`; `observations` (notes, not rules); `ungoverned` matched facts, scenarios, symbols and tests no requirement owns, with their `rank` (when the top match is one, the `note` says the governing list came from lower-ranked matches) and, for an unlinked fact that disagrees with a governing requirement's fact on the same key arguments, `overriddenBy` naming the fact that holds; `scope` (`branch`, `snapshotId`, `syncedAt`); `truncated`; and a `note`. The layer follows graph links and runs the existing checks for the governing requirements only: it is discovery, not proof, and a `none` verdict means no check named the requirement. A negative-path fact (a situation a rejecting scenario assumes, which must not happen) carries `negativePath`, ranks below the requirement it guards and is titled `Forbidden: …` in the table output, the answer layer and search hints. See the [MCP reference](mcp-reference.md#kb_search) for details. ## `kibi status` Reports the current KB snapshot, branch, and freshness state. **Syntax:** ```bash kibi status [--format json|table] ``` JSON output also exposes `proofSnapshot`, availability, dirty state, file count, and `kibi.workspace-snapshot.v2` version. This deterministic snapshot is the identity coverage uses to accept or reject proof receipts; an unavailable snapshot fails proof closed. Receipt-only frontmatter changes are excluded from the hash so ingesting a receipt cannot invalidate its own proof. Status also reports the exact `branchAttachment` (`gitBranch`, `kbBranch`, `kind`, and `migrationRequired`), bounded `staleReasons`, and `proofSnapshotChanges`. A legacy attachment is read-compatible only; writes and sync are blocked until the sanctioned migration is applied. Dirty editor/config paths are reported rather than silently ignored. Sync stamps the compiler contract it used (a hash of the entity property schema) into the branch store. When the store was compiled by a CLI build with a different contract, for example an older build that dropped properties it did not know, status reports `syncState: "stale"` with a `compiler_changed` reason even though every source hash still matches. After upgrading to a CLI whose entity schema changed, every branch store compiled by the older CLI reports it once. The next `kibi sync` re-imports every source once and clears it, and the status migration plan covers it with its automatic `freshness-resync` action (`kibi sync`), so applying that action clears it too; it gets no review action of its own. While `.kb/manifest.json` records a KB schema older than this Kibi, the text output of `kibi status` and `kibi report` starts with one line (text `kibi check` starts with a note of its own that names `kibi migrate`): `Migration needed: this KB is at schema N and this Kibi expects schema M. Run 'kibi migrate' to review the upgrade, then 'kibi migrate --yes' to apply it.` JSON output carries the same information in `schemaStatus` and the migration plan instead. Status does not initialise a missing branch store or repair a damaged one. It instead returns `branchStore` (`missing`, `incomplete`, or `unreadable`) with a recovery-oriented stale reason. Use the explicit branch commands below after reviewing that diagnosis. Kibi compiles one store per branch and never copies another branch's, so a branch created without the `post-checkout` hook starts with no store (and the first engine attach creates an empty one, `generation-1:0`). While `.kb/` holds authored sources, status reports that state as one blocking stale reason, `branch_store_not_compiled`, whose remediation is `kibi sync` (the missing or empty store also reads `syncState: "stale"`), and the migration plan carries an automatic `branch-store-compile` action (`kibi sync`) that runs after `branch-store-ensure` and any schema upgrade. `kibi check` reports the same state once, as the canonical `branch-store-not-compiled` violation, instead of running rules against an empty KB (which used to report every authored relationship as a `source-relationship-parity` violation). When migration is needed, JSON status also returns `schemaStatus` and a `kibi.migration-plan.v2` `migrationPlan`. Actions are typed with a canonical `planHash`, dependencies, safety class, preconditions, postconditions, and exact operation/CLI guidance. Status remains read-only. The plan's `schema-config-upgrade` action runs `kibi migrate --yes`, so it declares everything that run writes. Its `affectedFiles` list `.gitignore` (the run adds the canonical derived entries) beside the manifest, config and `.kb/migrations`. When the schema is behind on the canonical `.kb/` layout, the authored-source rewrites the run performs are planned as their own actions, the same ones `kibi migrate --format json` lists, each with its own files: for example `symbol-legacy-link-mark` (`.kb/symbols.yaml`), `entity-origin-backfill`, `close-superseded-requirements` and `source-path-rewrite`. The upgrade depends on them, so approving it without them is refused, and their passes inside the run are no-ops. While the upgrade still moves legacy knowledge into `.kb/` or waits on an operator, it lists `.kb/` instead and says so in `evidence.sourceRewrites`. Applied through `kb_apply_plan`, the upgrade's `actionResults[].detail` is read from the migration audit record, for example `Migrated schema 8 -> 9 (audit .kb/migrations/main.json): legacy-link marks 0, origin backfill 0, superseded requirements closed 0, source paths rewritten 0, source paths removed 0; .gitignore updated.` ## `kibi find-gaps [type]` (`gaps` alias) Runs curated missing/present relationship analysis. **Syntax:** ```bash kibi find-gaps [type] [--missing-rel RELS] [--present-rel RELS] [--tag TAGS] [--source PATH] [--limit N] [--offset N] [--format json|table] ``` **Examples:** ```bash # Requirements missing scenarios or tests kibi find-gaps req --missing-rel specified_by,verified_by --format table # Source-linked gap analysis kibi gaps req --source src/auth --missing-rel verified_by --format table ``` `--missing-rel` and `--present-rel` count a relationship in either direction and treat `verified_by` and its documented inverse `validates` as satisfying each other, so a requirement whose test `validates` it is not reported missing `verified_by`; `relationshipCounts` keeps one count per relationship name. `find-gaps` is the canonical command name and dedicated JSON route. `gaps` is a true Commander alias for the same action, so flag and `--input` behavior are identical under either spelling. The JSON payload carries `rows` (the current page), `count` (matching rows before pagination), `summary` (`total`, the same number, and `provenanceStubs`, the bootstrap facts tagged `bootstrap:provenance-stub` that match the filters but are counted apart from knowledge; they enter `rows` only when `--tag` names that tag) and `meta`. ## `kibi coverage` Generates curated coverage reports. **Syntax:** ```bash kibi coverage [--by req|symbol|type] [--tag TAGS] [--include-passing] [--status STATUSES] [--no-include-transitive] [--limit N] [--offset N] [--include-migration-preview] [--migration-limit N] [--migration-offset N] [--migration-predicate-limit N] [--migration-predicate-min-score 0..1] [--format json|table] ``` **Notes:** - Requirement coverage summaries distinguish evaluated must-priority requirements from `not_applicable` rows. The link counts (`evaluated`, `fullyCovered`, `notApplicable` and the `missing*` gaps) judge only `priority: must` requirements, and the summary says so with `linkCoverageScope: "priority_must"`; the table titles that group `Links (priority: must)`. A KB without must-priority requirements reads `evaluated: 0` there while `evidenceLevels` and `proofTested` still count every requirement. - `--include-passing` adds rows with a tested or not-applicable proof outcome back into requirement results; compatibility-oriented structural coverage remains visible on every returned row. - `--status ` (comma-separated: `tested`, `missing`, `unresolved`, `not_applicable`) selects requirement rows by `proofStatus` and implies include-passing. Use it to enumerate one slice — e.g. `kibi coverage --by req --status not_applicable` lists every out-of-scope requirement with its typed applicability reason (`proofStages.applicability.reason`: superseded, a status-vocabulary mismatch, or a proof exemption). The summary always reflects the whole KB; pagination applies to the filtered rows. - Requirement coverage rows include coverage-depth labels when evidence can be classified: `direct_passing_e2e`, `scenario_passing_e2e`, `unit_only`, `open_or_nonpassing_tests_only`, `scenario_only_no_test`, or `no_test_evidence`. - Coverage-depth labels are informational. They do not change existing covered/uncovered pass-fail semantics, and typed test fields (`verification_scope`, then `verification_perspective`) take precedence over legacy `e2e` tags or `/e2e/` path heuristics. - Requirement rows also expose the additive `kibi.requirement-proof.v5` contract. `proofStatus` is `tested` (named `proven` before v4), `unresolved`, `missing`, or `not_applicable` for a non-current requirement, and is intentionally independent from compatibility-oriented `coverageStatus`. Each row also carries `evidenceLevel` (`proved`, `tested`, `asserted` or `unverified`) and the `evidence[]` entries that earned it, and the summary counts rows per level under `evidenceLevels`; `proofTested` (named `proofProven` before v4) counts tested rows. From v5 each row also carries `claimEvidence[]`, `claimSummary` and `unprovedClaims` (a requirement is proved only when a certificate binding derives every applicable claim), the summary totals them under `proofClaims`, and the table's Evidence column shows `n/m claims proved`. The summary also counts current requirements with an evidence floor under `evidenceFloors` (`met`, `below`, `pendingReproof`; a floor of `unverified` is not counted), and the table's Floor column shows each row's floor and status (for example `tested pending reproof`). See `docs/proof-ladder.md` for the per-stage semantics and the evidence levels. - `proofStages` records semantic inventory, logical grounding, contradiction, scenario, scenario-test, passing E2E, executable-symbol, production-symbol, and exact source-coordinate evidence. `proofGaps` lists only blocking issues that prevent `tested`. The passing-E2E stage exposes per-scenario `scenarioObligations`; every linked E2E proof-bearing test is mandatory, while unit/integration-only ancillary tests remain nonblocking when the scenario has qualifying E2E evidence. `proofAdvisories` is reserved for explicitly non-blocking context; missing, stale, failed, invalid, snapshot-unavailable, and contract-mismatched E2E evidence remains in `proofGaps`. `proofRepairs` ranks concrete recovery actions for blocking gaps only. - Requirement reports also include `repairPlan` (`kibi.repair-plan.v1`). It groups gaps into one small batch per requirement and dependency phase, marks only the earliest unresolved batch `ready`, and links later batches through `dependsOn`. Every batch is read-only guidance with `autoApplicable: false`, a reviewed `workflowSteps` sequence, targeted `validationRules`, and a sequential-write policy. - Requirement and symbol reports also include the shared `migrationPlan` (`kibi.migration-plan.v2`). Apply only ready automatic actions after explicitly approving its exact hash and action IDs; review, operator, and E2E execution actions remain agent/operator work. - `repairPlan.scope.complete` is false and `status` is `partial` whenever `limit`/`offset` exclude actionable requirements. Increase the limit and reset the offset before using a plan as a project-wide migration inventory. The plan ID is stable for the same snapshot, filters, evidence, and gaps; receipt ages and check timestamps do not churn it. - `--include-migration-preview` adds `kibi.legacy-migration-plan.v1` for ready semantic-inventory batches. It defaults to one requirement, reconstructs normalized authored Markdown with exact SHA-256 source identity and UTF-8 proposition spans, ranks project-local schemas before built-ins, and emits review-only property patches. The patch stores authored prose in requirement-only `semantic_text` and never replaces an independent `text_ref`; only an existing `semantic_text` that differs from the current normalized Markdown blocks the batch as source drift. All candidates remain `writeEligible: false` and all batches `autoApplicable: false`. - The passing-E2E stage requires append-only proof-receipt history for every linked scenario-backed E2E test. New evidence is produced by `kibi prove` as `kibi.proof-receipt.v1`. Only a fresh passed receipt bound to the live `proofSnapshot`, current contract hash, and effective execution fingerprint qualifies; authored `status: passing` remains structural metadata. - Symbol rows classify `traceabilityRole` as `production`, `executable_test`, or `mixed`. Executable-only test symbols are `not_applicable` to production coverage instead of being counted as fully covered. A production symbol whose `sourceFile` no longer exists in the workspace is `uncovered` with the `source_missing` gap, even when its links are complete, until the symbol is repaired, moved, or deleted. ## `kibi report` Generates a polished, self-contained HTML view of requirement health and a matching SVG badge. This is a human-facing presentation command over the existing `kb_coverage` operation, not an additional JSON/MCP operation. **Syntax:** ```bash kibi report [--output PATH] [--open] [--tag TAGS] [--limit N] [--certificates FILE] ``` **Options:** - `--output ` writes to an HTML file or to `index.html` inside a directory. Directory output also writes `badge.svg`; explicit file output writes `.badge.svg` beside the HTML. The default is `kibi-report/index.html` plus `kibi-report/badge.svg`. - `--open` opens the report with the operating system's default browser after the file is written successfully. - `--tag ` limits requirement and symbol health to comma-separated tags. - `--limit ` sets the maximum complete requirement row set. It defaults to 10,000 and fails instead of publishing partial per-requirement metrics. - `--certificates ` publishes a `kibi.certificates.v1` bundle written by `kibi check --write-certificates` next to the report (`kb-certificates.json`, or `.kb-certificates.json` beside an explicit HTML file) and links it with its certificate count per kind. The report does not re-check the bundle; `kibi check --certificates` does. **Report contents:** - The tested percentage and count use current requirements only; superseded and otherwise non-current requirements are reported as excluded rather than lowering the score. - Summary metrics show current requirements, requirements tested end to end, requirements proved by certificate, asserted or unverified (by evidence level), requirements below their evidence floor or pending re-proof, missing scenarios, stale E2E evidence, unique contradiction witnesses, unmapped production symbols, and requirements without implementation. - Requirement cards separate semantic grounding, scenario, implementation, E2E-test, and fresh-receipt stages, plus a certificate stage when a test carries a certificate (its proof kinds and claims proved). Each card shows the evidence level, the evidence floor and whether it is met, below or pending re-proof (`*` marks a floor set by `required_evidence` rather than the firm default), a `Proved` badge for proved requirements, and any certificate or claim-binding rejections. Cards below their floor sort right after contradictions. Search, health filters (proved, tested, needs attention, below floor, pending re-proof, stale, contradictions), and proof-gate filters run entirely in the generated file. Filter buttons include counts. Relative evidence and generation ages are computed in the viewer from preserved absolute timestamps. - Stale KB state and dirty workspace proof evaluation are shown as a prominent snapshot warning. - Stale KB state and dirty workspace proof evaluation are shown as a prominent snapshot warning. - All KB-provided values are HTML-escaped. The report has no CDN, font, script, or other network dependency, so the output directory can be hosted as-is. - The generated SVG badge uses the same complete coverage snapshot as the report. It pairs the Kibi logo with a `kibi` label in Codecov/Shields chrome (regular 11px type, `#555` label pane, reserved padding, and white status text), sizes itself to the tested-percentage message (`87% tested`), and uses conservative colors: red for a contradiction or a requirement below its evidence floor, amber for a stale snapshot. **Examples:** ```bash # Generate kibi-report/index.html and open it kibi report --open # Write the single-file site to a CI staging directory kibi report --output public/requirement-health # Publish a focused report kibi report --tag billing,security --output artifacts/kibi.html ``` For GitHub Pages, follow the copyable workflow in [docs/examples/github/kibi-report.yml](examples/github/kibi-report.yml) or run `kibi init --github`. That command scaffolds the same documented integration. Pull requests generate and validate `kibi report`, then upload `kibi-pr-report`; only the default branch publishes the canonical Pages site. Enable **Settings → Pages → Source → GitHub Actions**. Details, package-manager adaptations, owner-site URLs, and the badge-only opt-out are in [GitHub badge + report](github-integration.md). Wrap the published badge image in a link to the report so clicking it opens the dashboard: ```markdown [![Kibi requirement health](https://OWNER.github.io/REPOSITORY/kibi-report/badge.svg)](https://OWNER.github.io/REPOSITORY/kibi-report/) ``` To publish requirement health in a documentation site you already have (Hugo, Docusaurus, MkDocs, ...), generate both views in the site build: the JSON for your own templates and the self-contained report as a static page. ```bash kibi sync kibi coverage --by req --include-passing --format json > site/data/requirements.json kibi report --output site/static/requirements ``` Run `kibi sync` first, with `KIBI_BRANCH` set in CI. Every requirement row in the JSON carries its `proofStatus`, `evidenceLevel` and coverage stages, so a page template can list them; the report directory can be linked as-is. Actions artifacts expire and do not provide a stable anonymous URL, so the badge and its target should use the GitHub Pages deployment rather than the ordinary downloadable artifact. The Pages URL must be anonymously reachable for the badge to render in a public README; use an appropriate authenticated static host when the report must remain private. ## `kibi signoff` Shows the person what they are signing off on, in one readable view. Agents run it before asking for signoff at the end of a change, and with `--questions` whenever decisions about rules wait for the person. It is a CLI command, not an MCP operation; the `kibi-decisions` and `kibi-commit-review` skills say when to run it. It reports and never blocks. **Syntax:** ```bash kibi signoff [--staged] [--format chat|md|html|json] [--output PATH] [--open] [--no-proof] kibi signoff --questions [--format chat|md|html|json] [--output PATH] [--open] ``` **Summary view (default):** lists each requirement the change adds, rewrites or retires (from the Git diff of `.kb/requirements/` against `HEAD`, with untracked files; `--staged` uses the index), and each current requirement the changed code implements whose document did not change. Each entry quotes the statement (the previous one too for a rewrite) with its firmness, origin, replaced requirements, scenarios and proof state. The proof state names the evidence level, the evidence floor and whether it is met (a floor lowered with `required_evidence` says so, since approving the requirement accepts it), and any certificate that no longer re-checks. Each firm-edit receipt the change adds or rewrites (see `kibi review-firm-edit`) is listed under its requirement as the agent's verdict, labelled "judged by the agent, not approved by you". The view names the project's Kibi level under its heading (`Kibi level: test (the default)`), and a "Decisions only you make" section lists a change of the level against `HEAD` and each changed requirement whose evidence floor is now lower; the JSON view carries them as `level` and `decisions`. `--no-proof` skips the proof lookup, which runs a full coverage pass and can take tens of seconds on a large knowledge base. **Questions view (`--questions`):** reads JSON from a file or stdin (`-`): `{"questions":[{"id"?, "title"?, "statement", "quote"?, "firmness"?, "governs"?, "conflictsWith"?, "question"?, "answer"?}]}` or a bare array. Each decision is numbered, and the view quotes the recorded requirement it changes (`id`) or conflicts with (`conflictsWith`) next to the proposed statement and the person's own words. Decisions with an `answer` are shown as answered, so the agent can re-render the view as the person replies. **Output:** - `chat` (default) prints the view as plain Markdown (headings, quoted statements, lists) for the agent to put in its reply, or in a messaging tool's message when replies go through one. Any Markdown surface renders it. The path of the HTML page goes to stderr, so stdout stays pasteable. Long summaries stop after 15 entries and point to the HTML page. - `md` prints the same Markdown inside a fenced `kibi-signoff` or `kibi-questions` block, for hosts whose plugin draws that block (the OpenCode terminal). Elsewhere a fence shows as raw code. - `html` writes a self-contained page (no network, strict content security policy) and prints its path; `--output` chooses the file and `--open` opens it in the default browser. - `json` prints the `kibi.signoff.v1` view. `KIBI_SIGNOFF_FORMAT` (`chat`, `md`, `html` or `json`) sets the default format for a host. Every run also writes `.kb/briefs/signoff/latest.json`, `latest.md` and `latest.html`, which `kibi init` already ignores in Git. `latest.html` is a self-contained page, so an agent whose host can carry a file or publish a page can attach it next to the Markdown. The host integrations build on these files: | Host | What it offers | | --- | --- | | Claude Code | `/kibi-signoff`; a fenced block still renders as Markdown through the `MessageDisplay` hook | | Cursor, ZCode | `/kibi-signoff` | | OpenCode | The fenced block (`--format md`) drawn as a framed card, `/kibi-signoff`, and a toast for each new view | | VS Code (and Cursor with the extension) | The **Kibi: Show Requirements Signoff** panel | | Claude Code, Codex, Cursor, ZCode hooks; OpenCode v1 plugin | After a session writes a requirement, the stop hook (OpenCode: when the session goes idle) asks once for `kibi signoff` unless it already ran since | **Examples:** ```bash # Summary of the working tree for the end-of-work signoff kibi signoff # The fenced block for the OpenCode terminal card kibi signoff --format md # Staged change, as a page in the browser kibi signoff --staged --format html --open # Decisions waiting for the person printf '%s' '{"questions":[{"id":"REQ-042","statement":"Exports stay in CSV.","quote":"keep CSV for now","firmness":"firm"}]}' \ | kibi signoff --questions - ``` ## `kibi review-firm-edit` Records the agent's verdict on its change to code that implements a current firm requirement, a rule a person set. `kibi check --staged` blocks such a change (`firm_edit_unreviewed`) until every edited symbol has a current `keeps` receipt. MCP lists it as `kb_review_firm_edit` in every tool profile. The blocking finding prints the exact input to send, with the requirement, file and symbol filled and the note left empty. **Syntax:** ```bash kibi review-firm-edit --input ``` **Input:** `{"reviews":[{"requirementId", "sourceFile", "symbol", "verdict": "keeps"|"changes", "note", "requestQuote"?}], "dryRun"?, "staged"?}`. `symbol` is the name `kibi check` gives (`expireKey`, `KeyStore.rotate`, or a coarse `.kb/symbols.yaml` title such as `boot module`, bound to its source coordinates) and must carry an `implements` link to the requirement; a symbol the change removed is reviewed through its record at HEAD. With `"staged": true` the code and the requirement are read from the Git index, as `kibi check --staged` reads them, so a file with further unstaged edits can still be reviewed; `note` says in one line why the change keeps or changes the rule. The requirement must be current and firm. Every entry is validated before any receipt is written, and a refusal (`VALIDATION_FAILED`, rule `firm_edit_review_invalid`) writes nothing. **Receipts:** each entry writes `.kb/firm-edit-reviews//--.json` (the hash covers the source file and symbol), replacing an earlier receipt for the same requirement and symbol, including one an earlier release wrote as `--.json`. A receipt holds the verdict, the note, a hash of the requirement's statement and a hash of the symbol's code as they are when it is recorded. It stops matching when the statement changes, when the requirement is superseded or retired, or when the symbol's code changes, so record it after the edit and again after a later edit. Stage it with the change: `kibi check --staged` reads receipts from the index. - `keeps` clears `firm_edit_unreviewed` for that symbol. - `changes` turns the finding into `firm_edit_breaks_rule`, which stays blocking until the requirement is superseded with the person's words in `origin.ref` (a superseded requirement is no longer current, so its code is no longer gated). A receipt is the agent's judgment, never the person's approval; `kibi signoff` shows it as such. Hooks read receipts too: the Claude Code PreToolUse hook lets the retry of an edit it asked about through when a `keeps` receipt recorded after the question covers every edited symbol (a receipt from an earlier session never skips the question), and the Codex, Cursor, ZCode and OpenCode notices name this command (OpenCode v1 stops the first attempt of such an edit once and lets the same edit through when it is tried again). `KIBI_CONFIRM_FIRM_EDITS=0` turns off only the hook question, never the staged gate. **Example:** ```bash echo '{"reviews":[{"requirementId":"REQ-key-expiry","sourceFile":"src/keys.ts","symbol":"expireKey","verdict":"keeps","note":"Same ninety days, constant written another way."}]}' \ | kibi review-firm-edit --input - git add .kb/firm-edit-reviews ``` ## `kibi graph` Runs bounded graph traversal from one or more seed IDs. **Syntax:** ```bash kibi graph --from IDS [--relationships RELS] [--direction outgoing|incoming|both] [--depth N] [--entity-types TYPES] [--max-nodes N] [--max-edges N] [--format json|table] ``` **Examples:** ```bash # Follow requirement links outward kibi graph --from REQ-cli-gc --direction outgoing --depth 2 --format table # Inspect both incoming and outgoing relationships kibi graph --from REQ-mcp-search-discovery,TEST-mcp-search-discovery --direction both --depth 2 --format json ``` ## `kibi check` Validates knowledge base integrity and runs inference rules. **Behavior:** - Runs the canonical and advisory rules of the knowledge layer at every [Kibi level](#kibi-level), and those of the verification layer (`evidence-floor`, `symbol-coverage`, `must-priority-coverage`, `must-positive-scenario`, `proof-contract-claims`, `proof-contract-symbols`) only at level `test`. Each rule's layer is in `packages/core/schema/rule-registry.json`. `--rules` runs the rules it names at any level. - Validates required fields are present - Checks requirement coverage (must-priority rules) - Detects dangling references (entities that reference non-existent IDs) - Detects cycles in dependency graphs - Enforces `strict-fact-shape` as a canonical blocking check and supports advisory modeling checks (`strict-req-fact-pairing`, `predicate-verifiability`, `proof-contract-symbols`) that run by default as non-blocking `qualityDiagnostics` (a requirement constraining a subject fact is paired by a `requires_property` fact on that `subject_key` or a `requires_predicate` fact about it: the predicate fact's own `subject_key`, else the argument its project-local schema names `subject`, else its first argument), and default-off migration diagnostics (`strict-readiness`, `semantic-completeness`) that run only when explicitly selected with `--rules`. Canonical rules always populate blocking `violations[]`. `--rules` is an invocation-time diagnostic filter only; leftover `.kb/config.json` cannot disable canonical checks. `proof-contract-symbols` reports unresolved `required_proofs.symbol_id` values, type-shape required proofs, and `proof_bindings.source_file` disagreement with the named symbol `sourceFile`. Kibi does not infer TEST names from filenames. - Runs the canonical `scenario-feasibility` check (a success scenario whose assumed values cannot hold, alone or together, with the property facts and typed rules of current requirements that govern it, by scope and validity window) and two advisory analysis-gap checks by default: `scenario-feasibility-unknown` (a success scenario whose feasibility cannot be decided: no assumptions, contradictory assumptions, an unconstrained or incomparable assumption, conflicting governing requirements, a rule the assumptions neither satisfy nor refute, or a conflict only with constraints whose validity window may not cover the scenario) and `rule-key-arguments-missing` (an opposing rule pair left `unresolved` only because a condition predicate declares no `key_arguments`; the finding names the predicate as `namespace:name/arity` and the key positions that would decide the pair). Both advisory checks report non-blocking `qualityDiagnostics`. - Runs the canonical `scenario-outcome-mismatch` check: a scenario that expects `rejection` or `error` while current requirements govern every value it assumes and permit them together exercises no failure side, so the knowledge base predicts success for it. - Runs the canonical `exception-claim-keys` check (an exception requirement's `exempts_claims` must name claims of a requirement it `exempts`) and the advisory `numeric-string-value` check (a `property_value` fact stores a plain decimal as `value_type: string` where the comparison is numeric, so contradiction and feasibility checks skip it; the suggestion gives the typed `value_int`/`value_number` replacement). - Runs two canonical lifecycle checks: `superseded-requirement-open` (a requirement that another requirement `supersedes` must have `status: closed`; requirements that supersede each other, directly or through a chain, are reported once per cycle with every member and edge, and their members are not reported again as open; `no-cycles` follows only `depends_on`) and `source-path-dangling` (an authored `source` frontmatter field must name an existing workspace path, with any `#anchor` ignored, an existing entity id, or an http(s) URL; a missing `source` is fine). The authored field is dead data: the compiled `source` is always the entity's own file, and Kibi never writes the field, so `kb_upsert` cannot change it. Each `source-path-dangling` finding therefore names the automatic fix in its evidence: `rewrite` when the value names a knowledge file by its pre-canonical path (`documentation//...` or `/...` relative to the knowledge root) and that file exists under `.kb//` and is not the entity's own file, otherwise `remove` (`self` when the value names the entity's own file, `dangling` when it names nothing Kibi can map). The same rule covers `text_ref` when its value is shaped like one workspace file path (a directory, a file name with an extension, no spaces; a `#anchor` is ignored) and that file does not exist; prose, entity ids, URLs and lists in `text_ref` are never judged. `text_ref` is evidence, so Kibi never removes it: a pre-canonical knowledge path whose file exists under `.kb/` gets `evidence.rewrite` (with `evidence.field: text_ref`), and anything else gets `evidence.refused` and a review action for a person. A `text_ref` that is a requirement's semantic source (declared `semantic_source_field: text_ref`, or a requirement without `semantic_text`) is never rewritten automatically, since that changes the inventory hash. Both checks block, and `kibi migrate` repairs them (see below). - Runs the canonical `entity-context-missing` check on authored sources: a current `req`, `scenario`, `test`, `adr` or observation/meta `fact` needs at least 12 words of body context that do not restate its title (requirements: only text under `Context`, `Rationale`, `Why`, `Background`, `Source`, `Notes` or `Evidence` headings). Entities the schema 8 migration acknowledged (tagged `review:context-missing` and recorded in `.kb/manifest.json` as `contextAcknowledged`) are counted by the info diagnostic `entity-context-acknowledged`; the tag on any other entity is still a violation. - Runs four canonical decision-firmness checks on authored requirements and ADRs (KB schema 9): `decision-firm-unreferenced` (a current decision marked `firmness: firm` must name the human words it rests on in `origin.ref`, or `approval_ref` on a requirement), `decision-firm-superseded` (a decision that supersedes a firm one, retired or not, must itself be firm; from KB schema 10 a decision without `firmness` is firm unless an agent wrote it, and the supersedes of such decisions recorded before schema 10 are acknowledged in `firmSupersedeAcknowledged`), `decision-firm-edited` (a decision that was firm at `HEAD` must not have its title, stated meaning, recorded reason, `## Source` section, an ADR's body or its firmness changed, or be retired or reopened, in the working tree unless the edit cites new human words in `origin.ref` or `approval_ref`; `kb_upsert` refuses such a write up front) and `supersedes-reason-missing` (a current decision that supersedes another needs a `## Why this changed` section of at least 12 words naming the evidence). Supersede edges the schema 9 migration acknowledged (`supersedesReasonAcknowledged` in `.kb/manifest.json`) are counted by the info diagnostic `supersedes-reason-acknowledged` instead. See [Decision firmness](entity-schema.md#decision-firmness). - Runs the canonical `kb-consistency` check: the facts current requirements name must hold together, jointly and not only pairwise. Each run produces a `kibi.certificates.v1` bundle (a model or an irreducible contradiction core per property context, a truth value per predicate atom, a decision per decision key, a stratum assignment or a negation cycle for the stored rules) and re-checks it with the independent checker. A re-verified contradiction is a blocking violation that names the core facts, the requirements behind them and one model per dropped fact, with the certificate under `evidence.certificate`; a certificate the checker rejects also blocks. The advisory `kb-consistency-unresolved` check reports each context the checker cannot compare (mixed value types or units, an unsupported operator or polarity, a contradiction whose validity windows never overlap) as a non-blocking diagnostic; it never counts as consistent. See [Knowledge-base certificates](./proof-ladder.md#knowledge-base-certificates). - Runs the canonical `evidence-floor` check (KB schema 11): every current requirement's evidence level (`proved`, `tested`, `asserted`, `unverified`) must reach its floor, which is `required_evidence` when set, otherwise `tested` for a firm requirement or (from KB schema 15) one a person approved (`origin.approved_by`) that states no `firmness`, and no floor for any other. A requirement whose receipts are only older than the code counts as pending re-proof and passes unless `--fresh-evidence` is given. Each finding names the level, the floor and where the floor came from, and its suggestion says what would raise the level. See [Evidence floors](./proof-ladder.md#evidence-floors). - Runs the canonical `agent-requirement-unapproved-implemented` check (KB schema 15): a current `priority: must` requirement with `origin.kind: agent` that production symbols implement must have `origin.approved_by` once it is more than 14 days old by `origin.recorded_at`, else by a `created_at` its front matter states (a requirement with neither counts as older, as does one whose date is not ISO 8601 or lies more than a day in the future; the `created_at` sync fills in is not read). `kibi upsert` refuses such a `created_at` or `origin.recorded_at` on a requirement. See [Evidence floors](./proof-ladder.md#evidence-floors). - Runs five canonical domain-subject checks (KB schema 16): `claim-subject-missing` (a current requirement's unmodeled claim, an inventory entry with status `ambiguous`, `ontology_gap` or `missing`, whose role is `normative`, `condition`, `exception` or `definition`, must name the subjects it is about under the entry's `subjects`), `claim-subject-undefined` (every subject key a claim names, and every `part_of`, `kind_of` or `distinct_from` key of an active subject fact, must be defined by an active `fact_kind: subject` fact), `subject-definition-missing` (a subject fact's body is its definition: at least 8 words, each Chinese or Japanese character counting as a word, that do not restate the title or `subject_key` and add at least 3 words of their own beyond them and function words; a definition that 3 or more subjects repeat with only the key or title changed is a template, not a definition; a body that opens with `Definition not stated:` and says where the subject is named records the gap instead, and so does the older bootstrap body `Subject , shared by the requirements bootstrap planned from ...`), `subject-duplicate` (two facts with the same `subject_key`, keys with the same words up to simple plurals such as `report.export` and `report.exports`, or keys and titles whose words mostly coincide, token Jaccard at least 0.7; an ancestor and its descendant such as `report_export` and `report.export.pdf`, siblings under different parents such as `web.drawing.view` and `mobile.drawing.view`, and a pair either fact relates through `distinct_from`, `part_of` or `kind_of` are exempt) and `subject-hierarchy-invalid` (no subject lists its own key under `part_of`, `kind_of` or `distinct_from`, and following `part_of`, `kind_of` and the nearest defined dotted prefix upward never comes back to where it started). A KB whose `.kb/manifest.json` records an older schema skips them until `kibi migrate` upgrades it. See [Subject facts](entity-schema.md#subject-facts). - Runs the canonical `must-positive-scenario` check (KB schema 17): a current must requirement needs an active scenario with `expects: success` that it links through `specified_by` and that `assumes` a `property_value`, predicate or rule fact (the subject fact itself does not count) on one of its subjects or a narrower one, so `scenario-feasibility` can refuse the behaviour it promises when another current requirement forbids it. Must requirements that `kibi migrate` recorded under `positiveScenarioAcknowledged` in `.kb/manifest.json` during the schema 17 upgrade are exempt. A requirement that names a subject no active subject fact defines is told to define the subject first. - Runs the canonical `related-requirement-unmodeled` check (KB schema 18): a current requirement with an unmodeled rule claim (an inventory entry with status `missing`, or `ontology_gap` or `ambiguous` on a `normative`, `condition`, `exception` or `definition` claim) is a blocking violation against the current requirements it pairs with, through a `relates_to` edge in either direction or a subject both are about (an `ontology_gap` claim counts for the subjects its entry names, or narrower ones). `domain-contradictions` compares grounded facts only, so the pair stays blocked until the claims are modeled, one requirement supersedes the other, or a `pair_reviews` entry on either requirement settles it: `with` the other id, `verdict` `no_conflict` with `separated_by` or `interacts` with `resolved_by` (an active scenario either requirement is `specified_by`, an active fact either links through `constrains` or `requires_*`, a third current requirement, or a `condition` or `exception` claim key of either; never the two requirements themselves), and `claims` naming every unmodeled claim by `claim_key` (a `payload_hash` is accepted and ignored). A verdict counts only while a `relates_to` edge links the pair; a `conflict` verdict never settles it; and on a pair with a must or firm requirement, a verdict whose `origin` is missing or not `kind: human`, or that sits on a requirement an agent wrote, counts only with `origin.approved_by`. There is one finding per requirement and problem: it names the claims, the requirements it pairs with and how (the first 8, then how many more), and what the verdicts lack; it also names a `with` that is no current requirement, and `missing` claims whose role states no rule, to model, set to `ontology_gap` with a reason when no predicate can state them, or review (`nonlogical` is accepted only for `rationale`, `example` and `subjective` claims); an `interacts` verdict whose `resolved_by` names one of the pair or something that resolves nothing is told which entry was rejected and why. On a KB below schema 18 the earlier form of the rule runs, and `claim-subject-missing` and `claim-subject-undefined` apply from schema 16. - Runs the canonical `quantity-duplicate` check (KB schema 19): two active `property_value` facts, each grounded by a current requirement through `requires_property`, must not state one quantity under different `subject_key.property_key`. A pair is one quantity when the values are equal and comparable (numbers other than 0 and 1 after unit canonicalization, or sets of at least two members; booleans and strings are never compared), the requirements are implemented by symbols in one source file, and one signal holds: a shared implementing symbol, a proof `value_source` that implements the other requirement, or property keys or claim texts sharing at least half the words of the shorter. A pair grounded by one requirement, or where either fact lists the other's key under `distinct_from`, is exempt, and a `distinct_from` entry naming no active value fact is reported. The finding names both facts, keys, values, requirements and the shared file; ground both claims on one key, or add `distinct_from` with the difference in the fact's body. `kb_upsert` warns on a value fact write that states a twin's quantity, on a dry run or write that moves a value away from a twin still stating the old one, and on a requirement write whose `requires_property` grounds such a fact. A requirement write that adds a `requires_property` link also gets a `quantity-duplicate (note):` line for a value fact in the same file whose key or claim words match although the values differ; the note never blocks. A KB below schema 19 skips the rule until `kibi migrate` upgrades it. See [One quantity under two keys](inference-rules.md#one-quantity-under-two-keys). - Runs two canonical retirement checks (KB schema 14): `retired-reason-missing` (a requirement with `status: retired` must state a non-blank `retired_reason`) and `retired-owner-only` (a current fact, scenario or test whose every owning requirement is retired: the requirements grounding a fact, specifying a scenario, or verifying a test directly or through a scenario; a fact or scenario with `status: deprecated` is archived and not reported). See [Retired requirements](entity-schema.md#retired-requirements). - Runs four advisory lifecycle checks by default: `symbol-owner-superseded` (a symbol whose every `implements` target is superseded, deprecated or retired, so no current requirement owns it; a `closed` requirement is done, not retired; up to 25 symbols per check, then one summary finding), `adr-unlinked` (an accepted ADR that no requirement or other ADR links with, in either direction; a symbol's `constrained_by` link does not count), `adr-proposed` (info: an ADR still `proposed` and not superseded) and `requirement-rationale-missing` (a current requirement whose `origin.kind` is `human` or `agent` has no `rationale` field, no `## Rationale`, `## Why` or `## Context` section in its body, and no link to an ADR; up to 25 per check, then one summary finding). Imported and migrated requirements are not asked for a rationale. - Runs three advisory approval checks by default, all non-blocking: `exception-unapproved` (a current exception requirement `exempts` another requirement but has no `approved_by`, so it exempts nothing), `exception-approval-self-attested` (an exception whose `origin.kind` is `agent` records `approved_by`, but `origin.approved_by` or `approval_ref` is missing, so nothing corroborates that a person approved it) and `agent-requirement-unapproved` (info: current requirements with `origin.kind: agent` and no `origin.approved_by`, listed by id up to 25 per check, then one summary finding with the remaining ids). Kibi cannot verify that a person approved anything; these checks make agent-recorded approvals visible so a human can confirm them. - Runs two canonical check-policy rules, inert unless a package is activated for `kibi.check-policy.v1` (such as the experimental `kibi-plugin-ui`): `policy-ownership` (a production symbol in the policy's file set must implement a current requirement grounded in one of its predicates, unless tagged with the policy's exempt tag) and `policy-markers` (a file implementing a requirement that names a pattern must contain every marker the KB declares for it, in the file or its declared sibling templates). Kibi reads the policy as JSON from the package and never imports plugin code; a policy that cannot be read blocks. See [plugin-development.md](./plugin-development.md#check-policy). - Runs vocabulary-convergence checks by default, all advisory and non-blocking (see [Vocabulary convergence checks](#vocabulary-convergence-checks)): `domain-redundancy`, `subject-key-identity`, `subject-key-shape`, `entity-id-style`, `predicate-schema-conformance` (warnings) and `domain-implication`, `ontology-quality` (info). - Runs the canonical, blocking symbol-to-source check `symbol-granularity`, which reads each judged symbol's working-tree `sourceFile` with the same source analyzers as `kibi check --staged`: a symbol with `implements`, `covered_by` or `executable_for` links and no allowed `granularity_reason` violates it when it covers its file coarsely while narrower behavioral declarations exist, including when its `title` names no declaration the extractor produces (a private class member, or a removed, renamed or non-exported declaration). It is the staged gate's `symbol_granularity_violation`, evaluated for every symbol with every declaration of the file as a candidate. A file the analyzers cannot fully analyze is skipped. Only the source files of judged symbols are parsed, once per check and for syntax only, so the rule adds a few seconds to a full check. - Runs the advisory `symbol-coordinates-missing` check (warning, non-blocking): an active symbol whose `sourceFile` exists but which has no coordinates, because Kibi could not place it there (no declaration with its title, a file the analyzer cannot read, a missing plugin or grammar pack), is linked to no code. `kb_upsert` of such a symbol warns too. - With `--changed [paths...]`, runs the `--staged` gate over what a commit of every current change would hold: the index plus the working tree's staged, unstaged, untracked and deleted files (ignored files stay out). It copies the index to a scratch file in the git directory, adds the working tree to the copy and judges the copy, so the real index is never written and the scratch file is removed afterwards. With paths, only those paths and `.kb` are added on top of the index; a relative path is read from the directory the command runs in, also in a subdirectory of the workspace, and a path that is neither in the working tree nor tracked by git is refused rather than skipped, since skipping it would judge nothing and pass. Exit codes and output are those of `--staged`. It cannot be combined with `--certificates` or `--write-certificates`. `kb_check` with `changed: true` (and optional `sourceFiles`) runs it in a child process and returns `commitAllowed` with the findings. - Every finding in `--format json` and `kb_check` output carries `blocks`: `"commit"` when the commit gate refuses a commit over it, `"merge"` when the full check fails over it (so CI refuses the merge), and `"none"` when it is advice. The full check tags `violations` and `violationGroups` `merge`, blocking `qualityDiagnostics` `merge`, blocking `impactDiagnostics` `commit` and the rest `none`; `--staged` and `--changed` tag every violation `commit` and other blocking findings `commit`. - With `--staged`, the temporary store the gate builds is never saved to disk while it is filled, and the evidence floor is evaluated only for the requirements the commit touches. A one-function change on a test project with 8,457 entities went from 7m17s to 48s with the same verdict. - With `--staged`, inventories every index path before analysis. TypeScript and JavaScript keep their blocking symbol checks; Kibi metadata is validated through its typed lanes; every other readable UTF-8 text file receives advisory file-level ownership and impact-evidence checks. - With `--staged`, runs the full-check `symbol-coverage` rule on the staged knowledge for every changed symbol: each changed source symbol and each symbol whose staged `.kb/symbols.yaml` entry changed. It is the same Prolog rule, so a direct `verified_by(Req,Test)` or `validates(Test,Req)` does not count once the requirement has a scenario, and the requirement/scenario/test graph is read from the index, not the working tree. A clean `kibi check` therefore does not leave a coverage gap for the next commit to trip over, and the staged gate does not pass coverage the full check rejects. - With `--staged`, a staged entity document or relationship shard under `.kb/` also runs the `domain-contradictions`, `scenario-feasibility`, `exception-claim-keys` and `kb-consistency` rules on the staged tree and blocks on each violation the last commit's tree does not already have. Violations already committed are left to the full check, so they do not block unrelated commits. - With `--staged`, each staged entity document (requirement, scenario, test, ADR, observation or meta fact) is checked with `entity-context-missing`, reading only the file. A finding blocks when the entity did not already have it at the last commit's tree; entities listed under `contextAcknowledged` in the staged `.kb/manifest.json` are exempt, so a migration commit passes. - Staged deletions and renames retain committed content and ownership for removal review. Binary blobs, unsupported encodings, symlinks, and submodules are reported with explicit skipped reasons and remain non-blocking. - Reports blocking `violations[]` with actionable suggestions and additive `qualityDiagnostics[]` audit signals for modeling quality, coverage depth, broad requirements, duplicate coordinates, symbol fanout, and strict-fact review - When `.kb/usage.log` exists, an unfiltered check also turns failed or insufficient `kibi.telemetry-acceptance.v1` metrics into ranked, non-blocking `category: telemetry` quality diagnostics; a missing log is skipped because diagnostic logging is opt-in - When `.kb/manifest.json` records an older schema than this Kibi writes, the text output starts with `Note: KB schemaVersion is older than the latest version ; run 'kibi migrate' to plan the upgrade.`: rules a later schema adds are not checked until the upgrade runs, so a clean result does not cover them yet. `--format json` carries the same upgrade as the `schema-config-upgrade` action of `migrationPlan` - Keeps advisory quality diagnostics non-blocking by default: `review`, `info`, and non-blocking `warning` diagnostics do not change the exit code; hard violations, `severity: "error"`, or `blocking: true` still fail the check **Flags:** - `--staged` - Only check staged files (not whole repo) - `--kb-path ` - Path to KB directory (optional) - `--rules ` - Comma-separated list of rules to run (optional) - `--min-links ` - Minimum requirement links per symbol for staged traceability (default: 1) - `--dry-run` - Show staged-traceability effects without modifying files - `--format json|text` - Output structured JSON for integrations such as OpenCode scheduled checks, or human-readable text output (default: text) - `--fix` - Show each violation's whole fix suggestion. Text output otherwise prints the first sentence of each suggestion. - `--symbol-debt` - List the unrecorded declarations per file. Without it a full check reports only their count: a passing check prints one line, `✓ No violations. 66 rules. 2,924 unrecorded declarations in 522 files do not block (kibi check --symbol-debt lists them).`, and JSON `symbolDebt` carries `total` and `fileCount` without `files`. - `--fresh-evidence` - The `evidence-floor` rule judges proof receipts as they are: a requirement whose receipts are only older than the code fails instead of counting as pending re-proof, and the proof snapshot must be clean. Run it right after `kibi prove` - `--write-certificates ` - Also save the `kibi.certificates.v1` bundle the `kb-consistency` rule re-checked (not with `--staged`) - `--certificates ` - Only re-check a saved bundle against the current KB with the independent checker and print the `kibi.verification.v1` report (one verdict per theorem: `proved`, `disproved` or `unresolved`, and every rejected certificate with the reason; `--format json` prints it as JSON). Exits 1 when a certificate is rejected or missing or a theorem is disproved; cannot be combined with `--write-certificates`, `--staged` or `--rules` ### Staged Impact Evidence When `kibi check --staged` reports `kibi_impact_evidence_missing`, first use Kibi discovery (`kb_search`, then `kb_query`) through visible MCP tools or trusted CLI JSON routes to inspect existing requirements, scenarios, tests, facts, and symbols for the edited source file. If the edit changes behavior, update the KB through either peer surface and also stage tracked evidence that the commit can carry: related entity markdown under `.kb/` or authored `.kb/symbols.yaml` entries. An edit where every declaration the commit adds or changes already has a `.kb/symbols.yaml` entry (and no entry the commit is judged on names a gone declaration) needs nothing more: coordinates are derived locally and never staged. No declaration line in a note or commit message waives the diagnostic: staged evidence or full manifest coverage are the only ways to clear `kibi_impact_evidence_missing`. A commit is judged only on what it changes. Compared with the base tree, a declaration is in the change when its title is new or its text differs once comments and whitespace are dropped (a declaration that only moved or was reformatted is not); a record is judged when the commit removes it, adds or changes it, or removes or renames its declaration. A copied file and an added file are judged on every declaration. Gaps the commit did not cause (unchanged declarations with no record, untouched records whose declaration was already gone) never block: the text output prints one `Symbol records: has N declaration(s) without a .kb/symbols.yaml record that this commit did not add or change ...` line per file, `--format json` lists them under `inheritedSymbolGaps`, and no action is required. One declaration that the commit adds or changes and that no requirement owns is printed as one block, first, instead of up to four findings for the same cause (`symbols_manifest_stale`, `kibi_impact_evidence_missing`, `symbol_semantic_review_needed` and the `Traceability failed` row): ```text [BLOCKS COMMIT] renameTag (src/tags.ts:5) is new and no requirement owns it. If one of these already states what it does, link it to that one (never pick one only to pass the gate): REQ-tags-001: Tag creation kb_upsert {"type":"req","id":"REQ-tags-001","properties":{"title":"Tag creation","status":"open"},"implementedBy":[{"sourceFile":"src/tags.ts","symbol":"renameTag","coveredBy":["TEST-tags-001"]}]} If it is new behavior, record a requirement for it first (template: kb_skills kibi-commit-review), then link it the same way. CLI: pipe a kb_upsert input to npx --no-install kibi upsert --input -. Then: git add .kb && git commit ``` The candidates are the requirements other code in the same file implements, in id order; Kibi never picks one. The first three get a paste-ready `kb_upsert` input, whose `coveredBy` names the tests that cover that other code; the rest are named. A type, interface or enum gets a symbol record with `symbol_role: type-shape` instead, since it needs no requirement link. A declaration that has a record but no `implements` link says so ("has a symbol record but no requirement owns it"). Findings that also name other declarations stay as they were. `--format json` keeps every underlying finding under `violations` and `qualityDiagnostics` and adds `ownerFindings`: per declaration, `blocks: "commit"`, `symbol`, `file`, `line`, `state` (`new` or `unlinked`), `typeShape`, `causes` (the ids it stands for), `candidates` (`id`, `title`, `status`, `tests`) and `payloads`. Both `kibi_impact_evidence_missing` and `symbols_manifest_stale` carry `Detail:` lines that name the cause per file: how many declarations the commit adds or changes and exactly which of the judged ones are missing from `.kb/symbols.yaml` (with their definition lines). When the Detail lines list uncovered symbols, fix the cause first — author `.kb/symbols.yaml` entries for those symbols (`kibi upsert`), each with a `symbol_role`; behavioral code also needs `implements`/`covered_by` links, and a function, class, method, property, accessor or a variable holding a function always does — and re-point or retire entries listed as evidence without a matching symbol; the same comparison drives the printed `Suggestion:`. The comparison is by symbol title: coordinates are derived, so a declaration that only moved is never a finding. Detail lines name every symbol, never a shortened list; the `--json` diagnostic `evidence` (`symbolsManifest[].missing`/`extra`, `uncoveredSymbols[].titles`) carries the same complete lists. Generated files are left to their generator. A staged TypeScript or JavaScript file that the commit's base marks generated (a `package.json` `kibi.generatedPaths` glob, `linguist-generated` or `linguist-vendored` in `.gitattributes`, or a generator header such as `@generated` or `Code generated ... DO NOT EDIT` in the committed version of the file) does not need a requirement link for its symbols, and other generated staged files get no `staged_file_ownership_missing` warning. The output names those files (`Generated files: symbols without a requirement link in ...`). The marks are read from the commit's base, so a change cannot exempt itself by adding a header, an attribute or a pattern; a new generated file is exempt once a committed `.gitattributes` rule or `kibi.generatedPaths` glob covers it. A generated file that `.kb/symbols.yaml` names keeps the full check, and symbols that already carry a requirement link are still checked. A `!` pattern in `kibi.generatedPaths` (`"!src/gen/hand-written.ts"`) or `linguist-generated=false` brings a file back under the check. While a merge commit is being made (`MERGE_HEAD` exists, for example after resolving conflicts), `kibi check --staged` judges only what the merge itself changed: staged files whose content equals a merged parent's are taken from that parent unchanged, sit in the comparison base, and are neither listed nor checked. The output says how many files were skipped this way (`Merge commit: N staged file(s) are taken unchanged from the merged branch ...`); any debt in them was inherited from that branch. A file the merge resolved or edited is judged in full. When the staged change moves knowledge files into the canonical `.kb/` layout, as the first commit after `kibi migrate` does, `kibi check --staged` compares each moved file with its committed content at the old path instead of treating it as new. A move qualifies when Git detects it as a rename (or, for a small file the move also rewrote below Git's similarity threshold, when exactly one deleted file and one added file share the file name), the old path is outside `.kb/`, and the new path is the same kind of knowledge file: an entity document into the `.kb/` lane of the same name (`docs/requirements/REQ-x.md` to `.kb/requirements/REQ-x.md`), or `symbols.yaml` / `symbol-coordinates.yaml` onto the canonical file. Only the edits the commit made inside those files are judged, so the move is not blocked by findings the files already had, for example `symbol-coverage` for every symbol of a migrated manifest. A manifest record the commit adds or changes, including records migration rewrites, is still checked in full. The output starts with `Baseline: HEAD with N staged knowledge rename(s) into .kb/ resolved ...`; full `kibi check` still reports the pre-existing findings. Renames inside `.kb/` and edits to files that were already canonical are compared with HEAD as before. When the staged commit carries a `kibi migrate` run, a symbol record whose only differences from its base are fields the migration writes mechanically is not counted as changed by the commit: a `granularity_reason: legacy-link` the base did not have, and an added `review:context-missing` tag (`origin`, a removed dead `source` and a pinned `semantic_text` are not part of the compared symbol record). The output then also starts with `Migration commit: N symbol record(s) changed only by kibi migrate ... are not judged as changed by this commit: `. A commit carries a migration when the staged `.kb/manifest.json` records a newer `schemaVersion` than the base, or the commit removes the legacy `.kb/config.json`; the audit record under `.kb/migrations/` is ignored by Git, so it is not the signal. Outside such a commit, adding `legacy-link` to an existing record is a change like any other. Records the commit adds, and records it edits in any other field (an `implements` link, for example), are judged in full. A staged requirement whose semantic inventory is missing or no longer matches its prose blocks the commit with the same test `kibi sync` applies (proposition-complete ingestion) when the requirement declares an inventory contract (`semantic_inventory_version`, `semantic_source_hash` or `semantic_inventory`) in the staged file or in `HEAD`, when it is new: its path is not in `HEAD` (a renamed requirement counts as new), or when its statement (the prose the inventory covers) differs from `HEAD`. A repository's first commit is exempt, and so is `git commit --amend` of it, since `kibi sync` imports it as its semantic baseline. Other requirements without a contract, for example one whose commit only edits its Context section, are left to `kibi sync`. Each finding names the requirement and the contract errors; re-derive a drifted inventory with `kibi migrate`, or run `kb_model` analyze with the complete prose and write the inventory contract it returns. KB writes through MCP or CLI JSON routes update branch state, but they do not automatically stage markdown or manifest files. The staged hook can only accept evidence present in the staged change-set, so run the required sync/authoring step and `git add` the tracked evidence before rerunning `kibi check --staged`. **Examples:** ```bash # Check entire KB kibi check # Export structured two-lane check output for automation kibi check --format json # List the non-blocking unrecorded declarations per file kibi check --symbol-debt # Check only staged changes kibi check --staged # Run specific rules kibi check --rules must-priority-coverage,no-dangling-refs # Audit advisory strict-fact modeling without failing canonical health kibi check --rules strict-fact-shape # Audit strict requirement/fact pairing without failing canonical health kibi check --rules strict-req-fact-pairing # Audit predicate ontology links without failing canonical health kibi check --rules predicate-verifiability # Audit Prolog validation query plans kibi check --rules query-plan-safety # Audit requirement status vocabulary (catches ADR statuses on reqs) kibi check --rules req-status-vocabulary # Audit vocabulary convergence (duplicates, subject keys, prose-in-atoms) kibi check --rules domain-redundancy,subject-key-identity,subject-key-shape,ontology-quality ``` ### Vocabulary convergence checks Deduplication and contradiction checks only work when equivalent prose lands on the same subject, predicate, and arguments. These rules measure and nudge that convergence. They are advisory: findings are non-blocking `qualityDiagnostics` and never change the exit code. All of them are deterministic over the compiled KB (Prolog, plus TypeScript for `predicate-schema-conformance`, which also needs the built-in predicate catalog); none calls a plugin or the network. | Rule | Severity | Reports | | --- | --- | --- | | `domain-redundancy` | warning | Two distinct current requirements ground the identical logical term (same predicate/property signature after unit canonicalization, same polarity) or link the same ground fact via `requires_property`, `requires_predicate`, or `requires_rule`. Pairs linked by `supersedes` or `restates` (either direction) are exempt. Evidence carries both requirement IDs, both fact IDs, and the signature. Links are grouped by signature once, so cost grows with the number of links, not with requirement pairs. | | `domain-implication` | info | Same subject and property, comparable numeric operators, and one bound strictly implies the other (`lte 30 min` implies `lte 3600 s`). Reported as "Implied by", never as a duplicate. | | `subject-key-identity` | warning | A subject key of the form `req.[.…]` where `` is a normalized existing requirement ID (`req.req_cli_gc` for `REQ-cli-gc`, or without the `req_` prefix). Every requirement becoming its own subject makes cross-requirement checks impossible. Also reports one subject or claim minted as several facts: more than one active `subject` fact with the same `subject_key`, and more than one active `property_value` fact with the same `subject_key`, `property_key`, `operator`, `polarity` (absent means `require`), typed value and `unit` (a `forbid` fact states the opposite of its `require` twin, so the pair is never reported; facts linked only by superseded or deprecated requirements are history, not live duplicates; facts that differ in operator, such as the two bounds of a range, or in value, such as two requirements bounding the same property differently, are distinct claims that `domain-contradictions` and `domain-implication` compare). Each group is reported once, on its first fact id, with every fact id in the evidence. | | `subject-key-shape` | warning | Subject facts whose key is not dotted `component.aspect[.sub]` with lowercase snake segments (`kibi.cli.check.staged`), and `property_value` facts whose `property_key` numbers a clause (`clause_03_must_refresh_...`, `contract_clause_2`) instead of naming a property other requirements can share. | | `ontology-quality` | info | A predicate (namespace, name, arity) with at least `KIBI_ONTOLOGY_QUALITY_MIN_FACTS` facts (default 8) where the share of argument slots holding a value that occurs in only one fact is at least `KIBI_ONTOLOGY_QUALITY_MAX_SINGLETON_RATIO` (default 0.6): prose is being compressed into atoms. The message names each argument whose own singleton share reaches the threshold. Both variables are read from the invoking `kibi`/MCP process. | | `predicate-schema-conformance` | warning | A predicate fact with no `predicate_schema` for its namespace, name, and arity (project-local, or the built-in catalog in the `default` namespace), a fact using a value outside a declared argument vocabulary, or a schema whose `argument_constants`/`argument_aliases` are malformed. When the repair is mechanical, the finding carries it and `kibi migrate` offers it as an automatic action (see below). | | `entity-id-style` | warning | Markdown entities whose filename stem differs from the frontmatter `id`. New purely numeric IDs (`REQ-123`) are reported where they are created: `kb_upsert` warnings (including `dryRun: true` and `kibi validate-upsert`) and staged added or renamed entity files (`--staged`). Committed legacy numbered entities are never flagged. | Property values are compared after unit canonicalization: durations convert to seconds, data sizes to bytes (SI `kB`/`MB`, IEC `KiB`/`MiB`), and percentages to percent. The authored value is stored unchanged. Unknown or ambiguous units (`KB`, `Mb`, `month`) stay as written and are never equated with anything else. A `predicate_schema` can close an argument's vocabulary: `argument_constants` lists the allowed values per argument name, and `argument_aliases` maps legacy spellings to one of them. Arguments without an entry stay open. ```yaml fact_kind: predicate_schema predicate_name: check_finding_policy argument_names: [rule, finding, severity] argument_constants: severity: [warning, info] argument_aliases: severity: { warn: warning } ``` `kb_upsert` rejects a predicate fact that uses an undeclared value or an alias (naming the constant to use), and predicate suggestion (`kb_model` mode `predicates`, CLI `suggest-predicates`) binds aliases to their constant and leaves undeclared values unbound. Existing facts are converged by `kibi migrate` (below). While editing, agents can run impact diagnostics through MCP `kb_check({sourceFiles:[...], includeImpactDiagnostics:true, includeWorkingTreeDiff:true})` or the equivalent `kibi check --input ` JSON route. `kibi check --staged` remains the commit-time git-hook gate once files are staged. `kibi check --format json` (and `--staged --format json`) prints the MCP-shaped payload `{"structuredContent": {...}}`, the form the OpenCode scheduled check and other integrations read. The `kibi check --input ` JSON route is a catalog route and prints the standard `{"kibiProtocol", "operation", "status", "data", ...}` envelope every JSON route prints, with the `kb_check` result (violations, quality diagnostics, migration plan) under `data`. Structured JSON output preserves the same two-lane model used by MCP: hard correctness failures appear under `structuredContent.violations[]`, while advisory audit signals appear under `structuredContent.qualityDiagnostics[]`. For `--staged`, one envelope is emitted for every outcome. `structuredContent.staged.files[]` records each path's Git status, analysis depth, disposition, ownership, evidence, provider, and skipped reason; file-level advisory findings appear in `structuredContent.diagnostics[]`. Advisory-only output is still a successful check; integrations should inspect `blocking` and `severity` instead of treating every diagnostic as a failure. **See also:** [Staged Symbol Traceability](#staged-symbol-traceability) for `--staged` usage details. ## `kibi doctor` Verifies environment setup and diagnostics. **Behavior:** - Reports the Kibi release this install belongs to ("Kibi release"), using the release manifest that the installed `kibi-core` ships (`release.json`): the release version and its KB schema, operation protocol and plugin API versions. It warns ("Mixed install") when an installed Kibi package has a different version than that release lists, and also warns when `kibi-core` predates release manifests. A local pack stamped `-dev.` counts as its base version. JSON output carries the manifest under `runtime.release` and the per-package comparison under the check's `details` - Reports whether a newer `kibi-cli` is published on npm ("Kibi updates"): a newer version is a warning that names both versions, the update command for this install and, when the newer release writes a newer KB schema, the schema move and `kibi migrate`. It uses the cached daily answer and asks the registry only when that is a day old; an unreachable registry passes without a warning, and CI, tests and `KIBI_UPDATE_CHECK=0` / `NO_UPDATE_NOTIFIER` skip the check (see [Update notices](install.md#update-notices)) - Resolves the SWI-Prolog Kibi runs (`KIBI_SWIPL`, then the bundled `kibi-swipl-` package, then `swipl` on `PATH`), reports its source, path, and version, and loads every library Kibi requires; when the bundle is missing on a supported platform it names the package to add - Verifies `.kb/` directory exists - Validates `.kb/manifest.json` syntax - Recognizes leftover `.kb/config.json` and recommends `kibi migrate --yes` - Checks git repository presence: outside any repository it is a warning carrying the `no_git_repository` advisory (what is off until there is a repository, and `git init`, then `kibi init`), not a failure - Checks the current branch's KB store ("Branch store"): when `.kb/` holds authored sources but the store is missing or empty (journal sequence 0, nothing compiled), it warns that the next Kibi query or check compiles it when auto-sync is on (`kibi.setup.autoSync`, the default), and fails naming `kibi sync` when auto-sync is off (`KIBI_AUTO_SYNC=0` or `autoSync: false`) or the attachment is read-only, detached or awaiting migration; an incomplete or unreadable store points at `kibi branch recover` - Verifies git hooks are installed and executable, reading them from the directory Git uses (`git rev-parse --git-path hooks`). Missing hooks are a warning (`!`, `"warning": true` in JSON, counted in the top-level `warnings`), not a failure: without them a new branch is not compiled on checkout and commits skip `kibi check --staged` - When a hook manager owns the hooks (lefthook, husky, the pre-commit framework), reads the commands from its configuration instead of the generated hook files. A hook whose configuration visibly runs Kibi's commands passes; one that does not (for example because it calls a task runner) is a warning with `kibi init --print-hook --format ` as the remediation, since doctor cannot see through the runner - Otherwise treats a hook without a kibi-managed section as the project's own hook (hand-written, husky, lefthook, ...). A custom pre-commit passes when it runs both `kibi check-generated --staged --changed-only` and `kibi check --staged` (via `kibi`, `npx kibi`, `node_modules/.bin/kibi` or `"$KIBI_BIN"`; commented lines do not count), and a custom post-rewrite passes when it runs `kibi sync`. Otherwise the check fails and the remediation shows what to delegate to and `kibi init --print-hook `, because `kibi init` never edits a custom hook - Fails when an installed kibi-managed hook section differs from what the running CLI installs ("Kibi-managed hook sections"), compared by content rather than by version, for example a pre-commit hook written before the generated-manifest gate - Reports the engine daemon serving this workspace and branch ("Engine daemon"), without starting one: its package versions and SWI-Prolog from the daemon handshake. A daemon with other package versions than this CLI is reported, not failed; the next Kibi command stops and replaces it - Warns ("Manifest merge driver"), once `.kb/symbols.yaml` holds a symbol, when Git does not route `.kb/symbols.yaml` to `kibi merge-driver` (`merge=kibi` in `.gitattributes`) or `merge.kibi.driver` is not set, and prints only the setup steps that are missing (the `.gitattributes` lines, the `git config` command, or both); merges still work without it, with ordinary line conflicts; the driver command names the project's package manager (from its lockfile) - Fails ("Capability plugins") when a plugin `package.json#kibi.plugins` declares is not installed in the workspace (run `npm install`), and when an installed release-qualified source analyzer such as `kibi-plugin-treesitter` is not the exact build this Kibi pins (its pinned file hashes or version differ, for example an older build published under the same version): the remediation is to remove `node_modules/` and install the qualified build. Doctor resolves and hashes the package; it never imports plugin code - Warns, rather than fails, when the secret of an activated plugin is missing and every capability of that plugin is in `augment` mode (for example `TYPESAFE_API_KEY` for `kibi-plugin-jev`): the plugin is skipped and builtin providers keep answering. In `replace` mode the missing secret is a failure - Reports issues with remediation suggestions **Examples:** ```bash kibi doctor kibi doctor --format json ``` JSON mode emits `kibi.doctor.v1` with resolved CLI, core, and MCP versions and their entrypoint/package locations so release validation can prove which artifacts are executing. **Common Issues Found:** - SWI-Prolog not found → Add the platform package it names, or see the [install guide](install.md#which-swi-prolog-kibi-uses) - `.kb/` missing → Run `kibi init` - Git hooks missing (warning) → Run `kibi init` - Branch store not compiled with auto-sync off → Run `kibi sync` - Kibi-managed hook section without kibi CLI resolution → Run `kibi init` to regenerate it - Custom (non-Kibi) pre-commit hook does not run `kibi check-generated --staged --changed-only` and `kibi check --staged` → Add both to the hook; `kibi init --print-hook pre-commit` prints a ready-to-paste snippet. Re-running `kibi init` does not help, because init never edits a custom hook. An unmarked file that is an old Kibi template can instead be deleted so `kibi init` reinstalls it - Kibi-managed hook sections outdated for this CLI → Run `kibi migrate --yes` (or `kibi init`) to refresh them (hooks are shared by every worktree of the repository) - `.kb/manifest.json` missing beside a legacy `.kb/config.json` → Run `kibi migrate --yes` (not `kibi init`) - Legacy knowledge files that `kibi migrate` cannot move (a destination already exists) → doctor prints the same resolution `kibi migrate` and the migration plan report (stale symbols subset, generated coordinates, ambiguous symbols manifest, or a conflict to compare), instead of sending you back to `kibi migrate`. Legacy copies identical to their `.kb/` file are counted separately; `kibi migrate --yes` removes them - Config invalid → Check `.kb/manifest.json` syntax; leftover `.kb/config.json` is retired with `kibi migrate --yes` ## Release package validation Release validation packs the published packages in dependency order, verifies their compiled entrypoints and dependency ranges, and exercises isolated npm and pnpm consumers. Consumer repositories own their local update scripts and dependency overrides; Kibi does not rewrite a consumer's manifests or workspace configuration. ## `kibi usage-metrics` Reports adoption and quality metrics from `.kb/usage.log`. **Syntax:** ```bash kibi usage-metrics [--format json|table] [--limit N] [--require-acceptance] ``` **Behavior:** - Reads `.kb/usage.log` from the current repository - Summarizes tool usage, branch activity, and success/error outcomes - Reports telemetry completeness and zero-result rates - Shows `kb_check` violation trend entries and grouped `kb_upsert` error categories - Limits the zero-result source-file leaderboard with `--limit` - Adds a versioned `kibi.telemetry-acceptance.v1` report over the latest 200 events. It measures telemetry completeness, advisor-before-requirement-write use, exact validation-before-upsert use, lookup-before-first-edit (per host session, whether `kb_search` or `kb_query` ran before the first edit of a requirement-linked file, read from host plugin hook rows), source-linked zero-result rate, proof-gap recovery, receipt freshness, and repeated mutation failures. - Separates `failed` from `insufficient_evidence`: an empty, stale (older than seven days), future-dated, partial-coverage, or pre-field-upgrade log cannot pass merely because no failure was observable **Flags:** - `--format json|table` - Output format (default: table) - `--limit N` - Maximum number of top zero-result source files to include (default: 10) - `--require-acceptance` - Exit non-zero unless the acceptance status is exactly `passed`; the report is still printed for repair automation **Examples:** ```bash # Show the default table report kibi usage-metrics # Export the full report structure as JSON kibi usage-metrics --format json # Show only the top 5 zero-result source files kibi usage-metrics --limit 5 # Enforce the telemetry report as a completion gate kibi usage-metrics --format json --require-acceptance ``` **Notes:** - Returns an error if `.kb/usage.log` does not exist in the current repository - `--limit` must be a positive integer - Default thresholds are conservative and inspectable in `acceptance.policy`: at least 95% telemetry completeness, 100% advisor/preflight sequencing when applicable, 100% of host sessions looking requirements up before their first linked edit when hook rows record one, no more than 20% zero-result source lookups, no receipt-specific gaps, and fewer than three consecutive failures for any mutation target ## `kibi usage-remediation` Builds a read-only `kibi.telemetry-remediation.v1` report from `.kb/usage.log`. ```bash kibi usage-remediation [--format json|table] [--limit N] ``` - Enumerates the exact log line, request, timestamp, tool, target, reason, and repair action for events behind failed or insufficient acceptance metrics. Log lines count every line of `.kb/usage.log`, including host hook rows; a session whose first requirement-linked edit had no earlier lookup points at that hook row - Preserves session and actor identifiers when available; advisor and preflight evidence cannot match a write when both records expose different correlation identifiers - Keeps missing complete coverage evidence as an explicit report-level item - Sorts deterministically by repair rank, log line, and stable item identity - Does not write to the knowledge base or usage log; `--limit` only bounds rendered table rows and never truncates JSON evidence - The report uses exact canonical payload fingerprints for validation correlation when available and a deterministic legacy fingerprint otherwise. Requirement-advisor correlation requires the same requirement and, when both events expose it, the same semantic source hash. ## `kibi telemetry` Shows or changes the anonymous usage telemetry setting for the current user. ```bash kibi telemetry [status|enable|disable] [--format text|json] ``` - `status` (the default) prints whether telemetry is on, why (for example `KIBI_TELEMETRY=0`, `CI environment` or `on by default`), and where the settings and queue live - `disable` saves the opt-out for this user and deletes any events still queued; `enable` saves an opt-in, which does not apply in CI or test runs - `KIBI_TELEMETRY=0` and `DO_NOT_TRACK=1` always win over the saved choice - `--format json` prints `{ enabled, reason, directory, docs }` What is sent and when is described in [Usage telemetry](./telemetry.md). ## `kibi migrate` Previews or applies the structured branch migration plan. With no mutation flags, it is a read-only preview; `--format json` returns the complete `kibi.migration-plan.v2` action graph. **Behavior:** - Upgrades entity schemas and internal storage formats - Marks pre-existing coarse symbol links with `granularity_reason: legacy-link` at any schema version, using the same rule as the staged granularity gate (`kibi check --staged`): a traceability link is coarse when the source declares narrower behavioral symbols, such as the methods of a linked class (`ClassName.methodName`) or other exported functions when the linked title is not declared at all. The pass is idempotent; the plan offers it as the automatic `symbol_legacy_link_mark` action (id `symbol-legacy-link-mark`), bound to the hash of `.kb/symbols.yaml` it was planned from and listing each symbol with the narrower symbols that make it coarse - Refreshes generated symbol coordinates, the way `kibi sync --refresh-symbol-coordinates` does, whenever the run rewrote or moved `.kb/symbols.yaml` (a moved legacy manifest, or legacy-link marks, which change a record's coordinate identity), and prints `Refreshed generated symbol coordinates for the migrated .kb/symbols.yaml; ...`. The `symbol-legacy-link-mark` plan action refreshes them the same way. The first commit after a migration therefore carries a current `.kb/symbols.yaml`, and the pre-commit `kibi check-generated --staged` gate reports no drift. A symbol that gets no coordinates is listed as `failed : ` as in sync; if the refresh itself fails, the migration stays applied and a warning names `kibi sync --refresh-symbol-coordinates` as the step to run before committing - Fixes legacy requirement modeling to follow strict fact-pairing rules - Moves legacy `documentation/` knowledge lanes and leftover `.kb/config.json` into the canonical `.kb/` layout - Replaces the pre-canonical blanket `.kb/` gitignore stanza with derived-runtime ignores so migrated `.kb//` files are trackable - Schema 13: adds `.kb/symbol-coordinates.yaml` to `.gitignore` and removes it from the Git index (`git rm --cached`; the local file stays), because sync derives coordinates from source. Commit the removal with the migration - Schema 14: accepts `status: retired` (with `retired_reason`) on requirements, and `kibi check` blocks `retired-reason-missing` and `retired-owner-only`. No file is rewritten. At any schema version the plan lists each `closed` requirement that nothing supersedes and whose own source says it was retired (its `proof_exempt_reason` or title says retired or archived, its body says "this requirement was retired", or a `historical-status:` tag records retired, archived, deprecated or superseded) as a `req_retired_status_suggest` review action (id `req-retired-status-`). Its evidence lists the `signals` and the `retiredReason` it would write; approving it by id (`--approved-action req-retired-status-`) sets `status: retired` and `retired_reason`, changing only those two lines, and refuses when the requirement is no longer `closed`. `--dry-run` and `--yes` print the requirements it found. Leave a requirement that is done and still valid `closed` and mark the action deferred - Schema 16: domain subjects. No file is rewritten by the upgrade itself; at any schema version the plan lists the subject layer's open items. An unmodeled rule claim that names no subject gets `claim_subject_anchor_suggest` (id `claim-subject-anchor--`) when its words match one defined subject better than any other: approving it by id adds `subjects: []` to the inventory entry, inserting only those lines. A tie or no match gets `claim_subject_anchor_review` with the candidates, for a person to pick or define. A subject fact without a definition gets `subject_definition_review` (id `subject-definition-`), and two subject facts that read as one get `subject_duplicate_review` (id `subject-duplicate--`). Kibi never writes a definition - Schema 19: `quantity-duplicate` blocks two value facts of current requirements that state one quantity under different keys. No file is rewritten: whether two facts are one quantity is a person's call, so at any schema version the plan lists each pair as a `quantity_duplicate_review` action (id `quantity-duplicate--`) naming both claims, keys, values, requirements and files, and the upgrade notes how many pairs it found. Ground both claims on one key, or add `distinct_from` on either fact when they are different quantities; Kibi never writes `distinct_from` on its own. - Schema 20: [Kibi levels](#kibi-level). No file is rewritten: the upgrade leaves the level as it is, so a project that sets none stays at `test`, and its note says how a person chooses `remember` (set `kibi.level` in `package.json`, or `level` in `.kb/setup.json`, to `remember`, or run `kibi init --level remember`). - Treats malformed `.kb/config.json` as a blocker instead of guessing `documentation/` paths - Classifies a legacy file whose `.kb/` destination already exists, with or without a legacy `.kb/config.json`: a byte-identical copy is removed (the dry run lists it as `would remove`), and anything else blocks the move with a resolution. A legacy symbols manifest whose symbol ids are all in `.kb/symbols.yaml` is reported as a stale subset to remove with `git rm`, a `symbol-coordinates.yaml` copy as generated (keep `.kb/`, `kibi sync --refresh-symbol-coordinates` regenerates it), and other content as a conflict to compare. Kibi only deletes the identical copy itself. - Without `paths.symbols` in a legacy config whose lanes sit under another folder (for example `kibi-docs/requirements`), takes the symbols manifest beside those lanes (`kibi-docs/symbols.yaml`) instead of the `documentation/symbols.yaml` default. When a `documentation/symbols.yaml` exists too, or is the only candidate, the move is blocked as ambiguous until `paths.symbols` names the current manifest or the stale one is removed. - Writes `.kb/manifest.json` with the latest `schemaVersion`. While a legacy `.kb/config.json` is present, its `schemaVersion` is where the migration starts, even when a manifest already sits beside it, so no legacy step is skipped. The file move records that legacy version in the manifest and the latest one is written only after the schema steps, so an interrupted run replays them. An empty `.kb/symbols.yaml` seeded by an older `kibi init` does not block the move; the legacy symbols manifest replaces it. - After moving files in a Git repository, writes a pending-source receipt (`.kb/recovery/pending-sources/`, the record `kb_upsert` keeps for files it creates) for every moved file Git does not track yet, so `kibi sync` compiles the moved knowledge at once. Kibi never stages files: the warning asks you to stage them (`git add .kb`, plus the removals under the legacy folders) before committing, and each receipt retires once Git tracks its file. Later migration steps that rewrite a moved file rebind its receipt. - Collapses the `source-relationship-parity` findings that `kibi check` explains by untracked files (evidence `untrackedSources`) into one `untracked_knowledge_sources` review action (id `untracked-knowledge-sources`) that lists the files and the number of relationships, instead of one action per relationship. - Offers `predicate_schema_alignment` actions for `predicate-schema-conformance` findings with a mechanical repair: moving a predicate fact to the only namespace whose schema matches its name and arity, and rewriting argument aliases to their declared constants (with the matching `canonical_key`). Each action is `automatic`, carries the exact `kb_upsert` input, and re-reads the fact before writing; a fact that changed since planning fails the action instead of being overwritten. Ambiguous namespaces and undeclared values stay review actions. - Schema 6 (from 5 or older): the `entity_origin_backfill` action records `origin: {kind: migration, ref: "kibi migrate v5->v6", recorded_at}` as the last frontmatter key of every authored entity that has no `origin`; every other byte of the file stays as it was, and entities that already carry an `origin` are left alone. Its evidence lists the count, the count per type, and any file it cannot stamp safely (with the reason). - Schema 8 (from 7 or older): the `entity_body_context` step edits front matter only; every body stays byte-identical. Its `semantic_text_pin` action writes `semantic_text` on each requirement that lacks it, using the pre-schema-8 derivation from the body, so claim spans and hashes do not move once context sections are excluded from derived meaning. Its `context_missing_tag` action adds the tag `review:context-missing` to each current `req`, `scenario`, `test`, `adr` and observation/meta `fact` that fails the body-context test and records those ids (and any already tagged) in `.kb/manifest.json` as `contextAcknowledged`; it never writes prose. Both are idempotent, and `--dry-run` reports the counts (tagged entities per type). `kibi check` treats tagged entities as acknowledged legacy and counts them in the advisory `entity-context-acknowledged` diagnostic. - Re-derives drifted semantic inventories at any schema version. When the current semantic advisor reads a requirement's prose differently from its stored `semantic_inventory` (for example a claim it used to call `rationale` is now `normative`), `kibi sync` rejects the requirement. `kibi migrate` lists every such requirement. A `semantic_inventory_rederive` action (automatic) rewrites the inventory with the current advisor: a claim whose `claim_key` and `claim_text` still match keeps its status, so a modeled claim stays modeled with its grounding; a new or reclassified claim becomes unresolved (`ontology_gap`, `ambiguous` or `missing`), never modeled; `logic_claims` and `semantic_source_hash` are rewritten to match. Only the contract fields change. The action re-checks the contract hash it was planned with before writing. A requirement Kibi cannot re-derive safely (a grounding fact whose `claim_key` is no longer a modeled claim, or a modeled claim that is now context) gets a `semantic_inventory_review` action instead. Its evidence carries the re-derived `contract` (inventory, `logic_claims`, source hash) and its instruction says to write that contract into the requirement's front matter and re-ground or remove the listed grounding links in the file itself, because `kibi sync` rejects the requirement and store-backed tools cannot see it yet. It also gives a `kibi model --input -` analyze input (`{"mode":"analyze","type":"req","id":...,"text":...}`) that passes the public schema. When the requirement would pass ingestion once the orphaned grounding links are gone (each link in its own front matter `links`, pointing at a fact whose `claim_key` is no longer a modeled claim), the plan also offers `semantic_inventory_rederive_drop_grounding` (id `semantic-inventory-rederive-drop-grounding-`, safety `review`): it writes the re-derived contract and removes exactly the grounding links listed in its evidence (`droppedGrounding`); the facts stay. It drops modeled logic, so `--apply-safe` never selects it on its own: approve it by id with `--approved-action`. It re-checks the contract hash and the link list it was planned with, and verifies that the rewritten requirement passes ingestion before writing anything. `kibi sync` stays fail-closed: it still rejects the whole sync while any requirement fails. - Maps the legacy delivery statuses `implemented`, `done` and `completed` to `status: closed` plus the tag `implemented` in one automatic `req_status_delivered_map` action (id `req-status-delivered-map`). These statuses are outside the entity schema, so `kibi sync` cannot compile such a requirement and store-backed tools do not see it; closed with the tag `implemented` keeps the meaning (delivered, and a must-priority requirement still owes its scenario and test). The evidence lists each mapping (`{requirementId, path, from, to, tag}`); the edit replaces the `status` line and adds the tag to `tags` when it is missing, leaving every other byte of the file alone. `kibi migrate --yes` applies it and prints `Mapped legacy status implemented -> closed (tag implemented) on N requirement(s): ...`. - States the folder-implied `type` (`req` under `.kb/requirements/`, `scenario` under `.kb/scenarios/`, and so on) as the last front matter key of every authored entity file that has none, at any schema version, in one automatic `entity_type_backfill` action (id `entity-type-backfill`). Such files were written before Kibi stated the type in front matter; sync already reads the type from the folder, but every Kibi write states it, so without this the first `kb_upsert` after a migration would add an unrelated `type:` line to the user's change. Only that line is added. `kibi migrate --yes` applies it and prints `Stated the folder-implied type on N entity file(s) without one (...)`; a KB migrated by an earlier version gets it from its next `kibi migrate`. - Lists every other requirement whose authored status is outside the requirement vocabulary (`req-status-vocabulary`, for example ADR `status: accepted`, or an unknown status such as `wip`) as a `req_status_vocabulary_map` review action (id `req-status-vocabulary-map-`), planned from the source files so it is available before the KB compiles. Such a requirement is skipped by the proof ladder and its semantic inventory is never validated, so drift stays hidden until the status changes. The evidence suggests a target (`accepted`, `proposed` and `draft` map to `open`; `superseded` to `closed`; `deprecated` and `rejected` to `retired`, which then needs a `retired_reason`) and reports the `latentDrift`: the ingestion errors the requirement would have with that status. The target is a semantic choice, so the action runs only when approved by id; it replaces only the `status` line and refuses when the status changed since planning. To pick another status, set it in the file instead. When the latent drift exists, the plan adds the matching re-derivation (`semantic_inventory_rederive`, or the drop-grounding variant) as a review action that depends on the status action, so approving both (`--approved-action req-status-vocabulary-map-,semantic-inventory-rederive-`) applies them in order, and approving the re-derivation alone is refused. A status without a suggestion gets a plain review action. When the status keeps the file from compiling, the evidence carries the `extractionError` and the instruction says that `kibi sync` cannot compile the requirement until the status is fixed. - Repairs the blocking lifecycle findings from authored sources at any schema version. A `close_superseded_requirements` action (automatic, id `close-superseded-requirements`) sets `status: closed` on every superseded requirement that is not closed, replacing only the `status` line. Requirements that supersede each other are never closed automatically: each cycle gets a `review_supersession_cycle` action naming every member and edge, so a person decides which requirement is current. A `source_path_rewrite` action (automatic, id `source-path-rewrite`) repairs every authored `source` field that is redundant or dead; the compiled `source` is always the entity's own file, so nothing Kibi compiles is lost. Its evidence lists rewrites (`{entityId, file, from, to}`): a value that names another knowledge file by its pre-canonical path (`documentation//...`, or `/...` relative to the knowledge root) is pointed at that file under `.kb//`, keeping any `#anchor`. It also lists removals (`{entityId, file, from, reason}`): a value that names the entity's own file, in the pre-canonical or `.kb/` spelling, with or without `./` or `#anchor`, compared case-insensitively, is removed with reason `self`, and a dangling value Kibi cannot map is removed with reason `dangling`. A value that names another existing workspace path, an http(s) URL or an existing entity id is provenance and stays. Each edit replaces or removes only the `source` line and must read back with every other frontmatter key unchanged. A value Kibi cannot edit safely (one spanning several lines, for example) gets a `review_source_path_dangling` action for a person instead; that is the only review this repair produces. Both automatic actions re-read their files and refuse to write when the value changed since planning; `migration-sync` depends on them. `kibi migrate --yes` performs the same repairs directly, prints the cycles and the source fields it could not edit as warnings, and `--dry-run` prints the counts it would rewrite and remove. - Lists the schema 6 items a person must decide as review actions with stable ids: exceptions that exempt a requirement but have no `approved_by` (`review_exception_unapproved`), agent-recorded exception approvals nobody corroborated (`review_exception_approval_self_attested`), one action per predicate named by `rule-key-arguments-missing` (`review_predicate_key_arguments`), one per scenario reported by `scenario-feasibility-unknown` (`review_scenario_feasibility_unknown`), one queue for the agent-authored requirements `agent-requirement-unapproved` lists (`review_agent_requirements_unapproved`), one queue for the symbols `symbol-owner-superseded` lists (`review_symbol_owner_superseded`), one queue for the requirements `requirement-rationale-missing` lists (`review_requirement_rationale_missing`), one action per ADR reported by `adr-unlinked` (`review_adr_unlinked`) or `adr-proposed` (`review_adr_proposed`), and any blocking violation. It also lists, as one review queue (`review_inline_implements_comment`), every `implements REQ-...` comment still in a tracked source file: Kibi no longer reads these comments, so each one whose link still holds needs a `.kb/symbols.yaml` entry, and the comment can then be deleted. The evidence gives each comment's file, line, the ids it names, and `manifestLinked` (the ids a manifest symbol of the same file already implements, for which deleting the comment loses nothing). `kibi migrate` never edits source code. - When the plan rewrites authored sources, the schema upgrade depends on those rewrites and a `migration-sync` action recompiles the KB, so the check and coverage readback after `--apply-safe` already see the migrated files. `migration-sync` is left out while a requirement still needs a manual inventory fix, because sync would reject it, and when no source is rewritten and the status plan already compiles or resyncs the KB after the schema upgrade, so the plan matches the `kb_status` plan. For the same reason, the status plan's `freshness-resync` and `branch-store-compile` syncs depend on the inventory re-derivations, and are blocked (evidence `blockedBy`) while a `semantic_inventory_review` is open. - Plans quality actions only from a branch store that has been synced at least once; a never-synced store is reported as an incomplete `quality` domain instead of as one missing-relationship action per authored link. - Refreshes the kibi-managed sections of this checkout's Git hooks (`post-checkout`, `post-merge`, `post-rewrite`, `pre-commit`) when they differ from the template the running CLI installs, at any schema version, so `kibi doctor` passes "Kibi-managed hook sections" after an upgrade without a `kibi init`. The comparison is by content, not by version string, so a section written by another build of the same version is refreshed too. Only the text between `# BEGIN kibi-managed` and `# END kibi-managed` is rewritten; user-authored lines stay, a hook without a kibi-managed section is never installed, a symlinked hook is left alone with a warning, and nothing is touched where a hook manager owns the hooks or the hooks directory resolves outside the repository. `kibi migrate --yes` prints `Refreshed the kibi-managed sections of ...`, and `--dry-run` names them. The plan offers it as the automatic `managed_hook_sections_outdated` action (id `git-hooks-refresh`, category `hooks`), whose evidence lists the hooks and the SHA-256 `templateDigest` of the templates it was planned with; applying it with a CLI whose templates differ is refused, so rerun `kibi migrate` for a current plan - Idempotent: safe to run if already on the latest version. A second run after a completed migration plans no schema 6 actions, and `kibi migrate --yes` reports that no migration is needed. - The text preview lists migration actions apart from the quality backlog: review findings `kibi check` and `kb_status` report at any schema version (codes `quality_*`, `coverage_*`, and check reviews such as `review_adr_unlinked`) are counted per code under "Quality backlog (not part of the migration)", and `Migration: complete` means no migration action remains even when the backlog is long. `--backlog` lists each backlog action; `--format json` keeps the complete, unchanged plan. - After a completed migration, prints how to wire `kibi merge-driver` for `.kb/symbols.yaml` when Git does not route the file to it yet **Flags:** - `--dry-run` - Show what would be migrated without making changes - `--backlog` - In the text preview, list every quality and coverage backlog action instead of counts per code - `--yes` - Apply migration changes without prompting - `--format json|table` - Render the structured plan or a concise table. With `--apply-safe`, the table form prints the outcome, one line per action and a summary of the remaining plan; `--format json` prints the full apply result - `--apply-safe [SHA256]` - Apply only approved deterministic actions of the plan with this hash. The text preview prints the exact `kibi migrate --apply-safe ` command when the plan has ready automatic actions. A plan applies only with its current hash: when the plan changed after it was printed, nothing is applied and the error names the new hash and what changed (actions added, removed or changed state, and whether the KB snapshot, workspace files, branch or config moved) - `--approved-plan-hash SHA256` - The same hash as a separate flag (`--apply-safe --approved-plan-hash `); giving two different hashes is an error - `--approved-action ID` - Explicit action ID (repeatable or comma-separated): an automatic action, or a review action Kibi can execute once approved (`semantic_inventory_rederive_drop_grounding`, `req_status_vocabulary_map`, `req_retired_status_suggest`, `claim_subject_anchor_suggest`, or a `semantic_inventory_rederive` that depends on a status mapping). Without it, `--apply-safe` applies every ready automatic action and no review action. `--approved-action` and `--approved-plan-hash` only apply with `--apply-safe`; given without it, the command applies nothing and exits with code 2 After `--apply-safe`, the table form prints the plan `kibi migrate` builds now (`Remaining plan : ; actions: N (M migration, K quality backlog); automatic-ready: R`) and records it like the preview does, so that hash is one `--apply-safe` accepts. N counts every action of the plan, as the JSON `summary.actionCount` does; the text preview's `Migration: M action(s)` line counts only the migration section, and its `Plan status` line gives the total; when it still has ready automatic actions, the next `kibi migrate --apply-safe ` command follows. **Example (predicate vocabulary):** ```bash kibi migrate --format json > plan.json # review predicate_schema_alignment actions kibi migrate --apply-safe --approved-plan-hash "$(jq -r .planHash plan.json)" ``` **Example (schema 5 to 6):** ```bash kibi migrate --format json > plan.json # origin backfill, inventory re-derivations, review items kibi migrate --apply-safe --approved-plan-hash "$(jq -r .planHash plan.json)" kibi migrate --format json # remaining review actions, now including kibi check findings ``` `kibi migrate --yes` performs the same automatic steps without a plan: it stamps origins, maps the legacy delivery statuses, re-derives the inventories it can, prints a warning for each requirement that needs a manual fix, and records `entityOriginBackfill`, `supersededRequirementsClosed`, `sourcePathsRewritten`, `sourcePathsRemoved` and `legacyStatusesMapped` in `.kb/migrations/.json`, with `status: applied` and, as `preMigrationWarning`, the schema warning the KB showed before the run. `kibi migrate --dry-run` prints what it would change, including the review counts below. Like `--apply-safe` with its `migration-sync` action, `kibi migrate --yes` then compiles the branch store from the rewritten sources (`Recompiled the branch store from the migrated sources (kibi sync).`), so the next `kibi check` and `kibi status` read the migrated KB rather than a stale store. It skips the sync while a requirement status or inventory would make `kibi sync` reject the KB, and says to run `kibi sync` once those are fixed; a sync that fails leaves the migration applied and prints a warning. From schema 15 or older, `--yes` and `--dry-run` also print the schema 16 review counts (`Schema 16 review: ...`): unmodeled claims that name no subject, split into those with a suggested subject to approve by id (`claim_subject_anchor_suggest`) and those a person anchors by hand (`claim_subject_anchor_review`), subject facts that need a definition (`subject_definition_review`), subject pairs that read as one or share one `subject_key` (`subject_duplicate_review`), and subjects that name themselves or loop through `part_of`, `kind_of` or dotted keys (`subject_hierarchy_review`). A subject fact with no body at all gets the same `Definition not stated: ...` note bootstrap writes (the automatic `subject_definition_not_stated` action in the plan); a body with any text is never replaced. After the sync, `--yes` runs a plain `kibi check` on the synced store. When it reports any blocking finding (the rules schemas 15-18 added, such as `claim-subject-missing` or `agent-requirement-unapproved-implemented`, or any other), the run prints `Schema upgrade applied, but review work remains: kibi check reports N blocking finding(s) the upgrade does not fix (...)` with the count per rule and the next steps, instead of `Migration complete`. N is the count `kibi check` reports. When work remains that `--yes` does not apply (a requirement status with no safe mapping, an inventory that needs a manual fix, or a lifecycle item a person decides), the run does not print `Migration complete`. It prints `Migration incomplete: N requirement(s) are not compiled, so kb_query, kb_coverage and kb_upsert do not see them, and M other item(s) need a decision.`, one line per uncompiled requirement with its file, the extraction error and the edit that fixes it, and the next command to run. The exit code stays 0, as for any run that leaves review actions; `kibi status` and `kibi check` keep reporting the uncompiled files until they compile. **Notes:** - Use `kibi status` to check if a migration is pending for your branch. - Safe application rejects stale hashes, blocked actions, review/operator actions, and actions omitted from `--approved-action`. - Migration is recommended when upgrading `kibi-cli` or `kibi-mcp` packages. - Migration refreshes symbol coordinates itself when it rewrites the symbols manifest; run `kibi sync --refresh-symbol-coordinates` only if it warned that the refresh failed or coordinate diagnostics remain. ## `kibi gc` Garbage collects stale branch knowledge bases. **Behavior:** - Lists branch KBs that no longer exist in git - Quarantines stale stores first; irreversible deletion requires explicit purge - Keeps quarantined stores restorable during the retention window (30 days by default) - Safe by default (dry-run mode) **Flags:** - `--dry-run` - Only list stale branches (default) - `--force` - Quarantine stale branches (reversible) - `--purge` - Permanently purge quarantined stores past retention - `--retention-days ` - Retention window for purge (default: 30) **Examples:** ```bash # List stale branches (safe) kibi gc --dry-run # Quarantine stale branches kibi gc --force # Purge expired quarantined stores kibi gc --purge --retention-days 30 ``` **Notes:** - Use `--dry-run` first to see what would be deleted - Stale = an exact or legacy store whose branch is not a local Git head or worktree branch; remote-only refs do not keep stores live ## `kibi merge-driver ` Git merge driver for `.kb/symbols.yaml` and `.kb/relationships/*.yaml`. Git passes the ancestor (`%O`), current (`%A`), and other (`%B`) versions; the driver merges the record lists by `id` and writes the result to ``. **Behavior:** - Keeps records added on either side, applies one-sided edits and deletions, and unions relationships and links both sides added to one symbol - Reproduces the current file byte for byte when nothing changed - On a real conflict (both sides changed the same field differently, an edit against a deletion, duplicate ids, or invalid YAML) prints each conflict, leaves ordinary conflict markers, and exits 1 **Setup:** ```text # .gitattributes .kb/symbols.yaml merge=kibi .kb/relationships/*.yaml merge=kibi ``` ```bash git config merge.kibi.driver "npm exec --no -- kibi merge-driver %O %A %B" ``` Use `pnpm exec kibi`, `yarn exec kibi` or `bunx --no-install kibi` in place of `npm exec --no -- kibi` in pnpm, Yarn or Bun repositories; `kibi doctor` and `kibi migrate` print the command for the lockfile they find. `.kb/symbol-coordinates.yaml` is never committed, so it never conflicts; the next sync after the merge rebuilds it. For a CI job that applies this to open pull requests, see [GitHub badge + report](github-integration.md#merge-conflicts-in-kibi-manifests). ## `kibi branch` Lists and manages branch knowledge bases. **Syntax:** ```bash kibi branch ensure kibi branch migrate --from --to [--apply --approval-hash ] kibi branch recover [--apply] kibi branch restore --branch [--apply] ``` **Arguments:** - `ensure` - Ensure the active branch has a branch-local KB snapshot - `migrate` - Preview (or, with `--apply`, atomically move) a legacy branch KB into the exact active Git branch namespace - `recover` - Preview (or, with `--apply`, rebuild) an incomplete or unreadable exact branch store from authored sources while preserving the original bytes - `restore` - Preview (or, with `--apply`, restore) the newest quarantined exact branch store within its retention window **Flags:** - `--to ` - Explicit exact Git identity receiving a legacy-store migration; it must match the active branch - `--approval-hash ` - Required hash copied from the preview; source bytes and identities must still match exactly **Behavior:** - Ensures the active git branch has a compiled KB under `.kb/branches//branch.json` - A missing exact branch store is compiled from the current checkout's tracked sources; no other branch store is copied - Branch names are never normalized; `master` and `main` are separate namespaces and remote-only refs do not keep stores live - `migrate` previews by default, stops an attached branch engine before applying, requires the exact target namespace to be absent, and preserves journals/audit/cache files. - `migrate` is an explicit old/new legacy-literal-path migration. It rejects inferred renames and arbitrary branch-store cloning. The old and new identities may be equal when moving a literal store for the current branch into its hashed path. - `recover` publishes only after a clean rebuild has succeeded, moves the prior store to `.kb/recovery//...`, and writes an audit record. It never renames a Git branch. **Detached HEAD:** when HEAD is detached but its commit is the tip of exactly one local branch (for example `git checkout ` of a branch tip, or a tool that detaches before running), Kibi attaches that branch's KB. With zero or several candidate branches (a CI checkout of a bare SHA, a bisect, a commit two branches share) Kibi guesses no branch identity: - Read-only operations (`search`, `query`, `status`, `check`, `coverage`, `graph`, and their CLI JSON routes and MCP tools) answer from a read-only snapshot compiled from the checkout's tracked sources into `.kb/branches/`. The snapshot is refreshed incrementally before each read, never touches a branch KB, and every answer carries a `detached_head_read_only` warning diagnostic naming the commit, the branches at HEAD, the store path, and `writes: "refused"`. - Writes (`upsert`, `delete`, `apply-plan`, `sync`, and other `kb-write` or `workspace-write` operations) are refused with the way out: check out a branch (`git switch ` or `git switch -c `) or set `KIBI_BRANCH`. `KIBI_BRANCH` still overrides the Git identity verbatim. `kibi gc` keeps the snapshot store while HEAD is detached on it and collects it afterwards. **Examples:** ```bash # Ensure the current branch has a KB kibi branch ensure # Preview then apply a legacy literal-store migration while on the target branch kibi branch migrate --from old-ref --to feature/target kibi branch migrate --from old-ref --to feature/target --apply --approval-hash # Preview then recover an unreadable store for the active exact branch kibi branch recover kibi branch recover --apply ``` ## `kibi deps lock|fetch|status` Manage KB dependencies: other repositories' knowledge bases this project reads, read-only, at pinned commits. Declare them in `.kb/dependencies.json`: ```json { "version": 1, "dependencies": { "billing-service": { "git": "git@example.com:acme/billing-service.git", "ref": "v3.2.0" }, "catalog": { "git": "https://example.com/acme/platform.git", "ref": "main", "directory": "services/catalog" } } } ``` `git` is any URL or path `git` can fetch; `ref` is a tag, branch or commit (the remote `HEAD` when absent); `directory` names the subdirectory that holds the Kibi workspace in a monorepo. Names use lowercase letters, digits, `.`, `_` and `-`. A `git` or `ref` value that starts with `-` or holds a control character is refused (`DEPENDENCIES_INVALID`), so it cannot reach git as an option. A dependency is pinned, not trusted: Kibi reads its `.kb/` sources and nothing else. The process that serves a dependency does not load the plugins its `package.json#kibi` names or its `.env.kibi` and `.env` files, and fetches run with git's `ext` transport disabled. - `kibi deps lock [names...]` resolves each ref to a commit, fetches it, checks that it holds a Kibi KB of schema 6 or newer, and writes `.kb/dependencies.lock.json`. Existing pins are kept, so a dependency only moves when you name it or pass `--update`. Commit both files. - `kibi deps fetch` fetches every pinned commit into the shared cache, for CI or before going offline. Reads fetch on first use otherwise. - `kibi deps status` lists each dependency with its pinned commit, KB schema and cache state (`not_locked`, `lock_stale`, `not_fetched`, `fetched`); it exits 1 when a dependency needs `kibi deps lock`. All three accept `--format json`. They need `git` on `PATH`. Git runs without a terminal prompt, so private repositories need credentials git already has (SSH keys, a credential helper or a CI token). Kibi reads the dependency's committed `.kb/` sources at the pinned commit; the dependency publishes nothing extra. Pin a tag whose commit already carries the KB you want to read: `kibi deps lock` checks that `.kb/manifest.json` exists and names a supported schema, but a KB with no entities yet locks and then answers every read with nothing. A good default is the release of the dependency your project actually uses, so the answers describe the code you run. Read a dependency with `--kb ` on `kibi search`, `kibi query`, `kibi status`, `kibi find-gaps`, `kibi coverage` and `kibi graph`, or with `kb` in their JSON route input: ```bash kibi search "how are refunds approved" --kb billing-service printf '%s\n' '{"query":"refund approval","kb":"billing-service"}' | kibi search --input - ``` The answer comes from the dependency's own KB at the pinned commit, compiled once into a read-only store inside its cached checkout on the first read (a few seconds for a large KB; later reads reuse it). The project's own `.kb/`, branch store, sync, check and hooks never read or write it. Writes are refused: write commands have no `--kb` option, and their JSON routes reject a `kb` field. Failures carry a `DEPENDENCY_*` code; the [error reference](error-reference.md#kb-dependency-errors-dependency_) lists them with their fixes. The cache lives in `$KIBI_DEPENDENCY_CACHE`, else `$XDG_CACHE_HOME/kibi/dependencies`, else `~/.cache/kibi/dependencies`, keyed by repository URL and commit, so projects pinning the same commit share it. ## `kibi skills` Manage and inspect bundled agent skills. Skills are reusable Markdown guidance packages shipped with Kibi. **Behavior:** - Lists available bundled skills - Loads a skill's manifest and body - Reads individual resources declared by a skill - Validates a local skill bundle directory **Subcommands:** ```bash kibi skills list [--format json|table] kibi skills load [--format json|markdown] kibi skills read [--format text|json] kibi skills validate [--format json|table] ``` **Arguments:** - `list` - Show all bundled skills with ID, name, version, and description - `load ` - Load a skill by its bundled ID. Returns the skill body and manifest. - `read ` - Read a specific resource file declared in the skill manifest - `validate ` - Validate a local skill bundle directory against the skill schema. The Kibi fields (`id`, `version`, `kibiCompatibility`, `tags`, `resources`) may sit at the top level of the front matter or under `metadata:`, as in the Claude Code and ZCode bundles; a top-level field wins. **Flags:** - `--format json|table` - Output format for `list` and `validate` (default: table) - `--format json|markdown` - Output format for `load` (default: markdown) - `--format text|json` - Output format for `read` (default: text) **Examples:** ```bash # List all bundled skills kibi skills list # Load the canonical usage skill as markdown kibi skills load kibi-usage --format markdown # Read a specific resource from a skill kibi skills read kibi-usage resources/fact-lanes.md --format text ``` **Notes:** - Skills are bundled with Kibi. Remote installation, marketplace, and script execution are not supported in v1. - OpenCode is an adapter for skill discovery, not the source of truth. The bundled skill set is authoritative. - Generic MCP/CLI agents should start with [generic-agent onboarding](generic-agent-onboarding.md) and load `kibi-usage`. Do not copy a long prompt as a substitute for skill discovery. - The JSON routes `skills-list`, `skills-load`, `skills-read`, and the consolidated `skill` route (`{"action":"list"|"load"|"read", ...}`) back the MCP `kb_skills` tool. ## Environment files Before a command runs, the CLI and the MCP server load the same env files. Non-empty process variables win; then the project file `/.env.kibi` (or the file `KIBI_ENV_FILE` names), then the user file `~/.config/kibi/env` (`$XDG_CONFIG_HOME/kibi/env`), then the legacy `/.env`, which only fills gaps. Blank values count as unset. The project and legacy files are workspace files: a cloned repository controls them. They may set provider secrets (any key outside the `KIBI_` namespace, such as `TYPESAFE_API_KEY`) and provider settings (`KIBI_JEV_*`). Kibi ignores every other key there: - any other `KIBI_*` key, including executable and module paths (`KIBI_NODE_PATH`, `KIBI_SWIPL`, `KIBI_KB_PL_PATH`, `KIBI__PATH`), runtime and log locations (`KIBI_RUNTIME_DIR`, diagnostic log paths), `KIBI_ENV_FILE`, workspace and branch selection (`KIBI_WORKSPACE`, `KIBI_PROJECT_ROOT`, `KIBI_ROOT`, `KIBI_BRANCH`, `KIBI_KB_DEPENDENCY`), proof commands (`KIBI_PROOF_*`) and safety switches such as `KIBI_CONFIRM_FIRM_EDITS`; - process variables: `PATH`, `HOME`, `USERPROFILE`, `TMPDIR`, `TMP`, `TEMP`, `SHELL`, `SWI_HOME_DIR`, `BASH_ENV`, `EDITOR` and the like, and the families `NODE_*`, `NPM_CONFIG_*`, `BUN_*`, `LD_*`, `DYLD_*`, `GIT_*`, `SSH_*`, `XDG_*`, `PYTHON*`, `SWIPL*`, `SSL_CERT_*`, `MALLOC_*` and the proxy variables (matched in any letter case). Each command prints the ignored key names once on stderr, never their values. Set those keys in the process environment or in the user file, which Kibi applies unfiltered. The policy is `isWorkspaceEnvKeyAllowed` in `packages/cli/src/env/workspace-env-policy.ts`. ## Workspace selection The CLI runs in the current directory. The MCP server answers from the workspace it started in and can route single calls elsewhere through `workspaceRoot` (see the [MCP reference](mcp-reference.md#workspace-routing)). These environment variables decide which workspace that is: | Variable | Effect | | --- | --- | | `KIBI_WORKSPACE`, `KIBI_PROJECT_ROOT`, `KIBI_ROOT` | Pin the workspace. The CLI and MCP server use it instead of the working directory, and a pinned MCP server does not route calls to other workspaces. | | `KIBI_MCP_ATTACH_ROOT` | Set by host launchers (Claude Code, Codex, Cursor, ZCode plugins) to the session's workspace; the launcher starts the MCP server there. It does not pin: per-call `workspaceRoot` routing to worktrees stays enabled. An operator-set `KIBI_WORKSPACE` still passes through and pins. | A detached HEAD whose commit is the tip of exactly one local branch attaches that branch's KB. Any other detached HEAD serves reads from a read-only snapshot of the checkout and refuses writes; see [`kibi branch`](#kibi-branch). ## Engine read limits All CLI and MCP clients of a workspace branch share one engine process with a single Prolog queue. A read can be bounded so a runaway query cannot hold that queue: | Variable | Effect | | --- | --- | | `KIBI_ENGINE_READ_TIME_LIMIT_MS` | Wall-clock budget, in milliseconds, for each read-only engine request (capped at 115000, below the engine's hard 120 s query timeout). | | `KIBI_ENGINE_READ_INFERENCE_LIMIT` | Logical-inference budget for each read-only engine request. | Both are unset by default (reads are unbounded, as before). Write requests, module loads, and `kibi sync` compilation are never bounded. The read-only queries a write operation such as `kibi upsert` runs before it writes are reads, so a write can fail with `QUERY_LIMIT_EXCEEDED` before anything is written. A read that reaches its limit is stopped inside Prolog and fails with error code `QUERY_LIMIT_EXCEEDED`; the envelope's `error.details.limitExceeded` is `{ "kind": "time" | "inferences", "limit": }`. It is never reported as an empty or partial answer. ## Staged Symbol Traceability `kibi check-generated --staged` compares the staged `.kb/symbols.yaml` bytes with the canonical layout a refresh writes, computed from the exact Git index, and fails when `.kb/symbol-coordinates.yaml` is in the index: coordinates are derived locally by every sync and never committed (schema 13; `kibi migrate` untracks the file). It also fails if the index changes while it runs. The command does not alter the index or working tree. Run `kibi sync --refresh-symbol-coordinates`, review the diff, then stage only the intended hunks (`git add -p`) before retrying. CI runs the full check before `prove --all`. The installed pre-commit hook uses `--changed-only` to skip the check when the staged change does not touch the symbol manifest. An initialized repository with no symbols has no coordinate artifact to refresh, so its first commit is allowed without that file. The `kibi check --staged` command inventories every staged path and enforces traceability on code before commit. **Purpose:** Every new or modified code symbol (function, class, method, accessor, behavioral class property, or module) must be explicitly linked to at least one requirement before it can be committed. This prevents "orphan" code from being merged and catches edits hidden behind broad class/module links when a narrower changed anchor exists. **How to link a symbol:** Model the code as a symbol in the manifest (`.kb/symbols.yaml`, written through `kb_upsert` or `kibi upsert`): `implements` to the requirement it implements for production code, or `executable_for` to a `TEST-*` entity for executable test code. Use `covered_by` to link symbols to the tests that exercise them. The canonical traceability chain is `REQ--` → `SCEN--` → `TEST--`. This satisfies the staged check without modifying source code. Physical symbol coordinates are derived separately into `.kb/symbol-coordinates.yaml` and refreshed via `kibi sync --refresh-symbol-coordinates` when code changes. Source comments are not a link: an inline `// implements REQ--` comment is ignored by every check, and only the symbol manifest counts. `kibi migrate` reports comments left from older versions as `review_inline_implements_comment` actions. **How to use:** ```bash # Check staged files for traceability coverage kibi check --staged ``` This command reads blob content from the Git index rather than the working tree. It reports any new or modified TypeScript/JavaScript symbols that do not have requirement links in the symbol manifest. It also reports `symbol-coverage` for changed symbols (the full-check rule), stale symbol-coordinate evidence and `symbol_granularity_violation` when a changed behavioral member such as `UploadPageComponent.processingProgressLabel` is covered only by a coarse class/module relationship without an audited `granularity_reason`. If violations are found and this is run as a pre-commit hook, the commit will be blocked. Readable UTF-8 files outside the TypeScript/JavaScript and Kibi metadata lanes receive advisory file-level checks. This includes Python, shell scripts, YAML and Compose files, Dockerfiles, Markdown, JSON, and other text formats. Kibi resolves ownership only from real source-linked symbol entities and typed `implements` relationships in committed knowledge plus the staged KB changes. Unstaged KB edits and unrelated staged entities do not satisfy the advisory check. Files under `.kb/` (the schema, manifest and entity files Kibi writes) need no requirement ownership. With a configured source analyzer (such as `kibi-plugin-treesitter`), a changed line belongs to the innermost declaration that contains it: an edit inside a method changes the method, not its class, and the class counts as changed only when a line of its own (its header, a field) changes. When the analysis is partial (a C/C++ `#include`, a Bash `source`, a PHP `require_once`, a Python decorator), the declarations the analyzer placed are still checked like fully analyzed ones; a staged line inside a gap and outside every placed declaration does not fail the check but is named for a file-level review. A result capped at the analyzer's symbol or diagnostic limit places no declaration, so its touched gaps are all reviewed at file level. Failed analysis, syntax errors and timeouts still fail the check. The text and JSON output include the complete path inventory, counts by analysis depth, and an explicit reason for skipped content. “No staged files found” is reserved for an empty Git index. Binary blobs, non-UTF-8 text, symlinks, and submodules are reported but do not block the commit. The staged CLI gate does not prove that linked prose still matches the source edit. Use an impact-enabled `kb_check` through MCP or CLI JSON mode while editing to get `symbol_semantic_review_needed` guidance and inspect linked requirements/scenarios/tests before deciding whether to update KB entities. Quality diagnostics may also appear during full or staged checks. They are designed to surface auditability problems automatically without creating a new command agents must remember: broad requirement reviews, multi-requirement symbol fanout, mixed-purpose class/component reviews, duplicate symbol-coordinate reviews, status misuse, strict-fact modeling gaps, and coverage-depth labels are review signals unless explicitly marked blocking. **Scope Note**: Staged symbol checks handle explicitly modeled symbols and extracted TypeScript/JavaScript anchors, including exported class methods, accessors, and behavior-bearing class properties. Other readable text currently receives file-level analysis. Automatic extraction of framework-specific `test()` or `it()` callbacks is not currently supported. **Analysis depth:** - Symbol-level: TypeScript and JavaScript (`.ts`, `.tsx`, `.js`, `.jsx`, `.mts`, `.cts`, `.mjs`, `.cjs`) - Metadata: Kibi entity Markdown, symbol manifests, coordinate manifests, relationship shards, and `.kb/manifest.json` - Advisory file-level: all other readable UTF-8 files - Explicitly skipped: binary blobs, unsupported encodings, symlinks, and submodules **CLI Flags for staged checking:** - `--staged` - Only check staged files - `--min-links ` - Minimum requirement links per symbol (default: 1) - `--kb-path ` - Path to KB directory - `--rules ` - Specific rules to run - `--dry-run` - Show what would be blocked without blocking commit **See also:** - [Troubleshooting](troubleshooting.md) - Hook repair and remediation - [AGENTS.md](../AGENTS.md) - Agent-specific workflows --- *For detailed system architecture, see [architecture.md](architecture.md)* *For entity and relationship schemas, see [entity-schema.md](entity-schema.md)* *For MCP server reference, see [mcp-reference.md](mcp-reference.md)* --- # MCP tools URL: https://getkibi.dev/reference/mcp.html > The canonical MCP tool catalog, onboarding contract, and schemas exposed by the Kibi MCP server. The Kibi Model Context Protocol (MCP) server is a peer public interface alongside the CLI's dedicated JSON routes. It serves MCP-capable agents over `stdio` and receives JSON-RPC 2.0 requests; operation schemas and executors are shared with the CLI. ## Public Tools The public MCP surface is intentionally curated. Agents can call exact lookup, discovery/reporting, mutation, and validation tools through MCP, with equivalent operation access through `kibi --input `. Every MCP tool also accepts `workspaceRoot`, the directory the call is about; see [Workspace Routing](#workspace-routing). Every session loads the tool list, so it is kept small: each input field is described in one line of at most 120 characters, and a choice among string constants is listed as an `enum`. A field whose rule needs more words keeps its full description in the operation catalog, which validates input on MCP and the CLI alike, and in the kibi-usage resource `operation-fields` (`kb_skills` with `action: "read"`, `id: "kibi-usage"`, `resource: "resources/operation-fields.md"`). ### Response envelope Every tool except `kb_job_status` returns `structuredContent` as a protocol 1 envelope: `{ kibiProtocol, operation, status, data, effects, diagnostics, nextActions }` (plus `error` on failure). The operation's result fields sit under `data`. Field paths written `structuredContent.` in this reference (`structuredContent.bindingHints`, `structuredContent.actions`, `structuredContent.relationshipPlan`, `structuredContent.receipt`, `structuredContent.warnings`, `structuredContent.violations[]`, `structuredContent.qualityDiagnostics[]`, ...) are shorthand for `structuredContent.data.`. The CLI JSON routes print the same envelope. A tool that rejects its input or fails with a Kibi error code (for example `VALIDATION_FAILED` for a `clauses` entry that is not a verbatim fragment) answers with `isError: true` and an error envelope: `status: "error"` and `error: { code, message, retryable }`, the same `error` the CLI JSON route prints for that input. The text content reads `Tool failed: [] `. A failure that carries no Kibi code is still raised as a tool error with the text `Tool failed: ` and no envelope. The discovery tools (`kb_query`, `kb_search`, `kb_status`, `kb_prepare_impact_review`) also put the `data` JSON in front of their text summary, for hosts that hide `structuredContent` from the agent: Gemini CLI and Cursor give the model the text content only. Claude Code shows `structuredContent`, and Codex gives the model the serialized `structuredContent` in place of the text whenever a result has it, so on those two hosts the text is the summary alone and each result is sent once. `KIBI_MCP_STRUCTURED_TEXT=omit` or `embed` overrides that choice for any host (see [Diagnostic usage log](#diagnostic-usage-log-opt-in)). ### Result size budget Every operation keeps its `data` within 24,000 characters, on MCP and on the CLI JSON route alike: both fit the result with the same function, so the same call carries the same data. Each catalog operation declares how it keeps to the budget: - **Rows**: `kb_query` (`entities`), `kb_search` (`results`), `kb_find_gaps` (`rows`), `kb_graph` (`nodes`, with the edges that leave the kept nodes) and `kb_sparql_remote` (`rows`) and `kb_prepare_impact_review` (`files`, with the requirements and review obligations of the kept files; `fileCount` and the record headers always describe the whole scope) return the rows that fit, and always at least one. A single row larger than the budget is cut: its largest parts are left out and named in `omittedFields`. - **Fitted**: `kb_coverage` and `kb_check` fit their own results (below). - **Bounded**: every other operation's result is bounded by its input, with the reason recorded in the declaration. A cut result says so: `data.truncated: true` and `data.truncation` (`budgetChars`, `returned`, and when known `total`, `omitted` and `nextOffset`, plus a `hint`), a `RESULT_TRUNCATED` info diagnostic, a text sentence such as `Result cut to its 24,000-character budget: 8 of 725 rows returned. Call again with offset 15 for the next rows.`, and a `nextActions` entry that repeats the call with that `offset`. A larger `limit` returns the same page; page with `offset` or narrow the filters. A list or report read whose data is still larger than 64,000 characters after its cut is refused with `RESULT_TOO_LARGE` (not retryable). An output that has no smaller form to ask for, such as `kb_status` or a skill, is sized by what the call asked about and is returned whole. A write has already committed, so its result is returned as it is. The `kibi coverage`, `kibi report`, `kibi signoff`, `kibi migrate` and `kibi query` commands print the whole report, since they do not hand it to an agent. ### Tool list The catalog has 19 tools, and a session lists all of them unless the `core` profile is chosen: - **full** (the default): all 19. - **core**: the seven tools of every change, `kb_search`, `kb_query`, `kb_record`, `kb_upsert`, `kb_check`, `kb_status` and `kb_skills`, plus `kb_review_firm_edit`, which records the firm-edit receipt that a blocking `kb_check` finding asks for. While the knowledge base holds no entity yet, `kb_plan_bootstrap` and `kb_apply_plan` are listed too. The `initialize` instructions name the tools left out; each of them runs through the project CLI with the same input (`npx --no-install kibi `, JSON routes with `--input -`). The profile comes from `kibi-mcp --tools `, else `KIBI_MCP_TOOLS` in the server environment, else the project's recorded choice (`"kibi": { "mcpTools": "core" }` in the root `package.json`, or `"mcpTools": "core"` in `.kb/setup.json` in a repository without one), else `full`. Claude Code and Codex load a tool's schema only when the agent first calls it, so the full list costs a name per tool there. On a host that loads every schema at the start, `core` saves about 32,000 characters per session, but an agent there needs the project CLI for the other operations. `kb_upsert` advertises the 15 fields that capture a requirement or decision and its reason (`title`, `status`, `priority`, `tags`, `links`, `text_ref`, `origin`, `semantic_text`, `rationale`, `firmness`, `approved_by`, `approval_ref`, `required_evidence`, `sourceFile`, `symbol_role`). Fact, symbol, test, proof and predicate fields stay valid input; the kibi-usage resource `operation-fields` (`kb_skills` with `action: "read"`) lists each one in full. Advertised schemas write a choice among strings as `enum` (in input and output schemas alike), which validates exactly what the equivalent `anyOf` of `const` branches would. `kb_check` advertises `rules` as plain strings rather than its long list of rule names; the server still checks every name and refuses an unknown one with `VALIDATION_FAILED`, listing the allowed names. | Area | Tools | |---|---| | Discovery and reporting | `kb_query`, `kb_search`, `kb_status`, `kb_find_gaps`, `kb_coverage`, `kb_graph` | | Skills | `kb_skills` | | Modeling (read-only) | `kb_model` | | Mutation and validation | `kb_record`, `kb_upsert` (also the `dryRun: true` preflight), `kb_delete`, `kb_check`, `kb_review_firm_edit`, `kb_ingest_proof` | | Planning and review | `kb_prepare_impact_review`, `kb_author_impact_review`, `kb_plan_bootstrap`, `kb_compile_intent`, `kb_apply_plan` | At [Kibi level](cli-reference.md#kibi-level) `remember` neither profile lists `kb_ingest_proof`, and the server instructions do not offer it through the CLI: that level asks for no proof. `kb_skills` with `action: list` leaves out `kibi-provable-code` there too; it still loads by id. At `remember` the `full` profile also lists only the knowledge tools: `kb_query`, `kb_search`, `kb_status`, `kb_skills`, `kb_graph`, `kb_model`, `kb_upsert`, `kb_record`, `kb_delete`, `kb_check`, `kb_review_firm_edit` and `kb_apply_plan`. It adds `kb_plan_bootstrap` and `kb_compile_intent` while the knowledge base is empty, and `kb_prepare_impact_review` and `kb_author_impact_review` while the project has an impact policy (`.kibi/impact-policy.json`). The server instructions name the other tools (`kb_find_gaps`, `kb_coverage` and the planning tools) as project CLI commands. The list is decided by the server, so it is the same in every host and for any MCP client. Two more tools are opt-in. Set `KIBI_MCP_OPTIONAL_TOOLS` in the server environment to a comma-separated list of names, or `all`; a tool named there is listed in either profile: - `kb_sparql_remote`: remote SPARQL `SELECT` queries ([below](#kb_sparql_remote)). - `kb_job_status`: polls `kb_check` and `kb_apply_plan` jobs started with `async: true` ([below](#kb_job_status)). Without it, both tools ignore `async: true` and run synchronously. ### Catalog operations, MCP calls, and CLI routes The shared operation catalog is larger than the MCP tool list. Narrow operations stay in the catalog and on the CLI; MCP reaches them through a consolidated tool so hosts load fewer tool definitions. Result payloads still name catalog operations, for example `recommended_tools: ["kb_model_requirement"]`, `suggested_next_tool`, `suggested_next_tools`, and repair-plan `workflowSteps`. Translate them with this table: | Catalog operation | MCP call | CLI route | |---|---|---| | `kb_skills_list` | `kb_skills` with `action: "list"` | `kibi skills list` / `skills-list`, or `kibi skill` with `"action":"list"` | | `kb_skills_load` | `kb_skills` with `action: "load"`, `id` | `kibi skills load` / `skills-load`, or `kibi skill` | | `kb_skills_read` | `kb_skills` with `action: "read"`, `id`, `resource` | `kibi skills read` / `skills-read`, or `kibi skill` | | `kb_semantic_advisor` | `kb_model` with `mode: "analyze"` | `kibi semantic-advisor`, or `kibi model` with `"mode":"analyze"` | | `kb_model_requirement` | `kb_model` with `mode: "requirement"` | `kibi model-requirement`, or `kibi model` | | `kb_suggest_predicates` | `kb_model` with `mode: "predicates"` | `kibi suggest-predicates`, or `kibi model` | | `kb_validate_upsert` | `kb_upsert` with `dryRun: true` | `kibi validate-upsert`, or `kibi upsert` with `"dryRun": true` | | `kb_sparql_remote` | `kb_sparql_remote` (opt-in) | `kibi sparql-remote` | | `kb_job_status` | `kb_job_status` (opt-in) | none: jobs live in the server process | Every other operation has an MCP tool and a CLI route of the same name (for example `kb_check` and `kibi check`). With diagnostic logging on, `.kb/usage.log` records a `kb_model` call under its routed operation (`mode: "predicates"` logs as `kb_suggest_predicates`) and a `kb_upsert` dry run as `kb_validate_upsert`. ### Host-visible tool names The canonical MCP names in this reference use the `kb_*` form. Some hosts display tools with the configured MCP server name prefixed. In OpenCode, the same tools commonly appear as `kibi_kb_search`, `kibi_kb_query`, `kibi_kb_upsert`, `kibi_kb_check`, and `kibi_kb_plan_bootstrap`. Use the host-visible prefixed name when an agent must reference an exact tool identifier; the semantics are identical to the canonical `kb_*` names documented here. ### Generic-agent onboarding For a copy-paste discovery snippet, see [generic-agent onboarding](generic-agent-onboarding.md). Bundled skills are the canonical agent-guidance source; do not copy a long operating manual into the agent. MCP-capable agents should use the standard `tools/list` capability discovery step, then follow Kibi's progressive-disclosure path instead of assuming that a package `skills/` directory is loaded by the host: 1. Call `kb_skills` with `action: "list"` to obtain the bundled skill manifests. 2. Call `kb_skills` with `action: "load"` and a returned `id`, normally `kibi-usage` for general Kibi workflow guidance. Load `kibi-bootstrap`, `kibi-freshness`, `kibi-traceability`, `kibi-decisions` (a stated rule, a firm-requirement edit or a conflict with a recorded rule), `kibi-commit-review` (a blocked commit or an impact review), or `kibi-provable-code` (designing code that implements a requirement, a refused source read, or generated code) when the task matches those workflows. 3. Call `kb_skills` with `action: "read"` only for resource paths declared by that manifest. These skill operations are local, read-only, and do not require Prolog. They return a human-readable `content` item plus structured data for clients that support structured tool results. The `kb_skills` registration advertises `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true`, and `openWorldHint: false` as client-facing behavior hints. Clients must treat annotations and skill text as untrusted guidance: authorization, schema validation, approval gates, and mutation sequencing remain enforced by the server and repository workflow. The CLI is a peer surface with the same skill operations through structured JSON routes (select by what the host exposes): ```bash printf '%s\n' '{}' | kibi skills-list --input - printf '%s\n' '{"id":"kibi-usage"}' | kibi skills-load --input - printf '%s\n' '{"id":"kibi-usage","resource":"resources/workflows.md"}' | kibi skills-read --input - printf '%s\n' '{"action":"load","id":"kibi-usage"}' | kibi skill --input - ``` If neither a visible Kibi MCP surface nor a trusted local CLI is available, the agent must stop and ask the operator to enable one; it must not infer availability from configuration files or read `.kb/` directly. Day-0 bootstrap uses the `kibi-bootstrap` bundled skill and `kb_plan_bootstrap`: inspect `kb_status.bootstrap`, follow its typed next action, interview the human about knowledge sources outside the code and pass them with cited `intentClaims` in `bootstrapContext`, review the deterministic `kibi.bootstrap-plan.v1`, ask only further questions returned by a `needs_context` result, get explicit approval for its hash, then pass the unchanged plan to `kb_apply_plan`. Hosts that support it also expose `/kibi-bootstrap`. ### `kb_plan_bootstrap` Discover existing repository evidence and return a deterministic, snapshot-bound `kibi.bootstrap-plan.v1`. Use this as the backend for the interactive `/kibi-bootstrap` onboarding workflow. It never mutates the KB. **Parameters:** - `includeGenericMarkdown` (optional): Include generic Markdown content as candidate evidence. Defaults to `true`, or to `false` when `bootstrapContext` declares `intentClaims` (a diagnostic says so); set it explicitly to override. - `minConfidence` (optional): Minimum confidence threshold for generated candidates. - `maxCandidates` (optional): Budget for candidates Kibi discovers itself (symbols, tests, repository documents), default 50. Declared `intentClaims` sit outside it: they are never capped and never use its slots, so a long claim list still leaves the full budget for discovered candidates. Candidates with a claim take the budget before provenance stubs (below), so raising it only admits more stubs once every candidate with a claim is planned. - `entityTypes` (optional): Limit generation to selected entity types. - `bootstrapContext` (optional): Declared project summary, source-of-truth paths/notes, priority roots, verification anchors, and the outcome of the source interview: - `knowledgeSources`: sources outside the code the human confirmed, each with `id`, `kind` (`issue_tracker`, `wiki`, `specification`, `design`, `decision_log`, `support`, `chat`, `repository_docs`, `other`), `title`, `locator`, `authority` (`authoritative`, `supporting`, `stale`), an optional `connector`, and an optional `component` its claims are about. - `intentClaims`: statements the agent read in those sources, each with `statement`, `sourceId`, an exact `reference` (ticket key, page URL, section), an `excerpt` (required for `intent` and `observation` claims, optional for `open_question`), an optional `kind`: `intent` (default, intended behavior), `observation` (how things are today, without stating intent) or `open_question` (something the sources leave undecided), an optional `component` that overrides the source's, and an optional `rationale` (the reason the source or the human gave; it becomes the requirement's `rationale` and its body's `## Context`). - `conflicts`: contradictions between declared claims that the agent leaves for the human, each with `claimReferences` (two to ten `{ sourceId, reference }` pairs that must match declared claims) and a one-sentence `note`. Kibi never contacts the declared sources. All three lists are part of `declaredContext` and so of `planHash`; `kind` is omitted there when it is `intent`. A grounded `intent` claim from an authoritative or supporting source becomes a `req` candidate with `sourceKind: intent_claim`, citation evidence, `text_ref: :`, `origin: {kind: import, ref: :}`, `firmness: firm` (normative lines from repository Markdown get the same with `ref: #L`) and a body that persists the claim (statement, then `## Source` with the blockquoted excerpt, source title and reference). Generated subject keys follow `component.aspect[.sub]`: the declared `component` (claim, then source; for repository Markdown, the file or directory name) is the first segment and the claim's subject the aspect; a one-word subject, or one equal to the component, makes the constrained property the aspect; an already dotted subject is kept. An aspect longer than four words or 40 characters is shortened deterministically to a noun phrase (the words before the first clause boundary such as `when`, `while`, `for`, `and`, without stop words; if still too long, its first and last content words), and a `subject-key-shortened:` diagnostic names the original and the chosen key so the operator can rename it. When shortening gives two different subjects the same key, the later one gets a third segment from its own wording (or a short digest) and a `subject-key-disambiguated:` diagnostic; claims about the same subject keep sharing one key, and the plan writes one subject fact for that key: every requirement about the subject links to it through `constrains`, the later sources' provenance is added to its tags and body, and a `subject-key-shared:` diagnostic names the key and its sources. A claim with no component and a multi-word subject is reported in `diagnostics` and becomes an authoring follow-up rather than a requirement with a malformed subject key. A claim the strict modeler cannot ground becomes an authoring follow-up. An `observation` or `open_question` claim never becomes a requirement: it becomes a `fact_kind: observation` candidate with the same citation evidence and `text_ref`, and open questions are tagged `review:open-question`. Each conflict becomes a `fact_kind: observation` candidate tagged `review:conflict` that cites every referenced claim; a conflict citing an undeclared claim is reported in `diagnostics` and not planned. These facts pass the same write validation as every other candidate. Stale sources produce no candidates, and claims citing an undeclared source are reported in `diagnostics`. When no sources were declared, a `needs_context` plan asks for them. On a repository that already has a seeded knowledge base (`activationState: root_active_seeded`, `activationMode: attached_seeded_handoff`), Kibi does not generate discovered candidates (repository documents, symbols, tests), but it still plans the declared claims. A claim whose entity is already in the KB is suppressed as `entity_exists` and counted as already in the KB; the rest become candidates exactly as on an unseeded KB. When the plan holds only claim-derived candidates, `applyBlocked` is `false`, the plan can be `ready` and `kb_apply_plan` applies it after approval; `handoffMessage` and `recommendedActions` say so. Without declared claims, or when none can be planned, a seeded KB stays a `handoff` plan whose `handoffMessage` points at `kb_search`/`kb_query` for existing knowledge and at `kb_compile_intent` for each remaining claim. A mode that plans no declared claims at all (`vendored_blocked`) keeps one `suppressed_by_activation` row per claim in `suppressedCandidates`. On any KB, an `intent` claim that restates a current requirement (status `open`, `in_progress` or `closed`, or legacy `active`/`approved`, and not superseded) is also suppressed as `entity_exists` and counted as already in the KB, even though its own derived `REQ-AUTO-…` id is new. A restatement is a normalized exact match: the claim's `statement` or `excerpt`, lowercased with punctuation and whitespace runs removed, equals the requirement's `title`, its `semantic_text`, or one sentence of it. The row adds `matchedId` (the requirement), `matchedBy: "restatement"` and `matchedField` (`title` or `semantic_text`). A claim that only comes close (normalized token-set Jaccard of 0.8 or more against the title, the semantic text or one of its sentences, the same threshold the entity-context check uses for a restatement) is still planned: its evidence gains `possible_restatement:` and a diagnostic names the requirement and the overlap, so the reviewer can drop the claim or link the two with `restates` or `supersedes`. Requirements are compared in id order, so the same KB and context give the same plan. A planned `intent` claim is checked for contradictions only against current requirements with a logical representation. For each planned claim, the plan names up to five current requirements on the same topic (intent-search score at least 0.1) that have none: the claim's `evidence` gains `review_against:` for each, and a `conflict-review:` diagnostic names the claim's citation and the requirements. Compare them before approval; on a contradiction show both to the human, then drop the claim or keep it and supersede the requirement after apply, and record a conflict the human has not decided as a `review:conflict` observation fact. An intent claim the plan cannot model ("Intent claim needs authoring …") is ranked the same way: its `conflict-review:` diagnostic names the prose-only requirements to compare it with when it is compiled with `kb_compile_intent`, which takes the verdicts through `conflictReviews`, and the knowledge-source summary and `recommendedActions` count the authoring claims that need such a review. Each `Knowledge source …` diagnostic counts a source's claims as planned, already in the KB, filtered out (`filtered_by_entity_type`, `below_min_confidence`) and not planned, and splits the not-planned count by its reason so the numbers add up: suppressed by the activation mode (compile them with `kb_compile_intent`), suppressed with a row in `suppressedCandidates` (for example `invalid_write`, `missing_excerpt`, `stale_knowledge_source`), left as a `sourceOnlySignals` authoring follow-up, or, when none of these applies, explained only in `diagnostics`. **Returns:** Evidence, bounded context questions, dependency-ordered actions, expected snapshots/source hashes, payoff summary, diagnostics, and `planHash`. Every suppressed candidate stays in `suppressedCandidates`; `tldr` and one diagnostic summarize them as a count per reason (for example `over_limit 290, duplicate_title 75`). A deterministic provider candidate whose source states no claim (`source_symbols` "Source module: …", `repo_metadata`, `repo_layout`, and `test_topology` without a recognized framework) is a **provenance stub**: it is written as `fact_kind: meta` tagged `bootstrap:provenance-stub` with a body that says so, not as an observation. A `test_topology` entry that names its framework states a claim and stays an observation. Stubs stay readable through `kb_query` (filter by the tag) but `kb_search` ranks them after every other match and drops them below the default threshold, the answer layer never lists them as notes, `kb_find_gaps` skips them unless `tags` names the tag (its `summary.provenanceStubs` counts the stubs that matched the filters either way), and `kb_coverage` `by: "type"` counts them in `summary.provenanceStubs` instead of the `fact` row. `discoverySummary.candidatesWithClaims`, `discoverySummary.provenanceStubs` and `discoverySummary.suppressedProvenanceStubs` report them apart from candidates with claims; each `over_limit` row carries `provenanceStub`, and the `over_limit` diagnostic and `tldr` say how many suppressed candidates are stubs so nobody raises `maxCandidates` for them. Each candidate's writes are validated before it is offered, with the same checks and semantic advisor the apply uses, so a conditional claim ("If microphone access fails, the editor must …") is planned like any other intent claim; a candidate that fails is suppressed as `invalid_write`, and one that would write an entity another candidate already writes with different content is suppressed as `duplicate_entity`. Only a `ready` plan may be approved. Apply it with `kb_apply_plan`; do not replay raw `kb_upsert` payloads. `pluginOffers` lists optional plugins that fit the workspace and that `package.json` neither activates in `kibi.plugins` nor lists in `kibi.declinedPlugins`; each has `package`, `capability`, the `mode` to activate it in, `reason`, `fileCount` and up to five `evidence` paths, and `recommendedActions` repeats it as a `plugin_offer` action. Kibi offers `kibi-plugin-ui` (`augment`) when production `*.tsx`, `*.jsx` or `*.component.ts` files exist. `kibi-plugin-search-hints` is never offered: it ships with Kibi and is on unless the project lists it in `kibi.declinedPlugins`. Offers are outside the plan and its hash; the agent asks the human, and Kibi never edits `package.json` itself. ## Repository Ignore Policy During read-only discovery (for example `kb_plan_bootstrap`) and other file-based inference, Kibi will exclude files and directories matched by the repository ignore policy: - repository root `.gitignore` files and nested `.gitignore` files in subdirectories - `.git/info/exclude` In addition to these repository-configured ignores, Kibi hard-denies a set of common tool/runtime directories that are never inspected for candidates: - `.sisyphus/**` - `.opencode/**` - `.kb/**` - `.git/**` - `node_modules/**` - `vendor/**` - `third_party/**` Notes and migration limitations: - Global Git excludes (for example `~/.config/git/ignore`) are not read or honored. - When MCP tools return a non-null migration warning, run `kibi migrate --dry-run`, then `kibi migrate --yes` before relying on strict checks or automated writes. - Symbol granularity migration marks existing coarse file/module links as `legacy-link`; new MCP `kb_upsert` calls must target the narrow behavioral symbol when one exists, or provide an explicit `granularity_reason`. Interfaces, type aliases, and enums are `type-shape` symbols and do not by themselves block a coarse behavioral link. When using discovery tools, agents and operators should assume that ignored paths are not considered as evidence for candidate entities and that any candidates requiring approval will come from non-ignored sources only. ## Semantic Modeling Quick Path When prose contains a machine-checkable rule, do not store it only in `text_ref` or freeform `links`. Use the concise decision tree in `docs/modeling-cheatsheet.md`. 1. Call `kb_model` with `mode: "analyze"` and the complete body when starting from raw prose, or run `kb_upsert` with `dryRun: true` before the real `kb_upsert` for new or updated normative requirements. Verify the returned atomic clause inventory; supply `clauses` when automatic decomposition is incomplete. 2. For property/value requirements, call `kb_model` with `mode: "requirement"` or create a `fact_kind: subject` fact plus a `fact_kind: property_value` fact. Link the requirement with `constrains` and `requires_property`. 3. Model every assertive proposition: use `kb_model` with `mode: "predicates"` for approved ground ontology claims, strict facts for scalar claims, and `kb_model` with `mode: "requirement"` and a validated `kibi.logic.v1` object for conditions, exceptions, modalities, quantifiers, cardinality, or bounded temporal rules. Preserve `claim_key` and `claim_text` on each ground fact/rule, replace stale manifests with the exact current assertive key set, persist the complete `semantic_inventory` plus its `inventory_contract`, and link with `requires_predicate`, `requires_property`, or `requires_rule`. Ambiguity, ontology gaps, and missing interpretations remain explicitly unresolved. 4. Use snake_case field names exactly as the MCP schema shows. `kb_upsert.properties` rejects camelCase aliases such as `subjectKey`, `propertyKey`, `predicateName`, and generic `value`. Semantic advisor modeling suggestions remain advisory and do not auto-create facts. The proposition ledger is a mutation contract for current requirements: the advisor canonicalizes repeated identical normalized claims to one proposition at the first source occurrence; `kb_upsert` (dry run or real) still rejects source/hash/span drift, duplicate identities in a submitted ledger, omitted assertions, invalid `nonlogical` classifications, and modeled entries whose linked fact claim keys do not match. Review every proposition and still run `kb_check`; successful ingestion proves accounting integrity, not domain truth or contradiction safety. ### `kb_model` Turn requirement prose into checkable structure without writing the KB. One tool covers three read-only modes, selected by the required `mode` field; the other fields are the inputs of the mode's catalog operation, and the result is that operation's payload plus `mode`. Apply any returned plan with sequential `kb_upsert` calls. | `mode` | Catalog operation | CLI route | Use it to | |---|---|---|---| | `analyze` | `kb_semantic_advisor` | `semantic-advisor` | Get the clause ledger, grounding, ambiguity, and modeling suggestions for prose. | | `requirement` | `kb_model_requirement` | `model-requirement` | Turn one claim (or a typed `logic` object) into a strict write set or rule plan. | | `predicates` | `kb_suggest_predicates` | `suggest-predicates` | Rank ontology predicate schemas and get a predicate-fact plan or ontology-gap observation. | `text` is required in every mode. A parameter that only another mode accepts is ignored and named in the result's `warnings` (and text content), with the equivalent parameter of the chosen mode when there is one (`subjectKey` in mode `requirement` is `subjectHint` in mode `predicates`). `kibi model --input -` accepts the same object on the CLI: ```bash printf '%s\n' '{"mode":"analyze","text":"Sessions expire after at most 30 minutes."}' | kibi model --input - ``` #### `mode: "requirement"` (`kb_model_requirement`) Model a normative requirement claim into a deterministic strict write-set or a validated `kibi.logic.v1` rule plan for contradiction-ready KB persistence. Accepts an LLM-supplied semantic claim (or a typed `logic` object) and returns a ready-to-apply sequence of `req`, `fact_kind: subject`, `fact_kind: property_value`, `rule_schema`, and `rule` entities with typed relationships. Raw Prolog is rejected. High-confidence scalar claims (≥ 0.7) produce a strict write-set: one `req`, one `fact_kind: subject`, one `fact_kind: property_value`, and two typed relationships. A valid `logic` input produces a `rule_schema`, a `rule` with canonical JSON/full hash/semantic key, and `requires_rule`. A conditional clause ("X may happen only when C", "X only if C", "X must not happen unless C") without explicit claim fields is modeled the same way: when C is one comparison on one subject property ("the cart total is positive"), Kibi builds a `forbid` rule on the action with C as its exception (confidence 0.8). A conditional it cannot translate (several conditions, pronouns, relations) returns no observation and no strict facts: the plan is empty, or with `requirementId` a requirement update that records the clause as `ontology_gap`, plus an `unresolved_conditional_clause` warning asking for a typed `logic` rule. Other low-confidence claims (< 0.7) produce a single `fact_kind: observation` artifact tagged `review:ontology-gap` that does not enter the contradiction lane and carries no claim key (it does not ground the clause), plus a warning explaining how to retry with explicit claim fields. **Parameters:** - `text` (required): One atomic plain-language normative clause to model. - `source` / `sourceFiles` (optional): Provenance used for stable IDs and references. - `confidence` (optional): Claim confidence; values below `0.70` produce observation review output. - `subjectKey`, `propertyKey`, `operator`, and `value` (optional as a complete set): Explicit semantic claim fields. When all are supplied, heuristic extraction is skipped. - `provenance` (optional): Exact source anchor for the clause. - `existingLogicClaims` (optional): Existing requirement claim keys. The returned req update merges the new key rather than replacing previously modeled clauses. - `requirementId` (optional): The requirement the plan updates. The strict write set uses this id for the `req` step and its `constrains`/`requires_property` links instead of minting `REQ-AUTO-`; fact ids, `subject_key` and the claim key stay derived from the claim. A typed `logic` rule attaches its `requires_rule` link to it, and an untranslatable conditional records its `ontology_gap` on it. - `logic` (optional): Typed `kibi.logic.v1` IR. Kibi validates range restriction, modalities, units, temporal bounds, closed-world negation, and resource-safe structure before returning a rule plan. **Returns:** A `writeSet` discriminated union: - `isStrict: true` — includes `req`, `subjectFact`, `propertyFact`, `relationships`, and an `applyPlan` ready for sequential `kb_upsert` calls. - `isStrict: false` — includes a single `observationFact` for non-normative or low-confidence input. Also returns the stable `claimKey`, merged `logicClaims`, and `migrationWarning` when the workspace KB schema is outdated. For strict claims, `vocabularyAlignment` reports how the clause subject was resolved against the existing KB vocabulary: - `subject.decision` is `reuse_existing` or `declare_new`, with `subject.candidates` ranked deterministically (IDF-weighted token overlap over subject keys, subject titles, and titles of requirements already constraining each subject; requirement-derived subjects are never offered). When reusing, the plan links the existing subject fact through `constrains` instead of creating a duplicate subject fact, and `writeSet.subjectFact` names that fact: its `id` and its `source` (`.kb/facts/.md`, the existing fact's own file). A heuristic subject converges onto the chosen existing subject; an explicitly provided `subjectKey` is kept, and a `subject_reuse_review` warning names the better existing subject when there is one. A declared new subject is tagged `vocabulary:new-subject`, and `subject_key_shape_review` fires when it is not dotted `component.aspect[.sub]`. - `redundancyCandidates` lists existing claims on the same subject whose wording may state the same obligation, and `reviewPlan` holds an optional `review:possible-duplicate` observation step to record that for review. These are candidates, never verdicts; exact duplicates are reported by the deterministic `domain-redundancy` check. - `stamps`, `fallbackUsed`, and `diagnostics` disclose the provider. The builtin provider is always available; an activated `kibi.vocabulary-alignment.v1` plugin (for example `kibi-plugin-jev`) may refine the decision in `replace`, `augment`, or `shadow` mode and falls back to builtin on any failure. The modeling call is read-only. Applying its plan is a separate mutation and must follow the caller's authorization boundary. The write-set is deterministic and idempotent—the same claim produces the same stable entity IDs. Apply authorized writes through sequential `kb_upsert` calls. #### `mode: "predicates"` (`kb_suggest_predicates`) Suggest ontology predicate candidates for a prose requirement before an agent writes freeform ontology notes. Agents should spell out the requirement claim, call this mode, then either apply a returned `fact_kind: predicate` plan linked with `requires_predicate`, supply exact `argumentBindings` when a fitting schema still has unbound arguments, or record the returned `review:ontology-gap` observation when no predicate fits. The gap observation is a review note, not a semantic claim: it quotes the claim in `claim_text` without a `claim_key`, carries `review:ontology-gap` and `needs_schema_extension` in `tags` (a tag is not an entity, so no relationship points at it), explains in `document.body` that no predicate schema fits, and stays queryable by tag without entering the contradiction lane. Apply it with `kb_upsert` exactly as returned. When a project-local schema declares `argument_constants`, bound values that are aliases are rewritten to their declared constant and any other undeclared value leaves that argument unbound, so the candidate lists the allowed constants instead of producing an applicable plan with a new atom. `kb_upsert` enforces the same vocabulary for predicate facts. The tool ranks project-local `fact_kind: predicate_schema` facts when available and falls back to Kibi's built-in predicate catalog covering state, transitions, guards, exceptions, mutual exclusion, dependencies, ownership, retry policies, escalation rules, availability SLAs, notification routing, idempotency, data residency, audit logging, consent, lifecycle actions, conflict resolution, fallback behavior, batch operations, consistency rules, build constraints, environment safety rules, schema invariants, coding standards, migration boundaries, absence/removal requirements, offline behavior, release gates, platform consistency, preservation rules, abstraction boundaries, security configuration, ordered strategies, refresh policies, scoped authorization, documentation standards, warmup policies, visual layout rules, enforcement-location rules, reconciliation rules, throttling policies, persistence/save/discard behavior, accessibility, retention, resource constraints, feature gates, events, permissions, defaults, uniqueness, state memberships, temporal ordering, conditional behavior, rate limits, acceptance outcomes, reusable launcher contracts (`dependency_resolution_policy`, `ordered_resolution_strategy`, `resolution_failure_policy`, `process_delegation_contract`, and `failure_behavior`), plus consumer-escalated families for fail-closed authorization, deployment preconditions, data-migration sequencing, diagnostic visibility, mutation authority, request deduplication, async boundaries, canonical identifiers, responsive breakpoints, and operational pauses. Built-in candidates include usage hints (`use_when` / `do_not_use_when`) so agents can choose precise predicates instead of matching keywords blindly. Candidate diagnostics are additive: each candidate may report `eligibility` (`eligible` or `rejected`), `rejection_reasons`, a conservative aggregate `binding_provenance` (the least-reviewable provenance across arguments), per-argument `binding_provenance_by_argument` (`explicit`, `extracted`, `inferred`, or `placeholder`), `applicability_score`, and deterministic score components. Retrieval and argument binding do not by themselves make a candidate applicable; negative evidence and margin-based abstention can reject weak or near-tied candidates. When no schema is genuinely eligible, the response uses `record_ontology_gap` and includes a non-null `recommendedPredicateSchema` draft with proposed name, ordered arguments, extracted bindings, unresolved bindings, rationale, and reuse scope for review. Draft schemas are never applied automatically. **Parameters:** - `text` (required): Prose requirement or claim to classify into ontology predicates. - `requirementId` (optional): Existing requirement ID. When present, the response includes a `relationshipPlan` describing the `requires_predicate` link to attach after preserving existing requirement metadata. - `source` (optional): Provenance/text reference for generated predicate facts or ontology-gap observations. - `subjectHint` (optional): Canonical subject key the predicate is about. It binds the argument the schema names `subject`, wherever that argument sits; for a schema without a `subject` argument it becomes the planned fact's `subject_key`. Without it, a `requirementId` whose requirement `constrains` exactly one subject fact binds that fact's `subject_key` the same way (provenance `requirement`); with several subject facts their keys are listed first in the subject's `bindingHints[].examples`. A requirement without a subject fact leaves `subject` unbound; only free text without `requirementId` falls back to keyword guesses. For a requirement that is not written yet or constrains nothing, an explicit `subjectHint` is the planned subject: the candidate's `subject_key` is set from it and `subject_pairing` is computed against it, so the planned fact pairs with the subject fact once the requirement `constrains` it. The parameter is `subjectHint`, not `subjectKey` (a `mode: "requirement"` parameter): a parameter that belongs to another `kb_model` mode is ignored and named in `warnings` (`subjectKey is a mode: requirement argument; mode: predicates ignored it. Use subjectHint in mode: predicates.`). - `maxCandidates` (optional): Maximum ranked predicate candidates to return. - `minScore` (optional): Minimum candidate score; higher values make ontology-gap fallback more likely. - `includeExistingSchemas` (optional): Include project-local predicate schema facts alongside built-ins. - `schemaId` (optional): Select an exact reviewed built-in or project-local schema ID instead of accepting lexical rank order. An unavailable ID returns `resolve_schema_reference` with no write or ontology-gap plan. - `argumentBindings` (optional): Exact values keyed by the candidate schema's ordered `argument_names`, taken from the claim text. Use this to resolve an incomplete candidate; unbound values are never emitted as an applicable predicate fact. A value that only repeats its own or another argument name (after snake-case normalization, for example `before_event: "before_event"`) unless the claim itself names it, or a bare stop word or trivial verb (`be`, `is`, `do`, `have`, `the`, `a`, ...), counts as a placeholder and leaves the argument unbound. `true`, `false` and the schema's declared `argument_constants` are always accepted. - `polarityHint` (optional): Reviewed `assert` or `deny` override for negation-scope false positives. Use only after reviewing the complete claim and selected schema. - `existingLogicClaims` (optional): Existing requirement claim keys. Returned relationship guidance merges the new key rather than replacing earlier clauses. **Returns:** - `candidates`: Ranked predicate suggestions with schema signature, usage hints, ordered `predicate_args`, `binding_status`, `unbound_arguments`, `canonical_key`, score, and rationale. With a `requirementId` that constrains subject facts (or, when nothing is constrained yet, an explicit `subjectHint`), `subject_key` is the subject the predicate is about (the value of its `subject` argument, or for a schema without one such as `permission_rule(actor, action, resource, decision)` the requirement's subject) and `subject_pairing` says whether that is one of the constrained subjects (`paired`, `unpaired`, or `not_required` when the requirement constrains none). An `unpaired` candidate is incomplete: its `unbound_arguments` include `subject` (or `subject_key` for a schema without a `subject` argument), because `kb_check` would keep reporting `strict-req-fact-pairing` after the link. The planned predicate fact records `subject_key` whenever it is known, so the strict lane pairs it with the subject fact whatever argument holds the subject. A value for an entity-, actor- or resource-like argument taken from the claim text that is longer than three words (a clause such as everything before the modal verb) is not a binding: it stays unbound with a `bindingHints` reason; short nouns still bind. - `recommendedAction`: names the predicate state whether or not the claim is already grounded. `apply_requires_predicate` when the top or explicitly selected candidate fits, every argument is bound, the predicate pairs with the requirement's subject (see `subject_pairing`) and the claim is not yet grounded; `replace_grounding` when such a candidate fits but `requirementId` already grounds this claim (same `claim_key`) through `requires_property`, `requires_predicate` or `requires_rule`; `keep_existing_grounding` when `requirementId` already links a predicate fact with the recommended candidate's `canonical_key` (the same predicate tuple stated in other words, or the same claim again; the candidate's decision may still be inferred): nothing is written or swapped, and `existingGrounding[].matchedBy` says whether the fact matched by `claim_key` or `canonical_key`; `extend_requirement` when such a candidate fits and the claim is not grounded, but the stored requirement's proposition ledger (`semantic_inventory`) has no entry for this text: a requirement grounds only the propositions its prose states, so no fact is planned (it would stay unlinked) and the prose has to be extended with the clause (kb_model `mode: "requirement"`, or `kb_upsert` with the extended `semantic_text` and the ledger `mode: "analyze"` returns) before `mode: "predicates"` is called again; `provide_argument_bindings` when its schema fits but exact values are missing or the predicate is not about a subject the requirement constrains (the summary, `candidates[].unbound_arguments` and `bindingHints` list them, and a warning says when the schema does not name the requirement's subject); `resolve_schema_reference` when an explicitly selected schema is unavailable; `review_nonlogical` when the semantic advisor classifies the input as nonlogical (rationale, example, or subjective context); otherwise `record_ontology_gap`. `record_ontology_gap` is also returned when the top candidate is incomplete solely because the claim names no participant for its `actor`, `actor_scope`, `role` or `owner` argument (the value is empty, the requirement's subject key or a clause of the claim that opens with a gerund such as "Discarding a draft while …", and none of the argument's declared constants or schema example values occurs in the claim text): such a schema does not fit the claim, so the `review:ontology-gap` observation is planned in `applyPlan`, while the candidate stays in `candidates` as `incomplete` and `bindingHints` still explains the unbound argument. A claim that names a participant in other words, or an argument unbound for another reason (a value outside `allowedValues`, a value the claim does not contain), keeps `provide_argument_bindings`. A non-empty `existingGrounding` is the "already grounded" signal and lists the links found (`matchedBy`, the fact's stored `claimKey` and `canonicalKey`). When no hash-bound `plan` was compiled (the ledger lacks the claim, the requirement is not stored, or the call passed no `requirementId`), `decisionConflicts` lists the stored decision facts of current requirements that agree with the complete candidate on its key arguments and decide the opposite (`requirementId`, `factId`, `effect`, `proposedEffect`, `canonicalKey`), and a warning names each one; with a `plan`, its `contradictionAnalysis` carries the same information and `decisionConflicts` is empty. An already grounded claim never gets a predicate `applyPlan` or `relationshipPlan`, because a modeled claim takes exactly one grounding relationship and a second link fails the proposition-complete rule; on `replace_grounding`, `replacementPlan` gives the ordered swap (upsert the predicate fact, `kb_delete` the old grounding relationship, then upsert the requirement with the `requires_predicate` link) and `relationshipTarget` names the planned fact. Each step's `input` is a complete payload to apply unchanged: the requirement step restates the stored `title`, `status`, `priority` and `tags` (kb_upsert keeps the stored proposition ledger). The order is forced and the steps must run back to back: linking `requires_predicate` before the retraction is rejected because the claim would have two groundings, and between the retraction and the link the claim is ungrounded, so a `kb_check` in between reports `logic-coverage` for the requirement. If the last step fails, apply `replacementPlan.rollback`, which restores the retracted link. On `record_ontology_gap` the `review:ontology-gap` observation plan and `recommendedPredicateSchema` are returned even for a grounded claim, since the observation is not a grounding relationship. - `structuredContent.actions`: A ready-to-apply `kb_upsert` payload for a completely bound top predicate fact, an empty list for an incomplete binding, or an explicit `fact_kind: observation` tagged `review:ontology-gap` and `needs_schema_extension`, with `claim_text`, `value_string`, `text_ref` (when `source` is given), a `document.body` and no relationships. - `structuredContent.bindingHints`: On `provide_argument_bindings`, one entry per unbound argument of the recommended candidate: `argument`, `position`, `type` (from `argument_types`), `description` when the schema has one, `allowedValues` (the declared `argument_constants`) when the vocabulary is closed, `examples` (for `subject`, and for an `entity` argument of a schema without one, the requirement's constrained subject keys first; then constants, then the values at that position in the schema's `examples`; a `subject_key` hint, `position` -1, lists the constrained subject keys to pass as `subjectHint`), the rejected `currentValue` with its `provenance`, and a `reason`. A participant argument (`actor`, `actor_scope`, `role`, `owner`) is never offered the subject keys: the subject is what the claim is about, not who acts on it, and the planned fact already carries it as `subject_key`. An explicit binding of such an argument to a constrained subject key stays unbound (`placeholder`) with a reason, so the candidate cannot become `complete` through a vacuous actor; when the claim names no participant, the hint says so and points to `record_ontology_gap`, because a schema whose actor the claim never names does not fit the claim. Bind from the claim text using these instead of copying field names. Also returned on a `record_ontology_gap` that was decided for a matched but unfitting candidate; empty for every other action. Built-in schemas close the arguments with a natural vocabulary: `trigger` of `commit_action`, `discard_action` and `transition` (`escape`, `cancel`, `submit`, `navigation`, `click`, `timeout`), `decision` of `permission_rule` and `scoped_authorization_rule` (`allow`, `deny`), `policy` of `refresh_policy_rule` (`automatic`, `manual`, `on_demand`), `decision` of `environment_safety_rule` (`allowed`, `forbidden`, `read-only`), `operator` of `resource_constraint`, `unit` of `retention_policy` (`days`, `months`, `years`), `action` of `coding_standard_rule` (`use`, `avoid`) and of `lifecycle_rule` (`archived`, `deleted`, `expired`). A claim that names a constant in other words (`times out`, `must be denied`) binds it, and aliases such as `navigate` converge onto the constant. - `structuredContent.replacementPlan`: On `replace_grounding`, the ordered `steps` (write the predicate fact, `kb_delete` the old grounding link, upsert the requirement with `requires_predicate`), a `rollback` upsert that restores the old link, `instructions`, and `expected`: `kbCheckAfterStep` lists the `kb_check` findings for the requirement after each step by rule name (`[[], ["logic-coverage", "strict-req-fact-pairing"], []]`: between the retraction and the link the claim is ungrounded and its subject fact unpaired, so both rules fire), `kbCheckAfterLastStep` is `[]`, and `rollbackWhen` is "kb_check after the last step is not clean". Violations carry the rule as `rule`, quality diagnostics as `rule.`. - `structuredContent.relationshipPlan`: When `requirementId` is supplied and a predicate fits, the req -> fact `requires_predicate` link plus the merged `logicClaims` manifest to apply after querying/preserving the existing requirement entity. This is separate from `applyPlan` so the tool never emits a foreign-source relationship that `kb_upsert` would reject. `structuredContent.relationshipTarget` names the planned predicate fact id (`FACT-PRED-…`) that the `requires_predicate` link must target; `candidates[].id` (`SUGGEST-…`) values are never relationship targets. - `structuredContent.plan`: When `requirementId` is supplied, the candidate is complete and the claim is not yet grounded, the hash-bound `kibi.compile-plan.v1` behind `applyPlan` and `relationshipPlan`: step 1 writes the predicate fact, step 2 upserts the requirement with its stored title, status, priority, owner and tags, the merged `logic_claims` manifest and the `requires_predicate` link. Apply it with `kb_apply_plan` (`approvedPlanHash: plan.planHash`): both steps are validated together and committed in one transaction, and the requirement's authored body is kept. `plan.contradictionAnalysis` is the what-if over the current KB plus these steps, so a decision conflict with a permission fact that is already stored (an allow and a deny on the same key) is reported here before any write; the plan is then `blocked`, a warning names the witnesses, and `applyPlan` still shows the fact. `null` when no plan applies (incomplete binding, already grounded, no `requirementId`, or the requirement is not stored; a warning says why) and for ontology-gap observations, which `kb_upsert` applies as before. **Example:** ```json { "mode": "predicates", "text": "When the user navigates away with unsaved annotation edits, the editor must auto-save the draft and return to idle mode.", "requirementId": "REQ-EDITOR-004", "source": "requirements/editor.md#L12", "subjectHint": "editor.annotation" } ``` #### `mode: "analyze"` (`kb_semantic_advisor`) Analyze requirement prose without mutating the KB. Use this before constructing a `kb_upsert` payload when you have raw requirement text and want modeling suggestions. **Parameters:** - `text` (required): Requirement prose to inspect. - `type` (optional): Entity type context. Currently `req` is supported. - `id` (optional): Requirement ID used for draft relationship guidance. - `title` (optional): Requirement title for draft apply plans. - `source` (optional): Provenance for draft suggestions. - `status` (optional): Requirement status for draft suggestions. - `clauses` (optional): Caller-reviewed atomic proposition split. Use it when a sentence contains multiple obligations, conditions, exceptions, definitions, or qualifiers. Each clause must be a verbatim fragment of `text` (whitespace layout, a leading list marker and closing punctuation may differ); a clause that does not occur in `text`, such as a paraphrase, fails the call with `VALIDATION_FAILED` naming the clause. - `interpretations` (optional, maximum 3): Typed `kibi.logic.v1` alternatives with `claim_key`, `claim_text`, and `ir`. Kibi canonicalizes and structurally compares them; materially different valid alternatives remain unresolved and confidence never selects one. **Returns:** - `structuredContent.receipt`: Semantic advisor receipt with detected signals, a proposition ledger (`propositions[]`), a versioned `inventory_contract` containing the semantic source field and SHA-256 hash, typed interpretation results, deterministic shadow cues, modeling suggestions, candidate lane, payload hash, and suggested next tools. - `structuredContent.warnings`: Non-blocking warning strings explaining why the prose is not yet contradiction-checkable. The receipt returns stable provenance `claim_key` values, `claim_text`, exact UTF-8 byte spans, per-clause suggestion indexes, and a `logic_coverage` manifest comparison. Proposition statuses are `modeled`, `ambiguous`, `ontology_gap`, `nonlogical`, or `missing`; an assertive span is never silently dropped. Observation apply plans carry their review category in `tags` (for example `review:ambiguity` or `review:ontology-gap`; a tag is not an entity, so no relationship points at it) and a `document.body` that quotes the prose, so `kb_upsert` accepts them as returned; they remain outside contradiction checks. Suggestion kinds include `strict_property`, `predicate`, `rule`, `ambiguity_observation`, and `ontology_gap`. Supported deterministic suggestions include multi-claim prose, cardinality, thresholds with units, retention/expiry durations, booleans, enum sets, permissions and prohibitions, defaults, uniqueness constraints, state memberships, state transitions, exception rules, mutual exclusion, dependency rules, ownership, retry policies, escalation, availability SLAs, notification routing, idempotency, data residency, audit logging, consent, lifecycle, conflict-resolution, fallback/degradation, batch constraints, cross-entity consistency, conditional behavior, temporal ordering, comparative numeric constraints, rate limits, and ambiguity observations. For exact predicate suggestions, the receipt `candidate_lane` and `suggested_next_tools` follow the generated suggestion rather than the weaker signal heuristic. For example, a lifecycle rule containing a number still routes to `kb_suggest_predicates` (`kb_model` mode `predicates`), not `kb_model_requirement` (mode `requirement`), when the advisor can ground it as a predicate fact. These receipt fields name catalog operations; see [the mapping table](#catalog-operations-mcp-calls-and-cli-routes). ### `kb_query` Retrieve entities by `type`, `id`, `tags`, or `sourceFile`, or ask typed questions about modeled facts. Supports limit and offset pagination. **Entity filters:** - `type` (optional): Entity type (`req`, `scenario`, `test`, `adr`, `flag`, `event`, `symbol`, `fact`) - `id` (optional): Entity ID (exact match) - `tags` (optional): Tag list for filtering - `sourceFile` (optional): Source-file substring filter - `limit` (optional): Maximum number of results - `offset` (optional): Number of results to skip - `fields` (optional, default `summary`): without `id`, rows carry the summary fields (id, type, title, status, source and the like, plus `firmness`); `full` returns every front matter field. A query with `id` always returns the full entity. - `includeBody` (optional, default `false`): with `id` only, also return the entity's authored Markdown body **Returns:** Array of matching entities (`entities`) with deterministic ordering and the total `count`, cut to the [result size budget](#result-size-budget). Entity rows carry front matter only. With `includeBody: true` the answer adds `body: { id, path, text }`: the prose after the front matter of the entity's authored document, so an agent can see and correct a statement the body makes that the fields do not; `kb_upsert` `document.body` replaces it. `text` is `null` when the entity has no authored Markdown document inside the workspace (a symbol, for example), and a body longer than 32 000 characters is cut with `truncated: true`. `includeBody` without `id` is refused. An `id` lookup that finds the entity without `includeBody: true` ends its text with a one-line hint to pass it. **Example:** ```json { "type": "req", "sourceFile": "src/auth/login.ts", "limit": 20 } ``` **Typed fact questions:** instead of searching prose, ask the KB about the facts it models. These filters apply to `fact` entities only and cannot be combined with `id`, `tags` or `sourceFile`. - `factKind`: list facts of one kind (`subject`, `property_value`, `predicate`, `predicate_schema`, `observation`, `meta`, `rule`, `rule_schema`) with their typed fields. `factKind: "predicate_schema"` is the catalog of askable predicates: each row names the predicate, its argument names and types, declared `argumentConstants`, key arguments, examples and how many facts use it. Every row carries `id`, `builtin` and `stored`: a project schema is a stored entity (`builtin: false`, `stored: true`, its `id` answers `kb_query({ "id": ... })`); a built-in decision predicate such as `permission_rule(actor, action, resource, decision)` appears with `builtin: true`, `stored: false` and the catalog `id` that `kb_model` accepts as `schemaId` (`FACT-SCHEMA-PERMISSION-RULE`), which no stored entity carries, so a `kb_query` by that id returns nothing. - `predicate` (+ optional `namespace`): every stored fact of that predicate. Narrow it with `where`, an order-free object of argument name to value resolved through the schema (`{"actor": "admin", "decision": "allow"}`), or with positional `args` where `null` matches anything. `polarity` keeps `assert` or `deny` facts, `scope: "current_requirements"` keeps only facts a current requirement requires, and `distinct` names an argument whose distinct values are counted. Rows carry `arguments` (named), `polarity`, the effective `effect` (`allow`/`deny`) for decision predicates, the `canonicalKey`, `claimText` and the requirements that require the fact with their current/superseded status. - `subjectKey` (+ optional `propertyKey`): the strict property facts stated about a subject, each with `operator`, `valueType`, `value`, `unit` and the requirements that require it; `subjectFacts` names the subject fact itself. `where`, `args`, `polarity`, `distinct`, `namespace` and `propertyKey` refine one of those three questions and are refused with a message when sent without one or with the wrong one, and `kb_query` rejects positional `args` that do not cover the predicate's full arity. Every typed answer returns the rows in `entities` plus `factQuery`: the `mode`, the question as understood, the `schema` used, `distinct` counts, `suggestions` (when nothing matched a `where`, the values that do exist per bound argument), `warnings` (an argument name the schema does not declare, with the declared names) and `next`, the exact follow-up `kb_query` calls that make sense, so the agent never has to guess the next step. ```json { "predicate": "has_role", "where": { "user": "alice" }, "distinct": "role" } ``` answers "how many roles does alice have?" with the facts and `factQuery.distinct.values`; ```json { "predicate": "permission_rule", "where": { "actor": "admin" } } ``` answers "what may an admin do?" with each rule's `effect`; ```json { "subjectKey": "user.role_assignment", "propertyKey": "max_roles" } ``` answers "what is the role limit?" with the operator and value. Start from `{ "factKind": "predicate_schema" }` when you do not know the predicate names. `kb_search` answers already point here: each linked fact in the answer layer carries its typed `claim` (`has_role(alice, admin)`, `user.role_assignment max_roles lte 2`) and, when the search sets `fields: "full"`, the `ask` call that reproduces the fact's own tuple: `{ "subjectKey", "propertyKey" }` for a property fact, `{ "subjectKey" }` for a subject, and for a predicate fact the predicate (with its `namespace` when it is not `default`) plus `where` over its key arguments when a project `predicate_schema` or the built-in signature declares them (the schema's `key_arguments`, else the argument named `subject`, else the first argument: `{ "predicate": "has_role", "where": { "user": "alice" } }`, `{ "predicate": "permission_rule", "where": { "actor": "admin", "action": "read", "resource": "analysis_request" } }`), otherwise its full positional `args`. Pasted, the call returns that fact and only the facts sharing those key arguments. ### `kb_search` Ask the KB a question or search it. The default `intent-v1` ranking accepts natural-language questions ("what governs checkout rounding?"), deterministic host-agent facets, and changed-code source locations. Without a `type`, or with `type` `req` or `adr`, it ranks decisions (requirements and ADRs): each decision is credited with the words of the facts it links and of the symbols that implement it, scored with BM25 over its title, statement and those words, and given a scope first: **in** this workspace when it is linked to a file that exists here or comes from a knowledge source with at least two decisions linked here, **in another scope** when it is linked only to files that do not exist here (counted in `queryAnalysis.otherScopes`, never shown as a card), **distant** when it comes from a knowledge source of at least three decisions none of which is linked here (half its score) and **unscoped** otherwise (85% of its score). Superseded and deprecated decisions rank at half their score and closed ones at three quarters, below a current decision that matches as well. A superseded decision is folded into the current end of its chain, and a decision whose title shares at least 80% of its words with a higher-ranked one is folded into it unless either is firm or only one is negated; a folded decision stays listed on its card. With a scenario, test, fact or symbol `type`, the same mode ranks rows of that type with facets, source evidence, graph boosts and abstention below `minScore`. Set `rankingMode: "legacy"` for the older lexical ranking. **Parameters:** - `query` (required): Free-text query. `question` is accepted in its place when `query` is absent; it is not listed in the advertised schema. - `type` (optional): Entity type filter - `limit` (optional, default `5` decision cards, or `10` rows of another type): Maximum number of ranked results per page; `count` and `truncated` say when to page with `offset` or raise it - `offset` (optional): Number of results to skip - `rankingMode` (optional): `intent-v1` (default) or `legacy` - `answer` (optional, default `true`): Intent mode, first page only. Adds the answer layer described below. - `hints` (optional, default `true`): Intent mode over decisions. Fuses the meaning ranking of a `kibi.search-hints.v1` provider (the bundled search hints plugin is on by default) and, on the first page, lists decisions related by meaning in `queryAnalysis.hints`, described below. `false` ranks by words alone. - `semanticFacets` (optional): Host-provided `actors`, `actions`, `objects`, `constraints`, or `aliases` arrays - `sourceLocations` (optional): Workspace-relative `{path, line?, column?, symbol?}` locations for changed code. The symbols at those locations match, and so do the requirements they `implements`, even when the question shares no word with them (their `sourceMatches` name the implementing symbol with `distance: 3` and the reason `implemented at the source location`). - `minScore` (optional): Intent acceptance threshold between `0` and `1` for scenario, test, fact or symbol rows; defaults to `0.18` - `fields` (optional): `summary` (default) or `full` **Returns:** Ranked results. `count` is the number of matches in the whole ranking, before `limit` and `offset`; `returned` is the number of rows on this page; `truncated` says whether more pages remain. A decision search returns decision cards. Each row carries its `entity` (`id`, `type`, `title`, `status`, and `firmness: "firm"` for a firm decision), `score`, `reasons` (the card's evidence, such as `linked to ` or `owns `), `line` (the card as one line of at most 300 characters: id, firmness, title, statement and strongest evidence, plus `+N similar` for folded decisions), `scope` (`in`, `unscoped` or `distant`) and, when decisions were folded into it, `folded`. The text answer is the card lines. A card whose statement the `answer` already quotes carries only its `entity` `id`, `type` and `title`, its `score` and its `reasons`; `fields: "full"` returns every card with its whole entity. `queryAnalysis` has `rankingMode`, `unit: "decision"`, `decisionCount`, `fused` (whether a meaning ranking was fused in), `weak`, `abstained` (no decision shares a word of the question), `coverage` (the share of the question's weight the best card covers), `uncoveredTerms` (the question's words no returned card contains) and `otherScopes` (`count` and the leading `ids`). An answer none of whose cards covers at least half of the question's weight is weak: it names no governing requirement, keeps the cards as the nearest decisions, and carries `notes` saying the missing match is not evidence that nothing governs the question. A decision folded into a card governs only when its own words cover half the question too. Rows of another type carry identifying metadata only, `id`, `type`, `title`, `status`, `priority`, `tags`, `source`, and `updated_at`, alongside their `score`, `reasons`, `snippet` and `evidence` for matched facets, source locations, and normalized score; with `fields: "full"` it also lists `graphPaths`. Their `queryAnalysis` has candidate/accepted counts, top score, `topTwoMargin`, `topRivalMargin`, ranking mode, `abstained` and `ambiguous`. `ambiguous` reads `topRivalMargin`: the margin between the top match and the best match it is not linked to in the traceability graph. A **negative-path fact** (a fact that a scenario expecting `rejection` or `error` assumes and on which no requirement grounds a claim) describes a situation that must not happen; its row carries `negativePath` (`polarity: "forbidden"` and `guards`), the text names it as a forbidden situation, and it ranks directly below a requirement it guards that matched as well. An abstention's text says to ask again in the words and language the KB is written in. In both modes a code identifier in the question is read word by word (`canExport` as `can export`), and a path the call also passes in `sourceLocations` is dropped from the question's words. A question about contradictions or conflicts also gets a text pointer to `kb_check` with `domain-contradictions` (stored requirements) and to `kb_model` mode `predicates` or a `kb_upsert` dryRun (a proposed rule). Every response carries `branch`, the Kibi branch whose store was searched (`null` when the runtime attached none), whatever the result count. When that store was never compiled for the branch (a new branch created without the `post-checkout` hook) while `.kb/` holds authored sources, the response also carries `branchStore` (`state: "not_compiled"`, `code: "branch_store_not_compiled"`, `path`, `detail`, `remediation.command_argv: ["kibi", "sync"]`) and the text says to run `kibi sync` before relying on the results: an empty result from that store says nothing about the authored requirements. When a compiled store is confirmed stale for the query (with auto-sync off or after uncompiled `.kb/` or requested-path drift), `kb_search` and `kb_query` carry `meta` (`syncState: "stale"`, `dirty: true`, `staleReasonCount`, `staleReasons`), a `branch_store_stale` warning diagnostic in the envelope, and a stale-store warning note in `content[0].text` (kept even when `kb_query` results are budget-truncated). On the first intent-mode page, `data.answer` (`kibi.search-answer.v1`) turns the matches into what an agent asking "what governs this?" needs: - `governing`: current requirements matched by the query or linked to a matched entity, a closed requirement after a current one reached as well (its score carries the same three-quarter factor). A superseded requirement's replacement is added with `via: "supersedes "` only when the superseded requirement scored at least 0.8 of the best candidate's score, so a weak match on an old requirement does not fill a slot with its replacement. Each has `score`, `via` (how it was reached), `statement` (what it says: its `semantic_text`, else the statement its body derives, at most 300 characters; absent when neither holds prose), and its linked `facts` (with `factKind`, and for typed facts the `claim` they state; with `fields: "full"` also the `kb_query` call in `ask` that selects the fact by its own key arguments, as described under `kb_query`), `scenarios`, `tests`, and `adrs`. Facts list a fact the query matched first, then the facts grounding a clause (`requires_*`), then the constrained subject, at most eight per requirement; when more are linked, or the byte bound cut some, `moreFacts` gives the `count` left out and the `ask` (`kb_query` by the requirement's `id`) that lists every link. Tests include those that verify the requirement's scenarios; each test's `via` is `direct` or the scenario it was reached through. Each requirement also carries: - `why`: its recorded reason. `{ "recorded": true, "text", "from" }` takes the first that holds prose: the `rationale` field (`from: "rationale"`), a Why, Rationale or Context section (`section`; one that says "Reason not stated" holds none), a "Why this changed" section (`why_this_changed`), then the decision of a linked current ADR (`adr`). A line or list item that only notes a split or supersede ("Split from REQ-…", "Superseded by …", "Supersedes …", "Replaces …", "Replaced by …") is not a reason. `text` is at most 280 characters, and is left out only when the byte bound cut it. A reason from the requirement itself also carries `said`: `by`, the person who approved it (`origin.approved_by`) or else the origin's kind (`human`, `agent` or `import`), and `on`, the date the origin was recorded; a migration origin names neither. `{ "recorded": false }` means none of them records a reason; an agent asked why says so instead of supplying one. - `verdict`: what the existing checks report about it. `status` is `contradiction` (a domain-contradiction witness names it), `infeasible` (a scenario-feasibility witness: a success scenario it specifies assumes a value a current requirement forbids, or it forbids another requirement's scenario), `unknown` (only `unknowns` below), or `none`. `witnesses` lists each blocking finding with its `check`, `status`, the other requirement (`with`), the `scenario`, the `facts` involved and a `detail`. `none` means no check named the requirement, not that it is proven; proof-ladder status stays in `kb_coverage`. - `exceptions`: requirements that `exempts` it, each with `approvedBy` when a human approved the exception. - `unknowns`: what the checks could not decide, each with a `kind` and `detail`: `contradiction_unresolved` (a rule overlap the checks could not classify), `feasibility_unknown` (a success scenario whose assumptions no current requirement constrains), `unresolved_proposition` (a clause still `ambiguous` or an `ontology_gap`), `analysis_incomplete` (no complete clause ledger), or `verdict_unavailable` (the checks could not run). - `rationale`: ADRs that explain the decisions, each with its `source` path and an `excerpt`: the opening sentences of its Decision section (falling back to Rationale, then the first paragraph), at most 280 characters. - `notGoverning`: superseded or deprecated requirements, with `supersededBy` when known. They are listed so they are never read as current policy. - `observations`: observation/meta facts, labelled as notes rather than rules. - `ungoverned`: matched facts, scenarios, symbols and tests that no requirement owns (a fact that a requirement's scenario assumes, such as its failure side, is lifted to that requirement instead), each with its `type`, its 1-based `rank` in the results and, for typed facts, the `claim` (and with `fields: "full"` the `ask`) above. An unlinked predicate fact that states the same predicate and key arguments as a governing requirement's fact, with another value or polarity, carries `overriddenBy` (`fact`, `requirement`, `claim`) naming the fact that holds, and the `note` names the pair. A negative-path fact listed here (no current requirement specifies the scenarios that assume it) carries `negativePath` and a title prefixed `Forbidden: `. When the top-ranked match is one of them, the `note` says so first: the `governing` list, if any, was reached through lower-ranked matches and is not the top match's requirement. - `scope`: the KB the answer was computed from: `branch`, `snapshotId`, `syncedAt`, `syncState` (`"fresh"`, `"stale"`, or `"unknown"`), and, when stale, `staleReasonCount`. - `truncated`: `true` when a size bound cut the layer short. The whole answer stays under 16 KB: long titles, excerpts and details are clipped, then ADR excerpts are dropped, then each requirement keeps only its first scenario and test, then lower-ranked requirements and list entries, then the remaining requirement's statement and then its reason text; a verdict keeps its `status` when its witnesses are dropped. - `note`: how to read the layer. An empty `governing` list is not evidence that nothing governs the change. The answer layer is graph traversal plus the existing checks scoped to the governing requirements: discovery, not proof. Use `kb_check` and `kb_coverage` for full consistency and proof status. Pass `answer: false` to skip it. When a `kibi.search-hints.v1` provider is active (the bundled `kibi-plugin-search-hints` unless the project configured another provider or listed it in `kibi.declinedPlugins`), every decision search asks it to score each decision and each scenario, test and fact a decision links (`specified_by`, `verified_by`, `constrains`, `requires_*`, and the facts its scenarios assume), up to 50,000 entities. Each decision's own similarity is fused with the word ranking by reciprocal rank at weight 0.5. On the first page `queryAnalysis.hints` has the `provider` stamp (with its `model`) and `items`: up to seven decisions related by meaning that are not a card or folded into one, each with `id`, `title` and `score`, the mean of its two best scores among its own text and its linked entities, highest first. Superseded decisions and decisions in another scope are never listed, and the text names the items in one sentence. Shadow providers appear under `shadow` only, and `diagnostics` names a provider that failed, timed out, returned an invalid result or could not load; the search then ranks by words alone. Read a listed decision with `kb_query` before relying on it. Pass `hints: false` to rank by words alone. When the first page of an intent answer abstained or is weak and lists no decision related by meaning (hints are off, declined, failed or empty), the envelope's top-level `nextActions` (not repeated in `data`) holds a `kb_query` of the requirement titles (of the `type` filter when one is given), `required: false`: a missing match is not evidence that nothing is recorded, and the titles show the words to search with. A weak decision answer and an abstained typed answer also carry `notes` with that sentence, so the advice does not depend on the text digest. A file path written in the question adds a `kb_search` action that repeats the question with that path as `sourceLocations`, and a question about contradictions adds a `kb_check` action with `rules: ["domain-contradictions"]`. These mirror the advice in the text and do not change when it is given. **Example:** ```json { "query": "what governs the login flow?", "type": "req", "limit": 10 } ``` ### `kb_compile_intent` Compile complete post-change intent into a deterministic, snapshot-bound plan without mutating the KB. The compiler reuses intent-aware discovery and the semantic advisor, accounts for every proposition, checks current contradiction witnesses, proposes canonical traceability links, and emits dependency-ordered `kb_upsert`-style steps only for resolved typed claims. A conditional clause ("only when", "only if", "must not ... unless") on one subject property compiles to a `forbid` rule linked by `requires_rule`; one the advisor cannot translate stays an `ontology_gap` proposition and the plan `needs_resolution`. **Parameters:** - `intent` (required): Complete desired behavior, not a patch fragment. - `context` (required when the plan creates a new requirement, otherwise optional): Why the requirement exists, who asked and constraints, in the requester's words. Rendered as the `## Context` section of the requirement body; on update the statement is replaced and every existing context section is kept byte for byte unless `context` (or the source) is supplied, which replaces that section; a missing value is a validation error naming the field. Write "Reason not stated" rather than inventing one. - `sourceExcerpt`, `sourceReference` (optional): A verbatim quote and where it came from, rendered as a blockquoted `## Source` section. - `mode` (required): `create` or `update`. - `requirementId` (optional): Exact update target; automatic update selection is gated by score and runner-up margin. - `title`, `clauses`, `semanticFacets`, `sourceLocations`, `interpretations` (optional): Context for title, proposition decomposition, host-agent facets, changed-code evidence, and typed rule IR. Each `clauses` entry must be a verbatim fragment of `intent` (whitespace may differ); a clause that does not occur in `intent` fails the call with `VALIDATION_FAILED` naming it, instead of producing a proposition over unrelated text. - `scenarioDrafts`, `testDrafts` (optional): Draft traceability artifacts. Each draft's `body` is carried as the step's `document.body`, not as an entity property. Tests are linked through scenarios with `verified_by` (the scenario step carries the link, and tests are ordered before the scenarios that link to them; the requirement step carries `specified_by`); when multiple scenarios are supplied, each test must declare stable `scenarioIds` (a single scenario remains backward-compatible). Draft tests default to ancillary `integration`/`internal` evidence; explicitly declare `end_to_end`/`consumer` when that is the intended proof-bearing scope. - `proposalDecisions` (optional): Explicit `accept`/`reject` decisions for returned traceability proposals; pending proposals are excluded from executable steps. - `conflictReviews` (optional): Your verdict on each `contradictionAnalysis.reviewCandidates` entry of an earlier compile, as `{requirementId, verdict: "conflict" | "no_conflict", note?}`. A `conflict` verdict makes the outcome `conflict` and the plan `blocked`; a `no_conflict` verdict clears that candidate. A verdict may name a current requirement discovery did not rank; one that names no current requirement is ignored with a diagnostic. **Returns:** `kibi.compile-plan.v1` with `planHash`, status (`ready`, `needs_resolution`, or `blocked`), branch/KB/workspace snapshot bindings, discovery candidates, proposition ledger, contradiction analysis, traceability proposals, dependency-ordered steps, source before-hashes, and diagnostics. The plan is a review artifact; it is not a mutation request. Every non-symbol step of a `ready` plan carries `document.path`, the authored document `kb_apply_plan` writes that entity to (the same canonical path `kb_upsert` would pick). The requirement's document is the first `sourceLocations` entry when it is a `.md`/`.mdx` file outside `.kb/`, otherwise its existing document or `.kb/requirements/.md`; its `document.body` is the intent, then `## Context` with `context`, then `## Source` when `sourceExcerpt` or `sourceReference` is given, and `semantic_text` is written explicitly so the context never changes the checked meaning. Code `sourceLocations` are evidence only and are never write targets. `sourceWrites` is empty for compile plans. A step that cannot be applied as written (it fails entity validation or its document path cannot be resolved) makes the plan `needs_resolution` with the diagnostic `A plan step cannot be applied as written: …`. `contradictionAnalysis` stages the plan in a rolled-back transaction and compares it with the current KB: `introduced`, `removed` and `unchanged` list full contradiction and scenario-infeasibility witnesses (kind `property`, `predicate`, `rule` or `scenario_feasibility`; a scenario witness carries `scenario`, `requirements`, `assumedFacts` and `requirementFacts`). Any introduced contradiction or infeasible scenario makes the plan `blocked`, whichever requirements it names; a pre-existing one blocks only when it names the target requirement. `witnesses` lists the ones that decided `outcome`. `outcome` is `no_conflict` only when the check could decide. The checker compares only requirements with a logical representation (`constrains`, `requires_property`, `requires_predicate` or `requires_rule` links), so no witness does not mean no conflict. `reasons` lists what it could not check, each with the ids involved: `unmodeled_target` (claim keys of target propositions that are `ontology_gap` or `ambiguous`), `unmodeled_related` (related current requirements from discovery that have no logic, when the target is modeled) and `analysis_unavailable` (the staged check could not run). Any reason makes the outcome `unresolved`. `reviewCandidates` lists up to five related current requirements (discovery score at least 0.1; any related requirement when the target is unmodeled, only prose-only ones otherwise), each with `requirementId`, `title`, the `sentence` sharing the most terms with the intent, its `statement`, `score`, `modeled` and `review` (`pending`, `conflict` or `no_conflict`). `nextAction` tells the agent what to do while the outcome is not decided: compare the pending candidates and compile again with `conflictReviews`, resolve a conflict it reported (ask the human which rule holds, then supersede or change the requirement, or change the intent), or model the unmodeled claims. Pending reviews do not change the plan status: a plan with a modeled target stays `ready` with the outcome `unresolved` and the diagnostic `Contradiction check incomplete: …`, and becomes `no_conflict` once every candidate is reviewed `no_conflict`. A plan with an unmodeled target is already `needs_resolution`, and its outcome stays `unresolved` after review, because a review is not a logical check. **Example:** ```json { "intent": "Customer data must be retained for 7 years.", "mode": "create", "sourceLocations": [{"path": "src/retention/policy.ts", "symbol": "retentionYears"}] } ``` ### `kb_apply_plan` Apply an approved `kibi.compile-plan.v1` after revalidating its canonical hash, branch/KB/workspace snapshots, source before-hashes, and entity/relationship shapes. Every step runs through the same validation chain as `kb_upsert` (schema, proof receipts, relationship sources and targets, strict-lane pairing, supersedes direction, proposition-complete ingestion, grounding claim keys, predicate argument vocabulary), with entities and relationships created by earlier steps treated as present, and the whole plan is staged in a rolled-back transaction before the first write; a plan whose staged state introduces a contradiction or an infeasible success scenario is refused with nothing written. A compile plan then applies all-or-nothing: 1. Before the first write, Kibi writes a durable journal (`plan-apply-`) next to the branch store (under `.kb/recovery/plan-apply/` until the store exists). The journal records the plan hash, the exact before and after bytes and hashes of every workspace file the plan changes (its `sourceWrites`, each step's entity document, and the relationship shards its steps append), every store upsert, and a fingerprint of the store entities the plan touches. Plans without source writes get a journal too. 2. Files are published with temp-file + rename, fsynced where the host supports it. 3. All steps commit in one store transaction. That transaction is the only commit point. Each entity is committed with its authored document as its source, so `kibi sync --rebuild` keeps every entity and relationship the plan applied. Any failure before the commit restores every file from the journal and leaves the store untouched; the error says `no change was applied` and the plan can be applied again. If the process dies mid-application, the next `kb_apply_plan`, `kb_upsert` or `kb_delete` call (or `kb_apply_plan` with that `recoveryJournalId`) finishes the journal before doing anything else. A journal interrupted before the store commit was submitted is rolled back. One interrupted during the commit is decided by the store fingerprint: unchanged means roll back, changed means complete. One whose commit was accepted is completed. Recovery is idempotent, and it refuses (`PARTIAL_COMMIT_REPAIR_REQUIRED`), changing nothing, when a journaled file holds neither its journaled before nor after bytes. Mutating calls on that branch then fail until an operator resolves it. `kibi sync` does not yet settle pending plan journals; run a mutating call or the explicit recovery first. A bootstrap plan (`kibi.bootstrap-plan.v1`) applies its actions one at a time, checkpointing each in a `bootstrap-` journal under `.kb/recovery/`. Large bootstrap plans take a while (a few hundred actions can run past a minute), so: - A synchronous apply sends MCP `notifications/progress` after each action when the request carries a `progressToken`. Clients that reset their request timeout on progress (the MCP SDK's `resetTimeoutOnProgress`) keep waiting, and the server's own `KIBI_MCP_TOOL_TIMEOUT_MS` then bounds the time between progress reports rather than the whole apply. - `async: true` returns a `kibi.job.v1` receipt immediately and runs the apply as a background job; poll [`kb_job_status`](#kb_job_status) for the result. This needs `KIBI_MCP_OPTIONAL_TOOLS=kb_job_status`; without it the apply runs synchronously. - The plan is checked before any action runs. An invalid plan, or a missing or wrong `approvedPlanHash`, fails the call itself (also with `async: true`) instead of surfacing later in the job, and approval stays bound to the exact KB snapshot, including the journal generation and revision. A deterministic failure after application began (`BOOTSTRAP_PLAN_REJECTED`) is terminal and needs a corrected plan. - If the server dies mid-apply, call `kb_apply_plan` with the journal's `recoveryJournalId`. A journal still `applying` whose active action has no checkpoint is resumed without edits: the drift since the last checkpoint is attributed to that action, which is re-applied, and the result notes it. A source lock left by the dead process is reclaimed and recorded in the journal (`lockReclaims`); a lock whose holder is still alive keeps blocking. Any other drift since the last checkpoint is still refused. Never edit the journal by hand. **Parameters:** - `plan` (required): Complete plan returned by `kb_compile_intent`. - `approvedPlanHash` (required): Exact reviewed `planHash`. - `recoveryJournalId` (instead of `plan`): A `plan-apply-*` journal to complete or roll back, or another typed recovery journal returned by a `committed_with_repairs` result. Recovery never replays the original plan request. - `async` (optional, default `false`): Start the apply as a background job and return a `kibi.job.v1` receipt; see above. The CLI ignores it. **Returns:** `kibi.plan-apply-result.v1` with entity/relationship counts, final snapshots, validation counts, changed paths (every source write and entity document the plan wrote), `recoveryJournalId`, and notes. `outcome` is `applied` when this call committed the plan, or `replayed` / `rolled_back` when a recovery completed or rolled back an interrupted application. Recoveries a call performed before its own work are listed in `validationSummary.recoveredJournals` and in the text content. If the call then fails, its error text ends with `[settled before this failure: ...]`. A store that reports a failure but shows the batch committed yields `committed_with_repairs` with `STORE_COMMIT_REPORTED_FAILURE`. A pending-source receipt failure after the commit yields `committed_with_repairs` with `PENDING_SOURCE_RECEIPT_FAILED` and a `kb_apply_plan` recovery next action; further writes fail with `PLAN_APPLY_RECOVERY_REQUIRED` until that journal is recovered. Re-applying a committed plan fails with `MUTATION_ALREADY_COMMITTED`. It also accepts `kibi.migration-plan.v2`; migration application requires `approvedActionIds`, an exact `approvedPlanHash`, and rejects blocked actions and review actions Kibi cannot execute. A review action with a `cli` invocation that Kibi can execute (`semantic_inventory_rederive_drop_grounding`, `req_status_vocabulary_map`, and a `semantic_inventory_rederive` that waits on a status mapping) runs only when its id is in `approvedActionIds`; `kibi migrate --apply-safe` without `--approved-action` selects automatic actions alone. The `integrationPlan` from `kibi proof inspect --json` is such a plan: its `proof_integration_configure` action writes `.kb/proof/integrations.json`, refusing a create once the file exists and any plan whose source files (`package.json`, lockfiles, runner configs) changed since planning. Migration results (`kibi.migration-apply-result.v1`) report per-action outcomes (`applied`, `failed`, `skipped`, each with a `detail`) and an overall `outcome`: - `applied`: every approved action applied (`closeout.taskOutcome: complete`). - `partially_applied`: some actions applied before one failed; the rest were skipped (`closeout.taskOutcome: interim`). - `refused`: nothing was applied and every failure was a refusal, a precondition that failed before the action changed anything (for example a proof-integration create plan whose file already exists, a source that changed since planning, or an action with no automatic executor). The workspace is unchanged, so there is nothing to reconcile: obtain a new plan. The envelope is an error (`status: "error"`, MCP `isError: true`, CLI exit code 1) with code `MIGRATION_PLAN_REFUSED` whose message carries the refused action's `detail`; `closeout.taskOutcome` is `blocked`. - `reconciliation_required`: nothing was applied but an action failed without being refused, so its partial effect must be inspected before retrying (`closeout.taskOutcome: blocked`). After an applied migration on a healthy store, `remainingPlan` (`kibi.migration-plan-digest.v2`) reports what is left without repeating the whole plan: the merged plan's `planHash`, `status`, `expected`, `scope`, `summary` and `diagnostics`, the first 20 automatic actions as `{ id, code, state, autoApplicable, dependsOn }` (`automaticActions`), counts of all automatic actions (`automaticSummary`: `total`, `ready`, `blocked`, and `omitted` for those past the first 20), and every other action counted by `code`, `safety` and `state` (`actionGroups`). A digest cannot be applied; `kb_status`, `kb_check` and `kb_coverage` (or `kibi migrate`) return the full plan with each action's details. When an automatic action in the digest is `blocked`, its `next` text says so: the action waits for the actions in its `dependsOn` and needs no approval until a later plan shows it ready. **Engine daemon after a session.** MCP calls that use the branch store (for example `kb_apply_plan`, `kb_upsert`, `kb_check`) run in the workspace's engine daemon, a detached `engine-daemon` process with its own SWI-Prolog child that holds the branch store's `rdf/lock`. It is shared: later MCP sessions and CLI calls for the same workspace and branch reuse it. After the MCP server exits, the daemon and its lock stay until the daemon has been idle for 10 minutes (`KIBI_ENGINE_IDLE_TIMEOUT_MS` overrides this), then it exits and releases the lock (idle time is measured on the wall clock, so time the host spent suspended counts). A stopping daemon saves the store and detaches it, which removes `rdf/lock` and the ownership journal, before its SWI-Prolog child exits. A lock held by a live daemon is expected, not a stale lock: `kibi engine status` shows it and `kibi engine stop` ends it early. A lock whose process is gone is reclaimed automatically when the next engine starts, and `kb_status` reports the takeover in `notices` (`store_lock_taken_over`). A client only uses a daemon started with the same Kibi package versions (`kibi-cli@…,kibi-core@…`), Prolog core (a digest of its sources) and SWI-Prolog as its own, so two installs of one release share a daemon: the daemon reports both in its handshake and refuses other requests from a client that differs, and the client stops such a daemon (for example one an older install started from a git hook) and starts its own. `kibi doctor` reports the package versions of the daemon that is running. ### `kb_ingest_proof` Ingest a producer-emitted `kibi.proof-run.v1` artifact and evaluate it against each selected test's `kibi.proof-contract.v1` proof obligations. Kibi rechecks the live workspace snapshot, integration command binding, run-level outcome, attempt history, success policy, and proof history ordering, then derives and appends idempotent `kibi.proof-receipt.v1` receipts and compacts each history to the receipts that can still decide proof (`kibi.proof-receipt-compaction.v1`; kept receipts are never edited or reordered). Producers report what happened; Kibi evaluates proof. Caller-authored receipts and trusted outcomes are rejected. **Parameters:** - `snapshot` (required): Workspace snapshot captured immediately before execution. - `artifact` (required): Producer artifact containing `version`, `producer`, `integration`, `command_argv`, `code_snapshot`, typed `environment`, run-level `run` outcome, and `proof_results` (each with `symbol_id`, `target`, `outcome`, `binding`, and factual `attempts`). - `testIds` (optional): Existing test entities with `kibi.proof-contract.v1`. Omit to evaluate every test contracted to the artifact's integration. **Returns:** Per-test outcomes, receipt ids, applied/duplicate flags, receipt counts, the number of superseded receipts compacted away (`compacted`), expected-versus-received gap reports, the contract's proof `kind`, the `evidenceLevel` the receipt supports (`proved` only when its certificate re-checked), `certificateRejection` when it did not, and `claimBindings`, plus the artifact digest and Kibi-derived environment hash. A changed snapshot, unknown integration, command drift, run-level failure, failed success policy, or append-only violation fails before mutation. ### `kb_status` Return branch, snapshot, and freshness metadata for the attached KB, plus the deterministic workspace snapshot used to validate execution receipts. **Returns:** Branch name, KB snapshot ID, sync state, dirty flag, KB path metadata, and `proofSnapshot` evidence (`available`, `dirty`, file count, and `kibi.workspace-snapshot.v2` version). An unavailable workspace snapshot is reported as `unknown` and cannot prove the proof stage. Receipt-only frontmatter edits do not change the v2 hash. `sessionBrief` is the Kibi session brief: search for the recorded intent before changing behaviour, record the person's decisions with their reason, run the commit check before finishing, and ask before a change that would make a recorded rule false. The host plugins add the same text at session start and the server returns it in its `initialize` instructions, so an agent on a host without hooks reads it too. The response also includes exact `branchAttachment` metadata, bounded sorted `staleReasons` (with affected entity IDs and truncation totals), and `proofSnapshotChanges`. Editor/config paths are reported as ordinary workspace changes; they are not silently ignored. When migration is needed, the response includes `schemaStatus` and a typed `migrationPlan` (`kibi.migration-plan.v2`) with canonical hash, scope completeness, dependencies, safety classes, exact invocations, evidence, and postconditions. Status never mutates and remains available without Prolog for missing or damaged stores. The `schema-config-upgrade` action runs `kibi migrate --yes` and lists every file that run writes, `.gitignore` included; on the canonical `.kb/` layout the source rewrites it performs (such as `symbol-legacy-link-mark` on `.kb/symbols.yaml`, origin backfill and lifecycle repairs) are separate actions it depends on, so they must be approved with it. `kb_apply_plan` reports the upgrade's `detail` from the migration audit record (schema versions, legacy-link marks, origin backfill, lifecycle repairs, whether `.gitignore` changed). `kb_status` remains diagnostic when the branch store is missing, incomplete, or unreadable: it reports `branchStore` and a structured stale reason instead of initialising or repairing storage. Status itself never creates a store, but a call that attaches the engine does (`kb_check` and other tools that need the engine over MCP, `kibi check` on the CLI, and `kibi branch ensure`), and that store stays empty until `kibi sync` compiles it. An incomplete or unreadable exact store is rebuilt only through the previewed `kibi branch recover --apply` workflow. A store that is missing or empty (journal sequence 0) while `.kb/` holds authored sources, the state of a new branch created without the `post-checkout` hook, is one blocking stale reason, `branch_store_not_compiled` (`blocking: true`, `authoredSources`, remediation `kibi sync`), and the `migrationPlan` adds the automatic `branch-store-compile` action (`kibi sync`) after `branch-store-ensure`; `syncState` is then `"stale"`, whether the store is missing or empty. A missing store with no authored sources, and an incomplete or unreadable one, report `syncState: "unknown"`. `kb_check` over MCP and `kibi check` alike then return the single `branch-store-not-compiled` violation (MCP uses the runtime's branch attachment, including a `KIBI_BRANCH` override), and `kb_apply_plan`'s `closeout.kbState` reads `stale` (not `not_evaluated`) while the store stays uncompiled. An authored `.kb/` file that the last `kibi sync` could not extract (an invalid front matter field, such as a legacy requirement `status: implemented`) is a blocking stale reason, `source_extraction_failed` (`path`, `detail` with the extraction error, `remediation`), for as long as the file still has the bytes that failed; `syncState` is then `"stale"` and `dirty` is `true`, because what the file declares is missing from the KB. `kb_check` reports the same file as a blocking `source-relationship-parity` violation, and the `migrationPlan` lists it as a review action. Editing the file and running `kibi sync` clears it. The Prolog freshness check compares file modification times with the compiled snapshot. A fresh clone or a checkout rewrites every mtime without changing content, so before reporting `indexed_source_newer`, `knowledge_source_newer` or `documentation_source_newer`, `kb_status` compares the file's sha256 with the hashes the last compilation recorded (the store's `sync-cache.json`, a symbol manifest's composite hash of the sources it references, or the per-symbol `sourceHash` in `.kb/symbol-coordinates.yaml`). The coordinate artifact counts as evidence on its own, so code files referenced only by symbols that `kb_upsert` wrote into an untracked `.kb/symbols.yaml` are confirmed even though sync never hashed that manifest. A file whose content matches is dropped, and when nothing else remains the branch is `fresh`. A file with no recorded evidence keeps its reason. Sources whose content did change become one automatic `freshness-resync` action (`kibi sync`) in the `migrationPlan`, which `kb_apply_plan` runs. The same action covers `compiler_changed`, which a branch store compiled by a Kibi CLI with a different entity schema reports once after an upgrade: the sync re-imports every source and stamps the current schema, so that reason clears without a review action. When an untracked `.kb/symbols.yaml` has no pending-source receipt (as older Kibi versions left it) but declares symbols the branch store already holds, `kibi sync` writes the receipt `kb_upsert` would have written, compiles the manifest and records its content hash. `notices` lists informational, non-blocking observations that never make the KB stale. `store_lock_taken_over` (with `brokenPid`, `reason` and `at`) reports that Kibi broke a branch-store lock whose holder was no longer running and reattached: a crashed or killed engine or `kibi prove` run held the store. A lock and ownership journal copied in with the `.kb` directory (for example by `cp -a` while another workspace's engine held its own store) is taken over the same way, with `reason` `journal belongs to another workspace `, because a copied file never carries its advisory lock. It is recorded in `/.kibi-lock-takeover.json`, shown for 24 hours (and by `kibi doctor`'s branch-store check), replaced by the next takeover, and deleted by `kibi engine janitor --apply` once it is older than that. `branch_store_repaired` (with the record's `path`) reports that an engine removed duplicate triple copies an earlier release saved in the branch store snapshot, and printed `kibi: repaired branch store ...` on stderr. It is recorded in `/.kibi-store-repair.json` and shown for seven days (and by `kibi doctor`'s branch-store check as a warning), so answers given before the repair can be rechecked. See [Troubleshooting](troubleshooting.md#kibi-repaired-branch-store-on-stderr). **Example:** ```json {} ``` ### Engine cancellation limits MCP tool timeouts abort the operation `AbortSignal`, which `adaptProlog` forwards to `EngineClient` (`query`, `queryEntities`, `searchEntities`, `queryStatusJson`, `save`). The client rejects pending RPCs and sends a best-effort `cancel` frame. **Queued** daemon requests on that connection are skipped before `handle()`. Cancel marks are **per-connection** (request ids are not global). SWI-Prolog cannot cancel a running interactive goal, so when the cancelled request is the one running, or its client disconnects while it runs, the daemon stops its Prolog session; the next request restarts the session and reattaches the branch store, and requests queued behind it run there. The engine's own 120 s query timeout stops the session the same way. Read-tool timeouts still must **not** call `resetProlog` / `terminate()` on the client, so siblings do not fail with `Kibi engine connection closed`. To keep one read from holding the queue, set `KIBI_ENGINE_READ_TIME_LIMIT_MS` and/or `KIBI_ENGINE_READ_INFERENCE_LIMIT` in the MCP server's environment (see [engine read limits](cli-reference.md#engine-read-limits)). A bounded read runs under SWI-Prolog `call_with_time_limit/2` and `call_with_inference_limit/3`, so the engine stops it itself and serves the next queued request. A tool whose read hit its limit returns an error envelope with `error.code` `QUERY_LIMIT_EXCEEDED` and `error.details.limitExceeded` (`{ "kind": "time" | "inferences", "limit": }`); it never returns a partial answer. Write requests are never bounded, but the read-only queries a write tool such as `kb_upsert` runs before it writes are reads: under a limit they can stop it with `QUERY_LIMIT_EXCEEDED` before anything is written. On a detached HEAD that no single local branch points at, read tools answer from a read-only snapshot of the checkout and add a `detached_head_read_only` warning diagnostic (commit, branches at HEAD, store path, `writes: "refused"`); write tools fail with instructions to check out a branch or set `KIBI_BRANCH`. See [`kibi branch`](cli-reference.md#kibi-branch). Discovery tools (`kb_query`, `kb_search`, `kb_status`) may opt into `agentVisibleStructuredData` so envelope `data` is also embedded in `content` text for hosts that hide `structuredContent`. ### `kb_skills` Read bundled Kibi agent skills for progressive disclosure. Read-only; does not mutate the KB or require Prolog. The CLI peer is `kibi skill --input -`; the narrower `skills-list`, `skills-load`, and `skills-read` routes remain. **Parameters:** - `action` (required): `list`, `load`, or `read`. - `id` (required for `load` and `read`): Bundled skill ID. Example: `'kibi-usage'`. - `resource` (required for `read`): Manifest-declared resource path. Example: `'resources/fact-lanes.md'`. Arbitrary file paths are not exposed. **Returns:** The payload of the routed operation plus `action`: - `list`: skill manifests with `id`, `name`, `version`, `description`, and declared `resources`. - `load`: the skill bundle with `manifest`, `body`, `resources`, `hash`, and `sourceType`. The visible text lists the declared resources so agents can discover follow-up `read` calls without guessing paths. - `read`: the resource contents as text. **Example:** ```json { "action": "read", "id": "kibi-usage", "resource": "resources/fact-lanes.md" } ``` ### `kb_find_gaps` Run curated missing/present relationship analysis over KB entities. **Parameters:** - `type` (optional): Entity type filter - `missingRelationships` (optional): Required-to-be-absent relationship types - `presentRelationships` (optional): Required-to-be-present relationship types. In both lists a relationship counts in either direction, and `verified_by` and `validates` (its documented inverse for req/scenario ↔ test links) satisfy each other: a requirement whose test `validates` it is not a `verified_by` gap. `relationshipCounts` still counts each relationship name separately. - `tags` (optional): Tag filter - `sourceFile` (optional): Source-file substring filter - `limit` / `offset` (optional): Pagination controls **Returns:** `rows` (the requested page, each with its relationship counts, cut to the [result size budget](#result-size-budget)), `count` (matching rows before pagination), `summary` (`total`, the same number, and `provenanceStubs`: the bootstrap facts tagged `bootstrap:provenance-stub` that match the filters but are counted apart from knowledge and left out of `rows` unless `tags` names that tag), and `meta` (status metadata). **Example:** ```json { "type": "req", "missingRelationships": ["specified_by", "verified_by"], "sourceFile": "src/auth" } ``` ### `kb_coverage` Generate curated structural coverage and conservative end-to-end requirement proof reports. **Parameters:** - `by` (optional): `req`, `symbol`, or `type` - `tags` (optional): Tag filter - `includePassing` (optional): Include requirements with a tested or not-applicable proof outcome in addition to rows that still require repair - `statuses` (optional, req mode): Requirement proof-status filter (`tested`, `missing`, `unresolved`, `not_applicable`); selecting statuses implies include-passing and returns only rows whose `proofStatus` is listed. `not_applicable` rows carry their typed applicability reason in `proofStages.applicability.reason`. The summary always reflects the whole KB. - `includeTransitive` (optional): Include transitive symbol coverage - `includeMigrationPreview` (optional): Add a deterministic read-only legacy proposition migration preview - `migrationLimit` / `migrationOffset` (optional): Page ready semantic-inventory requirement batches; the default limit is one and the maximum is ten - `migrationPredicateLimit` / `migrationPredicateMinScore` (optional): Bound exact predicate-schema candidates retained per proposition - `fields` (optional, default `summary`): summary rows leave out `testResolutions` and reduce each proof stage to its status, and the plans come as `repairPlanSummary`, `symbolRepairPlanSummary` and `migrationPlanSummary`; `full` returns full rows and the plans with their batches and actions. Use `full` with a narrow filter or a small `limit`. - `limit` / `offset` (optional): Pagination controls **Returns:** Coverage summary rows, `matched` (the rows the filters select before paging), status metadata, and—when `by: "req"`—a deterministic `kibi.repair-plan.v1` read-only migration plan (its summary unless `fields: "full"`). The result keeps to the [result size budget](#result-size-budget): it returns the rows that fit with their plans, at least one, and marks a cut with `truncated`, `truncation` (with `total: matched` and `nextOffset`) and the next call. One row still past the budget has its largest parts left out and named in `omittedFields`. A repeated call on an unchanged store reuses the computed report: the check time it is computed for is rounded down to a 15-minute window. For requirement coverage, summaries distinguish evaluated must-priority requirements from rows marked `notApplicable`. Requirement rows retain compatibility-oriented `coverageStatus` and add a separate `kibi.requirement-proof.v5` result with `evidenceLevel` (`proved`, `tested`, `asserted` or `unverified`, with the `evidence[]` entries that earned it; the summary counts them under `evidenceLevels`), per-claim `claimEvidence[]` with `claimSummary` and `unprovedClaims` (proved needs a derived certificate binding for every applicable claim; the summary totals them under `proofClaims`), `evidenceFloor` (`required`, `source`, `status`; the summary counts current requirements with a floor under `evidenceFloors` as `met`, `below` and `pendingReproof`), `proofStatus` (`tested`, named `proven` before v4, `unresolved`, `missing`, or `not_applicable` for a non-current requirement), inspectable `proofStages`, blocking `proofGaps`, non-blocking `proofAdvisories`, and ranked `proofRepairs`. A row is proven only when semantic inventory and grounding, contradiction analysis, every linked scenario's qualifying fresh passing E2E receipt evidence, executable test symbols, production ownership/coverage, and exact source coordinates all pass. Every linked E2E proof-bearing test is mandatory: missing, stale, failed, invalid, snapshot-unavailable, or contract-mismatched evidence remains a blocking `proofGap`, with per-scenario diagnostics in `proofStages.passingE2e.scenarioObligations`. Unit/integration-only ancillary evidence remains nonblocking when the scenario has qualifying E2E evidence. A proven row never includes blocking `proofGaps`. `repairPlan` turns those row-local gaps into dependency-ordered batches across the returned requirement scope. Each batch identifies one requirement and phase, groups same-phase repairs, declares `state: ready|blocked`, lists prior `dependsOn` batches, and carries `workflowSteps`, targeted `validationRules`, and a conservative write policy. Plans are always `readOnly: true`; batches are always `autoApplicable: false`, so callers must query current endpoints, review semantic choices, validate payloads, and execute upserts sequentially. `scope.complete: false` and `status: partial` mean pagination omitted actionable requirements; read the following pages with `offset` before treating the result as a project migration plan. `planId` remains stable for the same snapshot, filters, proof evidence, and gaps while volatile receipt age/check-time fields are ignored. With `includeMigrationPreview: true`, `legacyMigrationPlan` adds the versioned `kibi.legacy-migration-plan.v1` review surface. It selects only ready semantic-inventory repair batches, defaults to one requirement, binds normalized authored Markdown to an exact SHA-256 hash and UTF-8 spans, and gives every proposition one recommended lane or explicit unresolved disposition. Ranked candidates preserve exact schema identity, signature, origin, polarity, binding status, and unbound arguments, but never produce an applicable write. Authored prose is previewed in requirement-only `semantic_text`, while an independent `text_ref` remains unchanged; a differing pre-existing `semantic_text` blocks the batch as semantic source drift. The passing-E2E stage evaluates append-only proof-receipt history. New evidence is produced by `kibi prove` as `kibi.proof-receipt.v1`. A current receipt must bind the test and its typed scope, integration command argv, contract hash, execution fingerprint, deterministic current code snapshot, canonical environment hash, timestamps, outcome, artifact digest, and observed proof results. The newest receipt for the live snapshot, current contract hash, and current fingerprint must be passing and no older than seven days. Missing, wrong-snapshot, stale, failed, malformed, mismatched, future-dated, or snapshot-unavailable evidence cannot prove the requirement; durable test status remains structural metadata. Symbol rows distinguish production symbols from executable test symbols. Executable-only symbols are not applicable to production coverage; mixed-role symbols are uncovered and carry an explicit role error. **Example:** ```json { "by": "req", "includePassing": false, "includeTransitive": true } ``` ### `kb_graph` Run bounded graph traversal from one or more seed IDs. **Parameters:** - `seedIds` (required): Starting IDs - `relationships` (optional): Relationship filter - `direction` (optional): `outgoing`, `incoming`, or `both` - `depth` (optional): Maximum traversal depth - `entityTypes` (optional): Filter returned nodes by type - `maxNodes` / `maxEdges` (optional): Traversal bounds (1 to 2,000 nodes, 1 to 5,000 edges) - `offset` (optional): The first reached node to return; nodes are sorted by id **Returns:** Nodes, the edges that leave the returned nodes, `nodeCount` (the nodes reached), truncation flag, and status metadata, cut to the [result size budget](#result-size-budget). **Example:** ```json { "seedIds": ["REQ-cli-gc"], "direction": "both", "depth": 2, "maxNodes": 100, "maxEdges": 200 } ``` ### `kb_sparql_remote` Registered only when `KIBI_MCP_OPTIONAL_TOOLS` names it (or is `all`); the `kibi sparql-remote` CLI route is always available. Run an opt-in SPARQL `SELECT` query against an external HTTP(S) SPARQL endpoint. This tool is remote-only: it does not query Kibi's local RDF store directly, does not start a local SPARQL endpoint, and does not store credentials. **Parameters:** - `endpoint` (required): Remote SPARQL endpoint URL. Must start with `http://` or `https://`; local file paths are rejected. - `query` (required): SPARQL `SELECT` query text. - `timeoutMs` (optional): Positive timeout in milliseconds for the remote request. **Returns:** Rows returned by the remote endpoint, serialized as structured MCP content. Network availability, endpoint rate limits, and remote endpoint authentication requirements are outside Kibi's control. **Example:** ```json { "endpoint": "https://query.wikidata.org/sparql", "query": "SELECT ?item WHERE { ?item wdt:P31 wd:Q146 . } LIMIT 5", "timeoutMs": 15000 } ``` ## Internal Prolog Implementation Notes Kibi's Prolog core may use maintained SWI-Prolog libraries such as `library(aggregate)` for count/reporting helpers and `library(chr)` for isolated derived-fact pilots. These are internal implementation details and do not change public KB semantics, MCP response shapes, or the canonical validation rules unless a future release explicitly documents such a change. ### `kb_upsert` Create or update a single entity and optional relationships in one call. When the caller has a filesystem-capable context, the mutation is source-first: the tracked entity document and relationship shard are authored transactionally, then the compiled branch store is updated. Kibi never stages or commits those working-tree files for Git. **Parameters:** - `type`: Entity type enum - `id`: Entity ID - `properties`: Entity fields, including required `title` and `status` (status values depend on entity type; legacy values may still be accepted for compatibility). For `symbol` entities this may include `sourceFile`, `symbol_role`, and `granularity_reason`; for `fact` entities this includes typed fact fields such as `fact_kind`, `subject_key`, `property_key`, `operator`, `value_type`, and one matching `value_*` field. - `relationships` (optional): Relationship rows with enum-backed `type`, `from`, and `to` - `dryRun` (optional, default `false`): Validate the payload and write nothing. See [Dry run](#dry-run-validation). - `implementedBy` (optional, `req` only): `[{ sourceFile, symbol, coveredBy? }]`, the code that implements the requirement and, in `coveredBy`, the tests that cover it. See [Linking code while writing a requirement](#linking-code-while-writing-a-requirement). - `why` (optional, `req` only): why the requirement exists, in the words of the person who asked (`Reason not stated` when they gave none). See [Recording a rule with its reason](#recording-a-rule-with-its-reason). - `document` (optional): `{ path?, body? }` for an explicit tracked source target. Existing entities preserve their current body when `body` is omitted; new requirements default the body to `semantic_text`. New entities without a unique configured target must provide `document.path`. Updating an existing Markdown document rewrites only the frontmatter keys whose value changes (new keys are appended); every other key keeps its authored bytes, including quoting, unquoted timestamps, flow lists and indentation. `symbol_role` values are `behavioral`, `structural`, `type-shape`, `config`, `module`, and `unknown`. Use `behavioral` for manual anchors when behavior is hidden inside factory/expression composition and the extractor cannot create a narrower symbol. `properties.origin` (optional, every type) records provenance: `{kind: human|agent|migration|import, ref?, approved_by?, recorded_at?}`. A new entity written without it is recorded as `{kind: agent, recorded_at: }` (a dry run validates a supplied origin but does not add the default to `normalizedPreview`). An update without it never changes the stored origin, and an entity that has none keeps none. A supplied origin is written as given; a missing `recorded_at` gets the write time. See `docs/entity-schema.md#entity-origin`. `properties.firmness` (optional, `req` and `adr` only) is `firm`, `default` or `exploratory`; absent reads as `default` when the entity's `origin.kind` is `agent` (a new entity written without `origin` is recorded as `agent`) and as `firm` otherwise. A `firm` write needs `origin.ref` (or `approval_ref` on a requirement) pointing at the human words that state the rule, or it is rejected. A write that changes the title, stated meaning, ADR body or firmness of a current firm decision is rejected unless it cites new human words (a changed `origin.ref`, or `approval_ref` on a requirement); supersede the decision instead when the person agreed to a replacement. See `docs/entity-schema.md#decision-firmness`. For current requirement writes with assertive prose, mutation fails closed unless the requirement carries the complete advisor ledger and source contract. Kibi derives the mechanical part of the ledger, and the writer supplies only its judgment. When the check below would refuse a requirement write that sends none of `semantic_inventory_version`, `semantic_source_field`, `semantic_source_hash` and `logic_claims`, Kibi records the ledger the advisor derives from the prose: a claim is `modeled` only when one of the write's `requires_property`, `requires_predicate` or `requires_rule` links targets a fact with its `claim_key`; otherwise it keeps the `status` and `subjects` the write's own `semantic_inventory` entry gives that `claim_key` (send `{claim_key, status, subjects}` for the claims you classify), else those the stored ledger gives it, else `missing`, which records that nobody classified it (context sentences stay `nonlogical`). An entry whose `claim_key` the prose does not state is refused, since it was written for other prose. Every check then judges the derived write as if it had been sent, so a `modeled` entry without its link, or a link that grounds no claim, is still refused. The result's `inventoryApplied` lists each recorded claim (`claim_key`, `role`, `status`, `claim_text`, and `advisor_status` when the advisor reads a `missing` claim as `ambiguous` or `ontology_gap`); `kb_validate_upsert` and `dryRun` report the same. A write that sends any of the four scalar fields is judged exactly as sent, and a write the check accepts is never changed. A relationship-only update of an existing requirement does not need to resend the ledger: when the payload carries no `semantic_*` or `logic_claims` field and any `title` or `text_ref` it sends equals the stored value, Kibi merges the stored ledger (`semantic_text`, `semantic_clauses`, `semantic_inventory`, `semantic_inventory_version`, `semantic_source_field`, `semantic_source_hash`, `logic_claims`) and the stored `text_ref` when the payload omits it under the payload, then runs the proposition-complete check on the merged requirement. For example, `{"type":"req","id":"REQ-x","properties":{"title":"","status":"open"},"relationships":[{"type":"specified_by","from":"REQ-x","to":"SCEN-x"}]}` links a scenario and keeps the ledger. A payload that supplies any ledger field, or changes `title` or `text_ref`, is checked exactly as sent. An update of a stored requirement is also checked as its authored file will read after the write: the stored status, prose and ledger with the payload's fields on top. When that requirement is current (`open`, `in_progress`, `closed`, `active`, `approved`) and lacks a complete ledger, the update fails with `Proposition-complete ingestion failed: would be written as a current requirement without a complete proposition inventory (...)`, the error `kibi sync` would otherwise report later; for example `{"status":"closed"}` on a `draft` requirement that never had an inventory. Supply the inventory contract that `kb_model` mode `analyze` returns for the requirement's id and complete `semantic_text` in the same write, or retire the requirement through a superseding one. A requirement that was already current with the same prose keeps accepting updates that change neither. When the store does not hold the entity but the file the write would merge into exists and declares it (a file `kibi sync` could not extract, or one written since the last sync), that file's front matter is the stored state for these checks, so the write is judged as an update of what the file says; a write that would leave the file uncompilable is refused with `Upsert of refused: exists in but is not compiled (...)`, naming the extraction error, and a successful one returns a warning that it updated that file. The `Proposition-complete ingestion failed` error ends with that contract as JSON (`semantic_inventory_version`, `semantic_source_field`, `semantic_source_hash`, `semantic_inventory`, `logic_claims`), keeping any inventory status the payload set for the same `claim_key`, so merging it into `properties` and resending needs no separate `kb_model` call. Every assertive claim key must appear exactly once in `logic_claims`; every `modeled` entry must have exactly one logical relationship whose target fact carries that same key. Explicit unresolved statuses are accepted as honest inventory states but do not make the requirement proof-complete. **Returns:** Confirmation of entity creation/update and relationship creation counts. Successful responses may also include `structuredContent.semanticAdvisor` (requirements only) and `structuredContent.warnings`. Modeling suggestions remain reviewable, while proposition accounting and source/grounding integrity are blocking for applicable requirement writes. A `symbol` payload with an `implements` edge but neither `covered_by` nor `executable_for` (and no `covered_by` edge already stored for that symbol) returns a warning, on `dryRun` and on the write, that `kb_check` will report `symbol-coverage` until the symbol gets `covered_by` to a test that covers the requirement. #### Linking code while writing a requirement `implementedBy` records the requirement and the `implements` links to it in one call, so a requirement written from finished work does not need a separate symbol upsert per function. Each entry names a workspace-relative `sourceFile` and one declaration in it: a function, a method as `Class.method` (or its bare name when only one class declares it), or an exported constant. Kibi parses the file and resolves the entry to exactly one declaration that the granularity check accepts: - a name the file does not declare is refused with up to ten candidate names; - a bare method name that several classes declare is refused, naming each `Class.method`; - a class whose behavior lives in its methods is refused as a coarse link, naming its methods; - an empty `symbol` is refused, because a whole file is never an `implements` link; - a file outside the workspace, or one that cannot be read, is refused. The resolved declaration's symbol entity gets an `implements` link to the requirement. When the KB already has a symbol with that title and `sourceFile`, Kibi adds the link to it and keeps its status; otherwise it creates one (`status: active`, the inferred `symbol_role`) under the first free id of `SYM--`, `SYM---` and `SYM--`. The requirement and every symbol write are validated before anything is written, and a refusal (`VALIDATION_FAILED`, rule `implemented_by_unresolved`) writes nothing. On `dryRun` the result previews the links without writing them. The result's `implementedBy` lists each entry's `sourceFile`, `symbol`, `symbolId` and `created`. If a symbol write fails after the requirement was written, the error names what was written and gives the remaining symbol payloads to upsert. An entry's optional `coveredBy` lists test ids; each becomes a `covered_by` link from the same symbol, so one call records both links a production symbol needs. Without it, a new symbol still needs `covered_by` to a test (see the `symbol-coverage` warning below). #### Recording a rule with its reason `why` gives the reason one home on the way in and writes it to every place that reads it: the requirement's `rationale` and the reason section of its body. That is its `## Context` section, or an existing `## Why` or `## Rationale` section, which keeps its heading; a body with none gets a `## Context` section after the statement. When the body has no `## Source` section and `origin.ref` is set, the `origin.ref` text becomes one, as a blockquote. An update without `document.body` revises the stored file the same way and keeps its statement and other sections. A `why` that is not text, or one that disagrees with a `rationale` sent beside it, is refused (`VALIDATION_FAILED`, rule `requirement_why_invalid`); `why` on another entity type is refused too. The reason section counts toward `entity-context-missing` like any other: it needs 12 words or more with the Source. A requirement write that sends `document.body` without `semantic_text`, for a requirement with no stored `semantic_text`, records the body's statement (the body without its context sections) as `semantic_text`, so the proposition inventory Kibi fills in is derived from the statement the file holds, not from the title. A committed requirement write then returns what `kb_check` would still block it on and the call could not finish, as `nextActions` entries (`operation`, `code` naming the check rule, a ready `input`, `reason`, `required`), and leaves those warnings out of `warnings`: - `entity-context-missing`: a `kb_upsert` that sends `why`; - `claim-subject-missing`: a `kb_upsert` that sends the stored `semantic_inventory` back with, on each claim without subjects, the closest existing subject by its words (the reason names the other candidates; `` when none matches); - `evidence-floor` and `symbol-coverage`, for a requirement that has no test: a scenario and the `specified_by` link when it has none, a test that validates its scenarios, a `covered_by` link for each implementing symbol without coverage, and, when the requirement's floor is `tested` or `proved` (a firm one), a `kibi prove` step that names the proof contract and steps the test needs. A value only the agent can supply (a reason, the case a scenario decides) is a `` in the input. The result's `relatedRequirements` lists up to five other current requirements whose title and statement share at least two of the written requirement's topic words and at least half of the smaller set, as `{id, statement}`; numbers are not topic words, so a floor of 9 and a new floor of 10 match. If the write replaces one of them, add a `supersedes` link to it and close it. ### Dry run validation A committed fact write that carries `claim_text` returns the stored `claimKey` (derived from `claim_text` when the payload did not supply `claim_key`), so the writer can link `requires_predicate` or `requires_property` and read the key back without a `kb_query`; a dry run shows the same key in `normalizedPreview.claim_key`. Proof-receipt history is append-only: an update of a test that sends `proof_receipts` must keep every stored receipt unchanged and in order. An update that omits `proof_receipts` keeps the stored history (and the stored `verification_scope` and `verification_perspective` when it omits those too), so a test's title or links can change without resending its receipts. Call `kb_upsert` with `dryRun: true` to validate a payload without mutating the KB (catalog operation `kb_validate_upsert`; CLI `kibi upsert` with `"dryRun": true`, or `kibi validate-upsert`). This read-only preflight returns `valid`, `errors`, `warnings`, `semanticAdvisor`, and `normalizedPreview`, plus `dryRun: true` and `skippedEffects: ["kb-write", "workspace-write"]`. With a store attached it runs exactly the validation a real `kb_upsert` runs before its first write: schema, append-only proof receipts, relationship sources and live targets, symbol granularity, strict-lane pairing, supersedes direction, proposition completeness, grounding claim keys and predicate argument vocabulary. It then previews the commit-time contradiction check: the entity and its relationships are staged in a transaction that is always rolled back and the check runs against that staged store, so a payload the commit would refuse with `Contradiction detected … (stage=contradiction_check)` is reported `valid: false` with the same message (`_skipContradictionCheck` skips the preview as it skips the commit check). For a `req` the check is `check_req_contradiction`; for a `fact` it refuses a write that makes two current requirements grounded on the fact contradict where they did not before (see `docs/inference-rules.md`, Writes the contradiction check refuses). A value fact payload that changes the fact's value, or creates it, also returns `siblings` and `nextActions`, as the write does. A dry run therefore rejects what the write would reject as far as the store can tell. It writes nothing, so it cannot report what only a write reveals: `DOCUMENT_PATH_REQUIRED`, filesystem, lock and pending-receipt failures, a concurrent writer, or findings of `kb_check`-only rules such as `logic-coverage` and `scenario-feasibility`. Without a store it runs only the store-independent checks. A payload the dry run finds invalid makes the envelope an error (`status: "error"`, MCP `isError: true`, CLI exit code 1) with code `UPSERT_DRY_RUN_INVALID`, whose message carries the validation errors; `data` still reports `valid: false`, `errors` and `dryRun: true`, and both write effects are `not_applicable`. The symbol granularity check judges the symbol as it will be stored: a payload that only adds `implements` or `covered_by` links to an existing symbol is checked against the stored `sourceFile` and `granularity_reason`, and a class-level symbol whose public members are behavioral symbols is refused as coarse, as the staged hook and `kibi check` (`symbol-granularity`) refuse it. `semanticAdvisor` describes requirement prose, so it is `null` on the preflight of any other entity type (and absent from its write result): analysing a fact's title would report claim keys nothing declares, while the fact's own `claim_key` is in `normalizedPreview`. A committed `kb_upsert` reports only its verdict (version, payload hash, inventory contract, logic readiness, candidate lane, logic coverage, suggested next tools and summary). On a preflight it includes a version, payload hash, source-bound inventory contract, proposition ledger, logic readiness, candidate lane, detected signals, ambiguity witnesses, modeling suggestions, and suggested next tools. A valid preflight proves source accounting at the ingestion boundary; contradiction checks and proof evidence are still separate proof stages. `plannedFacts` (dry run only) stages fact writes that have not happened yet: pass the `applyPlan` entries `kb_model` returned (`type`, `id`, `properties`, optional `relationships`). The planned facts are validated in order, each against the KB plus the facts before it, exactly as `kb_apply_plan` validates a plan's steps, so the payload's `requires_predicate` or `requires_property` target resolves and its `claim_key` is read from the plan instead of failing with `logical grounding target … must declare a claim_key`. The contradiction preview then stages the planned facts and the payload together in one rolled-back transaction and compares the witnesses with the current KB's: a contradiction or infeasible scenario the batch would introduce is refused with `Contradiction detected for requirement … (stage=contradiction_check, plannedFacts staged)` and the witness reason (for example `Decision conflict on default:permission_rule(coach,read,unassigned_analysis_request)`); otherwise the result adds `stagedFacts` (the planned ids in order) and `whatIf` (`introduced`, `removed`, `unchanged` witnesses). A planned entry that is not a `fact`, reuses the payload's id or fails its own validation is reported as `planned fact is invalid: …`. `plannedFacts` on a real write is rejected: write the facts first, with `kb_upsert` or the `kb_model` plan through `kb_apply_plan`. When invoked through MCP, the dry run also attaches to Prolog and validates live relationship endpoint types before mutation. Invalid tuples such as `verified_by fact -> test` are rejected in preflight with the same relationship guidance `kb_upsert` would return. ### `kb_record` Record a rule the way it was stated, in one call. `kb_record` takes the rule and turns it into exactly one `kb_upsert` payload, which goes through the same schema validation, semantic advisor, firmness and approval checks and write path as a hand-written `kb_upsert` call; nothing is relaxed or defaulted past a check. It then runs `kb_check` with `changed: true` for the files the code names and returns that verdict. CLI: `kibi record --input -`. **Parameters:** - `statement`: the rule as one testable sentence. It becomes the body and `semantic_text`; its first sentence, cut to 100 characters, is the title. - `why`: why the rule exists, in the words of whoever stated it (`Reason not stated` when they gave none). Sent as `kb_upsert`'s `why`. - `saidBy`: `user` or `maintainer` (a `firm` requirement of `human` origin) or `agent` (a `default` requirement of `agent` origin). - `quote` (optional): their words, recorded as `origin.ref`. A firm rule needs one, so a `user` or `maintainer` rule without it is refused by `kb_upsert`'s firmness check. - `code`: `[{ file, symbol }]`, the declarations that implement the rule, sent as `implementedBy`. - `test` (optional): an existing test id, recorded as the requirement's `verified_by` link and as each symbol's `coveredBy`. - `dryRun` (optional): return the payload and `kb_upsert`'s dry run; write nothing and run no check. The requirement is always new and `open`: its id is `REQ-` and the first six words of the statement that are not filler, numbered from `-2` when that id is taken. `kb_record` never writes `origin.approved_by`. Any other field (facts, relationships, proof contracts, an update of an existing entity) is refused with `VALIDATION_FAILED` (rule `record_field_unsupported`), naming `kb_upsert` as the call that records it. A payload `kb_upsert`'s schema refuses is refused before anything is written, with its errors. **Returns:** `id`; `upsert`, the payload sent; `written`, `kb_upsert`'s result; `verdict`, the `kb_check` `changed: true` result (`commitAllowed`, each finding with `blocks`); `commitAllowed`; `status` when the write needed repair; and `nextActions`, the steps `kb_upsert` returned (a scenario, a test, a claim subject, `kibi prove`). On `dryRun` it returns `id`, `upsert`, `preview`, `valid`, `errors` and `dryRun: true`. If the check fails after the write (in a workspace without git, for example), the call still succeeds with the write and no `verdict`: `verdictError` says the requirement was written, not to record it again, and which `kb_check` call gives the verdict. A derived id whose requirement file already exists, compiled or not, gets the next `-2`, `-3` suffix. The result is the same as `kb_upsert` of `upsert` followed by `kb_check` with `changed: true` for the same files: the same entities, relationships and verdict. ### `kb_review_firm_edit` Record the agent's verdict on its change to code that implements a current firm requirement. `kibi check --staged` and `kb_check` with `changed: true` block such a change (`firm_edit_unreviewed`) until every edited symbol has a current `keeps` receipt, and the finding names this tool with the exact input to send. Listed in every tool profile. CLI: `kibi review-firm-edit --input -`. **Parameters:** - `reviews`: `[{ requirementId, sourceFile, symbol, verdict, note, requestQuote? }]`. `verdict` is `keeps` (the change still does what the rule says) or `changes` (it does not); `note` says why in one line. - `dryRun` (optional): validate every entry and write nothing. - `staged` (optional): read the code and the requirement from the Git index, as the commit gate does. Each entry writes a receipt under `.kb/firm-edit-reviews//`, bound to the requirement's statement and the symbol's code; stage it with the change. A `keeps` receipt clears `firm_edit_unreviewed` for that symbol, and a `changes` receipt turns it into `firm_edit_breaks_rule`, which blocks until the requirement is superseded with the person's words. A receipt is the agent's judgment, never the person's approval, and `kibi signoff` lists it as such. Input rules, receipt matching and examples are in the CLI reference under `kibi review-firm-edit`. ### `kb_delete` Delete one or more entities by ID, or retract exact relationship triples. The two modes are mutually exclusive. Relationship deletion preflights the whole batch, preserves endpoints and unrelated edges, and handles legacy relationship shards through Kibi internals. **Parameters:** - `ids`: Array of entity IDs to delete - `relationships`: Array of exact `{type, from, to}` triples to retract - `dryRun` (optional): Preview the delete and write nothing (see below). - `approvedPlanHash` (optional, `ids` only): Apply the authored-entity deletion plan whose `planHash` this is, in the same call (see below). Not allowed with `relationships` or `dryRun: true`. Provide exactly one non-empty array; `ids` and `relationships` cannot be mixed. **Returns:** A direct delete returns `deleted`, `skipped` and `errors` (per-id failures such as a missing entity or one with dependents); a relationship delete adds `relationships_deleted`, per-selector `relationship_results`, and `sourceWrites` when a canonical shard or authored source was patched. Never edit `.kb/relationships` directly. Any call that is not a direct delete carries an `outcome`: | `outcome` | When | What to do next | | --- | --- | --- | | `plan_returned` | An id is authored in a Markdown or YAML source. Nothing is written: `deletionPlan` is a hash-bound `kibi.entity-deletion-plan.v1` and `skippedEffects` lists `kb-write` and `workspace-write`. | Review the plan, then run `nextActions[0]`: `{operation: "kb_apply_plan", input: {plan, approvedPlanHash}, required: true}`. Pass `input` unmodified. Or repeat the `kb_delete` call with `approvedPlanHash: deletionPlan.planHash`. | | `supersession_required` | An id is an authored requirement. Requirements evolve append-only and are never deleted; nothing is written. | `nextActions[0]` is a `kb_upsert` template: upsert a replacement requirement with a `supersedes` relationship to the old one, then upsert the old requirement with `status: closed`. | | `plan_applied` | `approvedPlanHash` matched the freshly computed plan. | The plan went through `kb_apply_plan`'s validation, journal and recovery path. `deleted`, `planHash`, `sourcePaths` and `recoveryJournalId` report what changed; `status: committed_with_repairs` with a `kb_apply_plan` recovery `nextActions` entry means the compiled retraction needs repair. | | `dry_run` | `dryRun: true` on a relationship or direct entity delete. | Nothing is written. `wouldDelete` counts what a commit would remove (`entities` and `ids`, or `relationships` and `compiledEdges`), `sourceWrites` lists the shard and authored-source writes with their before and after hashes, and `relationship_results` describe the planned effect per selector. | `errors` lists only real per-id failures. A returned plan is not an error, and the call reports `status: "success"`. An id that was resolved but not covered by the plan (a non-authored id in the same call as authored ones) is listed in `errors` and must be deleted in a separate call. `dryRun: true` on authored ids returns the same plan as without it, with `dryRun: true`, since that path never writes. `approvedPlanHash` recomputes the plan from the current sources and applies it only when its hash still equals the approved one. A different or stale hash fails with `DELETE_PLAN_HASH_MISMATCH` and writes nothing. A plan that requires supersession fails with `REQUIREMENT_SUPERSESSION_REQUIRED`. Approval also fails (`VALIDATION_FAILED`) when an id was not resolved into the plan, or when no id produced an authored plan. ### `kb_check` Run KB validation rules after mutations. Agents can also opt into read-only changed-file impact diagnostics for source edits while the edit context is still fresh. The MCP tool and CLI JSON route are peer interactive gates; CLI staged checks and git hooks remain the commit-time enforcement gate. **Parameters:** - `rules` (optional): Validation rule subset. The allowed names are maintained in `packages/core/schema/rule-registry.json` (single source for the tool schema, the TS rule registry, and the Prolog check dispatch): `must-priority-coverage`, `symbol-coverage`, `symbol-traceability`, `no-dangling-refs`, `source-relationship-parity`, `branch-store-not-compiled`, `source-path-dangling`, `no-cycles`, `required-fields`, `deprecated-adr-no-successor`, `superseded-requirement-open`, `scenario-feasibility`, `scenario-feasibility-unknown`, `exception-claim-keys`, `numeric-string-value`, `rule-key-arguments-missing`, `domain-contradictions`, `logic-coverage`, `rule-safety`, `rule-verifiability`, `query-plan-safety`, `req-status-vocabulary`, `retired-reason-missing`, `retired-owner-only`, `strict-fact-shape`, `strict-req-fact-pairing`, `predicate-verifiability`, `strict-readiness`, `semantic-completeness`, `related-requirement-unmodeled`, `quantity-duplicate`, `proof-contract-symbols`, `entity-id-style`, `domain-redundancy`, `domain-implication`, `subject-key-identity`, `subject-key-shape`, `ontology-quality`, `exception-unapproved`, `exception-approval-self-attested`, `agent-requirement-unapproved`, `requirement-rationale-missing`, `entity-context-missing`, `entity-context-acknowledged`, `decision-firm-unreferenced`, `decision-firm-superseded`, `decision-firm-edited`, `supersedes-reason-missing`, `supersedes-reason-acknowledged`, `symbol-owner-superseded`, `adr-unlinked`, `adr-proposed`, `predicate-schema-conformance`, `policy-ownership`, `policy-markers`. Canonical rules populate blocking `violations[]`. `must-priority-coverage` counts only current must-priority requirements: one that another requirement supersedes, one with a retired status, or one `closed` without the `implemented` tag owes no scenario or test (see `docs/inference-rules.md`). When the current branch's store was never compiled (missing, or empty at journal sequence 0) while `.kb/` holds authored sources, `kb_check` returns only the `branch-store-not-compiled` violation, naming `kibi sync`, plus a `migrationPlan` whose automatic `branch-store-compile` action runs it; every other rule would read an empty KB. The vocabulary-convergence rules (`entity-id-style`, `domain-redundancy`, `subject-key-identity`, `subject-key-shape`, `predicate-schema-conformance` as warnings; `domain-implication`, `ontology-quality` as info) are advisory, run by default, and report non-blocking `qualityDiagnostics` whose `evidence.witnesses` carry exact requirement IDs, fact IDs, and signatures; see `docs/cli-reference.md` for their precise definitions. `kb_check` never imports capability plugins, so these results are deterministic and offline. `policy-ownership` and `policy-markers` are canonical but inert unless a package is activated for `kibi.check-policy.v1` (such as the experimental `kibi-plugin-ui`); Kibi then reads that package's policy JSON as data and blocks production symbols in the policy's file set that implement no current requirement grounded in its predicates (`policy-ownership`), and implementing files that lack a marker the KB declares for their requirement's pattern (`policy-markers`). An activated policy that cannot be read blocks under the first selected policy rule. `domain-redundancy` is suppressed for pairs linked by `supersedes` or `restates`. `req-status-vocabulary` rejects requirement statuses outside the canonical+legacy vocabulary (`open`, `in_progress`, `closed`, `retired`; legacy `active`, `approved`) — e.g. ADR vocabulary such as `accepted` compiles but silently falls out of the proof ladder. `retired-reason-missing` blocks a `retired` requirement without `retired_reason`, and `retired-owner-only` blocks a current fact, scenario or test whose every owning requirement is retired (see `docs/entity-schema.md`, Retired requirements). `scenario-feasibility` blocks on a success scenario whose assumed values cannot hold, alone or together, with what the current requirements governing it require through `requires_property` facts or typed `requires_rule` rules, within each constraint's scope and validity window (each witness names a minimal set of requirements, assumption facts and requirement facts), unless an exception requirement with a non-empty `approved_by` exempts the requirement (only the clauses in its `exempts_claims`, when set); `scenario-feasibility-unknown` is advisory and lists success scenarios whose feasibility cannot be decided (no `assumes`, assumptions that contradict each other, an assumed property no governing requirement constrains, a type, unit or operator that cannot be compared, governing requirements with no common value, a governing rule the assumptions neither satisfy nor refute, or a conflict only with constraints whose validity window may not cover the scenario). `exception-claim-keys` blocks on an exception whose `exempts_claims` names a key that is not a claim of a requirement it exempts. `numeric-string-value` is advisory and lists `property_value` facts that store a plain decimal as `value_type: string` where the comparison is numeric, since strings are never coerced and such facts drop out of contradiction and feasibility checks. `exception-unapproved` (an exception that `exempts` a requirement but has no `approved_by`), `exception-approval-self-attested` (an agent-authored exception whose `approved_by` is not corroborated by `origin.approved_by` and `approval_ref`) and `agent-requirement-unapproved` (info; agent-authored current requirements without `origin.approved_by`, at most 25 per check plus one summary) are advisory approval checks. `superseded-requirement-open` blocks a requirement that another requirement `supersedes` unless its status is `closed`, and reports requirements that supersede each other (directly or through a chain) once per cycle, naming every member; `no-cycles` follows only `depends_on`. `source-path-dangling` blocks an authored `source` field that names neither an existing workspace path (a `#anchor` suffix is ignored), an existing entity id, nor an http(s) URL; a missing `source` is allowed. The authored field is dead data (the compiled `source` is always the entity's own file and `kb_upsert` never writes the field), so each finding names its automatic fix: `evidence.rewrite` for a pre-canonical `documentation//...` or `/...` value whose file exists under `.kb//` and is not the entity's own file, otherwise `evidence.remove` (`self` for a value naming the entity's own file, `dangling` for one Kibi cannot map), plus `evidence.refused` when the edit is not safe. It also blocks a `text_ref` shaped like one workspace file path that names no file (`evidence.field: text_ref`); such a value is rewritten only to a moved `.kb/` file and is otherwise refused for a person, never removed. The migration plan turns superseded requirements into a `close_superseded_requirements` automatic action plus one `review_supersession_cycle` per cycle, and dangling sources into the automatic `source_path_rewrite` action (whose evidence lists `rewrites` and `removals`); only a value with `evidence.refused` becomes a `review_source_path_dangling` review. `symbol-owner-superseded` (a symbol whose every `implements` target is superseded, deprecated or retired; at most 25 per check plus one summary), `adr-unlinked` (an accepted ADR no requirement or ADR links with, in either direction), `adr-proposed` (info: an ADR still `proposed` and not superseded) and `requirement-rationale-missing` (a current requirement with `origin.kind` `human` or `agent` and no `rationale` field, no `## Rationale`/`## Why` section and no ADR link; at most 25 per check plus one summary) are advisory lifecycle checks. `entity-context-missing` is canonical and blocks a current `req`, `scenario`, `test`, `adr` or observation/meta `fact` with no body context (see `docs/entity-schema.md`, Body contract); `entity-context-acknowledged` (info) counts the entities the schema 8 migration acknowledged (tagged `review:context-missing` and listed in `.kb/manifest.json`); the tag on any other entity is a violation. `kb_upsert` returns the same finding as a warning, including on dryRun. `decision-firm-unreferenced`, `decision-firm-superseded`, `decision-firm-edited` and `supersedes-reason-missing` are canonical (KB schema 9): a current requirement or ADR marked `firmness: firm` must cite the human words it rests on (`origin.ref`, or `approval_ref` on a requirement; `kb_upsert` rejects such a write up front), only a firm decision may supersede a firm one (retired superseders included; from KB schema 10 a decision without `firmness` is firm unless an agent wrote it, and the supersedes of such decisions recorded earlier are acknowledged in `.kb/manifest.json` `firmSupersedeAcknowledged`), a current decision that was firm at `HEAD` must not have its claim (title, stated meaning, recorded reason, `## Source` section, an ADR's body, or its firmness) changed, or be retired or reopened, in the working tree unless the edit cites new human words (`kb_upsert` refuses such a write up front, dryRun included), and a current superseding requirement or ADR needs a `## Why this changed` section of at least 12 words; `supersedes-reason-acknowledged` (info) counts the decisions whose supersede edges the schema 9 migration acknowledged in `.kb/manifest.json`; Kibi cannot verify that a reference points at a real person's words (see `docs/entity-schema.md`, Decision firmness). `subject-key-identity` also reports one subject or claim minted as several active facts (the same `subject_key`, or the same `subject_key`, `property_key`, `operator`, `polarity` (absent means `require`), typed value and `unit`; facts linked only by superseded or deprecated requirements are not counted), and `subject-key-shape` also reports property keys that number a clause (`clause_03_...`). `rule-key-arguments-missing` is advisory and names, for each opposing rule pair that is `unresolved` only because a condition predicate declares no `key_arguments`, the predicate (`namespace:name/arity`) and the key positions that would decide the pair. `strict-fact-shape` is a canonical blocking check as of schema 7. `strict-req-fact-pairing`, `predicate-verifiability`, and `proof-contract-symbols` are advisory modeling checks: they run by default and report as non-blocking `qualityDiagnostics`. A requirement that `constrains` a subject fact is paired either by a `requires_property` fact on the same `subject_key` or by a `requires_predicate` fact about that `subject_key` (the grounding a `replace_grounding` plan leaves): the predicate fact's own `subject_key`, else the argument its project-local `predicate_schema` names `subject` (any position), else its first argument when neither is declared, so `strict-req-fact-pairing` and `strict-readiness` report neither. `proof-contract-symbols` reports unresolved `required_proofs.symbol_id` values, type-shape required proofs, and `proof_bindings.source_file` disagreement with the named symbol `sourceFile`; Kibi does not infer TEST names from filenames. Migration diagnostics (`strict-readiness`, `semantic-completeness`) run only when explicitly selected. `related-requirement-unmodeled` is canonical and blocks a current requirement whose ledger still has `status: missing` propositions while it `relates_to` (either direction) a current requirement modeled with strict property or ground predicate facts; the finding names the modeled keys and asks for those propositions to be modeled against them or for a `supersedes` decision (requirements without a ledger, classified ledgers, unmodeled neighbours and superseded neighbours are not reported). `quantity-duplicate` is canonical from KB schema 19 and blocks two value facts of current requirements that state one quantity under different keys, unless either lists the other under `distinct_from` (see `docs/inference-rules.md`, One quantity under two keys); `kb_upsert` returns the same pairing as a `quantity-duplicate:` warning, including on dryRun, and names the twin a value change leaves stale. `logic-coverage` is enabled by default, validates explicitly declared requirement manifests against linked ground facts, and leaves requirements without a manifest as gradual-backfill debt reported by quality diagnostics. `domain-contradictions` compares strict property constraints and exact opposite predicate polarities over the same namespace, predicate name, and ordered arguments. It does not infer arbitrary equivalence between differently shaped predicates. - `sourceFiles` (optional): Repo-relative source paths to inspect for changed-file impact diagnostics. Without `rules`, it also scopes the result to those files (see below). - `includeMigrationPlan` (optional): With `sourceFiles`, return the full `migrationPlan` instead of `migrationPlanSummary`. - `offset` (optional, default `0`): With `rules`, the first finding to list; a rule selection lists its findings in pages within the [result size budget](#result-size-budget). - `staged` (optional): Inspect staged source changes when building impact diagnostics. - `changed` (optional): When `true`, give the commit gate's verdict on every current change before anything is staged: the call runs `kibi check --changed` (the `kibi check --staged` gate over the index plus the working tree, judged on a scratch copy of the index so the real index is never written) and returns `changed: true`, `commitAllowed`, `violations`, `diagnostics`, `qualityDiagnostics`, `messages` and, when the gate printed them, `staged`, `ownerFindings` and `operationalError`. With `sourceFiles`, only those files and `.kb` are added on top of the index. It runs as a child process, so the server's own environment never changes. - `includeWorkingTreeDiff` (optional): Include unstaged working-tree content/diffs for the supplied `sourceFiles`. - `includeImpactDiagnostics` (optional): Include changed-file diagnostics such as `symbol_granularity_violation`, `symbol_semantic_review_needed`, `source_file_unowned` and `requirement_statement_unverified` in structured output. - `maxDiagnostics` (optional): Cap returned impact diagnostics. Graph validation violations are not capped by this value. - `workspaceRoot` (optional): Workspace root for impact diagnostics. Defaults to the MCP server workspace. - `async` (optional, default `false`): Start the check as a background job and return a `kibi.job.v1` receipt (`jobId`, `status: "running"`, `pollWith: "kb_job_status"`) immediately instead of holding the request until the tool timeout. Use for full checks on large KBs that would exceed `KIBI_MCP_TOOL_TIMEOUT_MS`. This needs the opt-in `kb_job_status` tool (`KIBI_MCP_OPTIONAL_TOOLS=kb_job_status`); without it, `async: true` is ignored and the check runs synchronously. Poll `kb_job_status` until `status` is `succeeded` (full result under `result`) or `failed` (error under `error`). Jobs are process-local: they are not persisted and are dropped on server restart. **Returns:** Validation report with any hard violations found and suggested fixes. `structuredContent.evaluated` says what the run evaluated: `ruleCount`, the number of rules that ran; `rules`, their names, only when some default rule did not run (a `rules` selection, only `branch-store-not-compiled` when the branch store was never compiled, none when `rules: []`); and for `domain-contradictions` `domainContradictions.factPairsExamined`, the number of distinct pairs of requirement facts the rule compared (strict property facts of two current requirements on the same subject and property, predicate facts with the same namespace, name and arguments, and decision facts agreeing on every key argument). The text summary repeats it, so "No violations found" over zero pairs reads as nothing to compare, not as consistency. `structuredContent.violations[]` is the blocking correctness lane: graph, schema, contradiction, query-plan, and staged enforcement failures live there and continue to drive `count` and failure status. `structuredContent.qualityDiagnostics[]` is the additive audit-quality lane for non-blocking modeling, coverage-depth, symbol fanout, duplicate-coordinate, broad-requirement, status, strict-fact, and telemetry-acceptance review signals. Rule filtering affects the audit-quality lane. When `rules` is omitted, MCP runs the normal full validation profile and also performs the full-KB audit-quality scan that populates `qualityDiagnostics[]`. When `rules` is supplied, MCP preserves the requested scoped validation and skips that full-KB advisory scan so iteration stays fast and predictable. Source impact diagnostics are independent: pass `includeImpactDiagnostics: true` with `sourceFiles` or `staged: true` when you need changed-file review during a filtered check. When `sourceFiles` is supplied, `qualityDiagnostics[]` lists only the advisory findings that concern those files (findings on the files, on their symbols, or on the entities those symbols link to); the KB-wide rest is reduced to one `scoped_check_omitted_quality` info diagnostic with per-rule counts. Run `kb_check` without `sourceFiles` for the full audit. A check scoped to `sourceFiles` (without `rules`) also scopes its blocking `violations[]`. It lists the violations on an entity a changed symbol links to (or on those symbols), on an entity whose `.kb/` document differs from `HEAD` (staged, unstaged or untracked: the agent's own writes), on a relationship with either end among those, or whose source is a checked file, and every store-level violation (`branch-store-not-compiled`, `kb-consistency`, `source-relationship-parity`, or one without an entity). The rest are counted in `omittedViolations` (`total`, `byRule`); `count` still includes them, the text summary says they still block the unfiltered check, and such a result never reads as a pass. The migration plan is still built from every violation but is returned as `migrationPlanSummary` (hash, status, counts, action counts by code and up to ten blocked action ids) unless `includeMigrationPlan: true`. A scoped result larger than 24,000 characters is cut to that budget and marked `truncated: true` with a `truncation.hint`: advisory `qualityDiagnostics` are reduced to one `check_quality_truncated` count first, then blocking violations past the budget are listed in `violationGroups` by rule, count and up to 20 entity ids. Impact diagnostics are never cut. `kibi check --staged` lists every finding in full. A `kb_check` with neither `rules` nor `sourceFiles` also returns `symbolDebt` (`total` and `fileCount`): the declarations without a `.kb/symbols.yaml` record in source files that have at least one record, and the files holding them. `includeSymbolDebt: true` adds `files[]` with each `path` and its `unrecorded` titles (CLI: `kibi check --symbol-debt`). It never blocks and adds no violation; the staged gate judges those declarations only when a commit adds or changes them. The text summary adds one "Symbol records (not blocking)" sentence when the total is above zero. A `kb_check` without `rules`, with or without `sourceFiles`, keeps its structured result within a 24,000-character budget: advisory `qualityDiagnostics` become counts by id first, then a `migrationPlan` becomes `migrationPlanSummary` (unless `includeMigrationPlan: true`), then blocking findings past the budget are listed by rule and entity id in `violationGroups`. `count` keeps the full number, every blocking rule stays named, and `truncated: true` with `truncation.hint` says the result was cut. A `rules` selection lists its findings in pages within the same budget: it lists the findings that fit from `offset` (default 0), and `truncation` gives `total`, `omitted` and `nextOffset` for the next page. `kibi check --format json` lists every finding. The `symbolDebt` file list, when asked for, lists the files that fit in what the budget leaves and counts the rest in `filesOmitted`. When diagnostic mode has produced `.kb/usage.log`, the unfiltered scan evaluates `kibi.telemetry-acceptance.v1` over its latest 200 events. It ranks advisor/preflight bypasses, edits of requirement-linked files that no lookup preceded (from host hook rows), source lookup misses, stalled proof-gap recovery, receipt gaps, and repeated mutation failures as `category: telemetry` recommendations. Diagnostic callers may supply opaque `session_id` and `actor_id` metadata; when both evidence records expose an identifier, advisor/preflight correlation requires equality and never borrows evidence across an explicit boundary. Stale or incomplete evidence stays `insufficient_evidence`; absence of observable fields is never interpreted as a pass. A missing log is skipped because MCP diagnostic logging is opt-in. Use the CLI-only `kibi usage-metrics --format json --require-acceptance` route when a hard completion gate is required, and `kibi usage-remediation --format json` for exact read-only repair evidence. Every finding carries `blocks`, what it stops: `"commit"` (the commit gate refuses a commit over it), `"merge"` (the full check fails over it, so CI refuses the merge) or `"none"` (advice). An unfiltered or rule-filtered check tags `violations` and `violationGroups` `merge`, blocking `qualityDiagnostics` `merge`, blocking `impactDiagnostics` `commit` and every other finding `none`; a `changed: true` check tags every violation `commit` and every other blocking finding `commit`. The envelope's `diagnostics` restate violations and carry no tag. Quality diagnostics use explicit `severity` and `blocking` fields. `severity: "review"` and `severity: "info"` are advisory and do not fail checks by default; `severity: "warning"` is still non-blocking unless `blocking: true`; `severity: "error"` or `blocking: true` is a hard failure signal. Existing hard violations remain in `violations[]` rather than being downgraded into the advisory lane. When impact diagnostics are enabled, `structuredContent` also includes `impactDiagnostics`, `sourceFiles`, `extractedSymbols`, `linkedEntities`, and `nextActions`. `extractedSymbols` does not repeat each symbol's links; `linkedEntities` lists them with the symbol they come from. A `requirement_statement_unverified` diagnostic quotes the requirement's statement once, in `evidence.statement`. Advice that diagnostics of one kind share (it names the diagnostic's own ids only through its fields) is listed once in `impactAdvice`, and each such diagnostic carries `advice`, its index there, instead of a `suggestion`; a diagnostic with advice of its own keeps its `suggestion`. Each impact diagnostic is returned once: it is in `impactDiagnostics` and not repeated in `qualityDiagnostics`, the `migrationPlan` review action for it carries `evidence.diagnostic` as `{ id, entityId, listedIn: "impactDiagnostics" }`, and the text content writes a suggestion that several diagnostics share once, above their messages. Impact diagnostics follow the same blocking convention: advisory unless their severity is `error` or `blocking` is true. `symbol_granularity_violation` means a changed behavioral symbol has only coarse ownership when a narrower anchor is available and remains blocking. `symbol_semantic_review_needed` can fire even when graph coverage already exists; it tells the agent to inspect whether linked requirements, scenarios, and tests actually cover the changed behavior or UI copy. On a changed behavioral symbol in a file that no manifest symbol links to a requirement, the same warning says no recorded intent covers it and asks the agent to link it to an existing requirement or record a new requirement with a scenario, unless the change leaves behavior unchanged; recording it is part of finishing the change. `source_file_unowned` (`info`) fires for each file named in `sourceFiles` that no manifest symbol links to a requirement, including files Kibi does not extract symbols from (HTML templates): it says that no link does not mean no rule and lists in `evidence.candidates` the current requirements whose titles share the file's path words (layout words such as `src`, `app` and `pages` and file extensions are ignored), or a `kb_search` call when none does. The match is lexical; candidates are to confirm with `kb_query`, not owners. Kibi reports the linked entities and suggested MCP calls, but it does not prove prose semantics. Kibi's rules compare links, coverage and facts, never code with a requirement's prose, so a change that contradicts a requirement can pass them all. For every current requirement a changed behavioral symbol implements (by manifest `implements` link), an impact-enabled `kb_check` emits `requirement_statement_unverified` (`warning`, not blocking): it names the changed symbols, quotes the requirement's `semantic_text` and gives its firmness, and the text summary then opens with "No structural violations found" and the requirement ids instead of "No violations found". A requirement whose own document changed in the same change is left to the firmness and supersede checks; closed, superseded and deprecated requirements are skipped. If the changed code no longer does what a quoted requirement says, the request conflicts with a recorded rule: ask the person before keeping the change. The structured check response also includes `migrationPlan` (`migrationPlanSummary` for a scoped check). Treat its actions as typed evidence, not prose suggestions; apply only ready automatic actions with an explicit hash/action approval through `kb_apply_plan`. **Example:** ```json { "sourceFiles": ["src/app/pages/upload/upload-page.component.ts"], "includeImpactDiagnostics": true, "includeWorkingTreeDiff": true } ``` ### `kb_job_status` Registered only when `KIBI_MCP_OPTIONAL_TOOLS` names it (or is `all`). Poll a background job started by a long-running operation called with `async: true` (`kb_check` and `kb_apply_plan`). This tool is MCP-server-native: jobs live in the server process, so there is no CLI counterpart and no persistence across restarts. **Parameters:** - `jobId` (required): The `jobId` from the `kibi.job.v1` receipt returned by the async call. **Returns:** A `kibi.job.v1` object: `status` is `running`, `succeeded` (full result envelope under `result`), `failed` (error message under `error`), or `unknown` (no such job in this server process). **Example:** ```json { "kb_check": { "async": true } } { "kb_job_status": { "jobId": "job-kb_check-1-9f2a" } } { "kb_apply_plan": { "plan": { "...": "..." }, "approvedPlanHash": "<64 hex>", "async": true } } { "kb_job_status": { "jobId": "job-kb_apply_plan-2-4c1d" } } ``` ## Diagnostic usage log (opt-in) This local log is separate from the anonymous usage statistics described in [Usage telemetry](telemetry.md), and is never sent. Kibi writes no diagnostic log by default. Installing a host plugin, enabling it, or running the MCP server never turns logging on. Until an operator opts in, `.kb/usage.log` is not created and no row is written. Opt in per workspace with either signal: - `--diagnostic-mode` on the MCP command line, when you own that command line. - `KIBI_DIAGNOSTIC_MODE=1` in the server environment, for hosts where a plugin owns the command line. Set it in the host's MCP server `env` block. `KIBI_DIAGNOSTIC_MODE` is shared by every surface: the MCP server, the CLI JSON routes (`kibi --input`), and the Claude Code plugin hooks all honor it, so exporting it once in the environment your agent host inherits covers all of them. The older CLI-only `KIBI_CLI_DIAGNOSTIC_MODE=1` still works. Opting out is removing the signal; no other state persists. While opted in, every row carries `interface`, `host`, `package_version`, and `workspace_root` so rows stay attributable across worktrees, hosts, and Kibi versions. Host plugins set `KIBI_MCP_HOST` for attribution only; it is not an opt-in signal and never enables logging on its own. The same value decides whether the discovery tools repeat their `data` JSON in the text part: `claude-code` and `codex` (or a client that calls itself `claude-code` or `codex-mcp-client` on initialize) get the text summary alone because the host gives the model `structuredContent`, and every other host keeps the JSON copy. `KIBI_MCP_STRUCTURED_TEXT=omit` or `embed` overrides that for any host. CLI rows take `host` from `KIBI_HOST` (or `KIBI_MCP_HOST`) and recognize Claude Code shells; otherwise they record `unknown`. Rows record business arguments and agent-supplied telemetry metadata, and the log stays local to the workspace under `.kb/usage.log`. The host plugin hooks (Claude Code, Cursor, Codex, ZCode, and OpenCode) add rows with `interface: "hook"` under the same opt-in. They record the agent activity around Kibi calls rather than Kibi operations, and every row names its `host` and the host `session_id`, so one session's lookups and edits can be put in order. All hosts write two kinds of row: - `hook_action: "kb_usage"` when a tool call ran a Kibi operation, through MCP or a `kibi ` shell command, with the canonical name in `kb_operation` (`kb_search`, `kb_query`, …); - `hook_action: "edited"` for each source, test, or `.kb/` file an edit tool changed (`path`, `path_kind`), with the requirements the file's symbols implement in `requirement_ids`. Docs, config, and generated paths are not recorded. The Claude Code plugin also records whether a requirement snippet was shown or suppressed and whether the session had used Kibi yet (`kb_used_before`). Hook rows never enter the bounded window of operation events, so a busy editing session never pushes operations out of it. The only metric that reads them is `lookup_before_first_edit`: per host session, did a `kb_search` or `kb_query` run before the first edit of a file with non-empty `requirement_ids`? It is `not_applicable` when no hook recorded such an edit. Counts are only recorded when they can be read. A call whose payload cannot be parsed records `result_count: null` rather than zero, and acceptance metrics treat unreadable counts as insufficient evidence instead of a pass. ## Discoverability - MCP clients discover available tools through `tools/list`. - MCP clients discover available prompts through `prompts/list` and `prompts/get`. - Allowed static values are encoded directly in each tool's `inputSchema` enums. - `kb_upsert` advertises `proof_contract`, `proof_bindings` and `proof_receipts` as one-line stubs, because every session loads the tool list and their full schemas are about 17k characters. Input is still validated against the full contract, and a rejection under one of these fields includes that field's full schema. The `proof` resource of the `kibi-usage` skill (`kb_skills`) explains how to write a proof contract; `kibi upsert --schema` prints the full input schema. - There are no separate runtime listing tools for entity or relationship types. ## Public Prompts ### `/kibi-bootstrap` Interactive onboarding workflow for day-0 KB activation. It guides agents to interview the human about knowledge sources outside the code, call `kb_plan_bootstrap` with the declared sources and cited intent claims, ask at most four further bounded questions when requested by the planner, present the complete hash-bound plan for approval, call `kb_apply_plan` once, and finish with `kb_check`/`kb_status`. ## Branch Behavior - The server attaches to the exact active Git branch name, or `KIBI_BRANCH` when set. Git-valid slash, Unicode, `@`, and `#` names are preserved verbatim. - The compiled store lives at `.kb/branches//` and is verified by a versioned `branch.json`. A missing store is compiled from the current checkout's tracked sources; Kibi never copies another branch store. - Git remains the merge and conflict authority. Unresolved authored-file conflicts block compilation; Kibi does not select merge winners. - Branch KBs are revalidated and updated automatically on branch change—no server restart is required for normal branch operations. - You can override the branch selection by setting `KIBI_BRANCH` before starting the server; the value is validated without normalization. - Branch garbage collection is not part of the public MCP interface. Use `kibi gc` or automation hooks; deleted stores are quarantined before any explicit purge. ### KB Auto-Refresh For same-branch workflows, MCP validates the attached branch KB against filesystem stat metadata before attach-sensitive operations. When MCP detects a KB replacement for the same branch, it triggers a controlled re-attach flow. - The session stores an `attachedBranchStamp` at attachment time. - MCP recomputes the latest branch stamp with `readBranchKbStamp` and compares it with `sameBranchKbStamp`. - If stale, MCP runs a full `refreshAttachedBranchKb` attempt. - For transient refresh failures, MCP retries through `refreshAttachedBranchKbWithRetry`. - If recovery fails, MCP returns a `KbRefreshError` and the operation fails closed. This behavior is important after external branch operations such as `kibi sync --rebuild`, where the branch KB snapshot can be replaced while the MCP process stays running. ## Workspace Routing Hosts start an MCP server once per project and then let the agent work elsewhere, most often in a git worktree. A server that stayed attached to the checkout it started in would answer from another branch, and nothing in the result would say so. Every Kibi tool call is therefore answered from the workspace the caller is working in, decided per call: 1. An explicit `workspaceRoot` argument (every tool accepts it): the absolute path of the directory the call is about. Host plugins with pre-tool hooks (Claude Code, Codex, Cursor, ZCode) fill it in from the agent's current directory; any agent in any harness can pass its working directory. 2. Otherwise the client's MCP roots, when the client declares the `roots` capability: the first root that lies in a Kibi workspace. Roots are cached while the client reports `notifications/roots/list_changed` and asked for per call otherwise. 3. Otherwise the workspace the server is attached to. A different workspace is served by a child `kibi-mcp` started there: the workspace's own project-local install when it has one, so the child matches that branch's code, else this server's entry. Children are pooled (at most four), reused across calls, and retired after ten idle minutes; the first call into a workspace pays its start (one to two seconds) and, for a branch store that was never compiled, the compile that any attach pays. An async `kb_check` started in a child is polled by `kb_job_status` in the same child. A routed call is logged, in diagnostic mode, by the child in that workspace's `.kb/usage.log`. Routing is limited to worktrees of the attached repository (same git common directory), directories under the client's declared roots, and the `KIBI_MCP_ROUTABLE_ROOTS` allowlist (path-delimited). Anything else, a directory no Kibi workspace owns, or a child that fails to start is answered from the attached workspace with a `workspace_mismatch` diagnostic: ```json { "code": "workspace_mismatch", "severity": "warning", "message": "Answered from /repo, not from the requested workspace /other: ...", "detail": { "requested": "/other", "resolved": "/other", "answeredFrom": "/repo", "reason": "not_routable" } } ``` `reason` is one of `pinned`, `not_a_kibi_workspace`, `not_routable`, or `unavailable`. A tool that writes (`kb_upsert`, `kb_record`, `kb_review_firm_edit` and the other writes) is not answered from the attached workspace in these cases: the call fails with an error naming both workspaces and the reason, so a record or receipt never lands in the wrong knowledge base. A successful route adds nothing to the result; the tool list is always the attached server's. `KIBI_WORKSPACE` (or `KIBI_PROJECT_ROOT`, `KIBI_ROOT`) pins the server to one workspace and disables routing; `KIBI_MCP_ROUTING=0` disables it without pinning. Host plugin launchers set `KIBI_MCP_ATTACH_ROOT` to the session's workspace and start the server there; unlike the pinning variables it leaves routing enabled. Routed children run with `KIBI_MCP_ROUTED=1` and never route further. For `kb_check`, a `workspaceRoot` that no Kibi workspace owns keeps its older meaning: the tree to inspect for impact diagnostics. The CLI JSON routes do not take `workspaceRoot`; they run in the current directory, which makes them the fallback when a result reports a mismatch. ## KB Dependencies A project can read the knowledge bases of other repositories it depends on, such as a library it calls or the other services that share a user journey, without mixing them into its own KB. The read tools `kb_search`, `kb_query`, `kb_status`, `kb_find_gaps`, `kb_coverage` and `kb_graph` accept a `kb` argument: the name of a dependency declared in `.kb/dependencies.json` and pinned in `.kb/dependencies.lock.json` (see [`kibi deps`](cli-reference.md#kibi-deps-lockfetchstatus)). ```json { "query": "how are refunds approved", "kb": "billing-service" } ``` The call is answered by that repository's own KB at the pinned commit: - The pinned commit is fetched once into a shared cache (`$KIBI_DEPENDENCY_CACHE`, else `$XDG_CACHE_HOME/kibi/dependencies`, else `~/.cache/kibi/dependencies`) as a detached checkout, and compiled into that checkout's own read-only snapshot store on first read. - A child `kibi-mcp` started in the checkout (this server's own entry, with `KIBI_KB_DEPENDENCY=@`) answers it, pooled and retired like the children of [Workspace Routing](#workspace-routing). This server's engine, branch store and sync never see the dependency, so its size never slows this project's KB. - The result carries a `detached_head_read_only` diagnostic naming the dependency and its store. - A dependency is never written. Tools without a `kb` input (`kb_upsert`, `kb_delete`, `kb_apply_plan` and the other writes) refuse a call that names one with "`` does not take a kb scope: KB dependency '``' is read-only", instead of dropping `kb` and acting on this project's KB. - With `workspaceRoot`, the dependencies of that workspace are used. - `KIBI_WORKSPACE` and `KIBI_MCP_ROUTING=0` do not block a dependency read: the caller asked for it by name. Dependencies must carry KB schema 6 or newer, and no newer than this Kibi reads. The answer is only as complete as the dependency's committed KB at the pinned commit: Kibi reads its `.kb/` sources as they are, so a release made before that repository wrote any requirements answers with nothing. An unknown, unpinned or stale dependency fails the call with its code (`DEPENDENCY_UNKNOWN`, `DEPENDENCY_NOT_LOCKED`, `DEPENDENCY_LOCK_STALE`, and the others in the [error reference](error-reference.md#kb-dependency-errors-dependency_)) instead of answering from this project's KB. The CLI read commands take the same scope as `--kb `, and their JSON routes accept `kb` in the input. ## Recommended Agent Workflow 1. **Interactive Bootstrap**: Start with the `/kibi-bootstrap` workflow, inspect typed status, and let `kb_plan_bootstrap` return any bounded context questions. Always preview candidates for user approval before applying. 2. **Gather Context**: Use `kb_search` for discovery (ask it a direct question or decompose broad tasks into focused probes; read `data.answer` for the governing requirements) and `kb_query` for exact follow-up. 3. **Inspect Freshness**: Use `kb_status` when branch or stale-state confidence matters. 4. **Analyze**: Use `kb_find_gaps`, `kb_coverage`, and `kb_graph` for curated reporting. 5. **Check Source Impact**: After meaningful source edits, run `kb_check` with `changed: true` and the edited `sourceFiles`: it returns the verdict `git commit` will give, and findings with `blocks: "commit"` stop the commit. `includeImpactDiagnostics: true` with `includeWorkingTreeDiff: true` adds the edit's impact diagnostics without the gate's verdict. 6. **Execute Changes**: Model prose with `kb_model`, preflight with `kb_upsert` and `dryRun: true`, then use `kb_upsert` to create/update entities and relationships. 7. **Validate**: Run `kb_check` after structural changes. Use explicit `rules` during iteration for scoped validation; run an unfiltered `kb_check` before completion to include the full-KB `qualityDiagnostics[]` audit scan. 8. **Clean Up**: Use `kb_delete` only for intentional removals after validating dependencies. **Modeling note:** Use `flag` for runtime/config gates. Bug and workaround notes belong in `fact` entities, usually with `fact_kind: observation` or `meta`. **Strict facts** drive contradiction checks; observation/meta are non-blocking notes. ## Error Handling The MCP server returns structured errors for: - Invalid parameters (missing required fields, invalid enum values) - Referential integrity violations (attempting to delete entities with dependents) - Branch KB startup/attach failures - Validation failures Always check error responses before proceeding with more mutations. For common validation failures and recovery payloads, see `docs/error-reference.md`. In particular, strict fact writes must use `subject_key`, `property_key`, `value_type`, and exactly one typed `value_*` field; do not use `subjectKey`, `propertyKey`, or generic `value` in `kb_upsert.properties`. ## Determinism Guarantees - Query results are sorted and de-duplicated for consistency - MCP responses use explicit field names and fixed shapes - Validation output is stable across repeated runs on unchanged KB state --- # Error reference URL: https://getkibi.dev/reference/errors.html > Every MCP error code, its meaning, and the recovery path. Use this reference when an MCP mutation fails. Fix the payload instead of falling back to prose-only `links` or `text_ref`. ## `must NOT have additional properties` **Likely cause:** The payload used fields not accepted by `kb_upsert.properties`, often camelCase semantic claim names. **Common fixes:** | Invalid | Valid | | --- | --- | | `subjectKey` | `subject_key` | | `propertyKey` | `property_key` | | `predicateName` | `predicate_name` | | `predicateArgs` | `predicate_args` | | `canonicalKey` | `canonical_key` | | `closedWorld` | `closed_world` | | `value: true` | `value_type: "bool"` and `value_bool: true` | If starting from prose, call `kb_model` with `mode: "requirement"` and apply its sequential `applyPlan` instead of guessing field names. ## Invalid `status`, `fact_kind`, `operator`, or `value_type` Use the enum values shown in the MCP `inputSchema`. For property facts, common values are `fact_kind: "property_value"`, `operator: "eq"`, and `value_type: "bool" | "int" | "number" | "string"`. A `req-status-vocabulary` finding on a requirement written with a legacy status (`accepted`, `proposed`, `draft`, `deprecated`, `superseded`, `rejected`) gets a `req_status_vocabulary_map` review action in the `kibi migrate` plan, with the suggested status (`accepted` -> `open`) and any semantic-inventory drift the new status would expose. Approve it by id (`--approved-action req-status-vocabulary-map-`); a re-derive planned for that drift depends on it. ## Incomplete `property_value` fact `fact_kind: "property_value"` requires: - `subject_key` - `property_key` - `operator` - `value_type` - exactly one of `value_string`, `value_int`, `value_number`, `value_bool` ## Incomplete `predicate` fact `fact_kind: "predicate"` requires: - `predicate_name` - non-empty `predicate_args` - `canonical_key` Call `kb_model` with `mode: "predicates"` before hand-writing ontology predicates. ## Incomplete logical claim provenance `claim_key` is derived from `claim_text`, so a grounding fact (`property_value`, `predicate`, `rule`) only has to send the exact atomic clause as `claim_text`: Kibi fills in the key on `kb_upsert` and on `kibi sync`. A `claim_key` sent with the text must equal the derived key (`kb_model` with `mode: "analyze"` returns it for that clause); a `claim_key` without `claim_text` is rejected. Do not invent or reuse a key for different prose. An `observation` or `meta` fact is a non-grounding review note, so it quotes the claim it is about in `claim_text` alone and gets no key. The error `/properties must have required property 'claim_key'` came from releases before the key was derived; upgrade, or send the pair `kb_model` returned. If `kb_check` reports `logic-coverage`, compare the requirement `logic_claims` manifest with its linked `property_value` and `predicate` facts. Ground every missing key, add any omitted linked key to the manifest, and keep ambiguity or ontology gaps explicitly unresolved rather than satisfying the check with an observation. If `kb_coverage.repairPlan.status` is `partial`, do not execute it as a complete migration. Its `scope.excludedByPagination` count identifies omitted actionable requirements; rerun requirement coverage with `offset: 0` and a large enough `limit`. Apply only `ready` batches, never infer that `blocked` means safe to skip, and rerun coverage after each validated sequential batch because new downstream gaps can become visible as prerequisites are repaired. ## Invalid entity origin `origin` is an object with a required `kind` (`human`, `agent`, `migration` or `import`) and optional `ref`, `approved_by` and `recorded_at` (ISO 8601). Unknown kinds and unknown fields are rejected by `kb_upsert` and, in Markdown frontmatter, by `kibi sync` (classification `Invalid Entity Origin`). To keep a stored origin, omit `origin` from the upsert instead of copying it. ## Invalid firmness `firmness` is allowed only on requirements and ADRs and must be `firm`, `default` or `exploratory` (classification `Invalid Firmness` in `kibi sync`). A `kb_upsert` that sets `firmness: firm` without `origin.ref` (or `approval_ref` on a requirement) fails with `Entity validation failed: firmness: firm needs origin.ref ...`: set the ref to the message, review or ticket where a human stated the rule, or use `firmness: default` for a delegated or agent choice. Kibi only checks that a reference is present, so never mark your own choice firm or cite words a person did not say. ## Firm decision edited in place `kb_upsert` fails with `Entity validation failed: is a firm decision, so kb_upsert does not change its title, statement, body or firmness in place` when a write changes the claim of a current requirement or ADR whose firmness is `firm` (explicit, or read from a non-agent origin) without citing new human words. `kb_check` reports the same edit made directly on disk as `decision-firm-edited` (compared with `HEAD`). Ask the person who stated the rule. If they agree, either repeat the write with `origin.ref` (or `approval_ref` on a requirement) pointing at their words, or supersede the decision with a new `firmness: firm` one that cites them; otherwise leave it and propose the change. To undo a direct edit, restore the file from `HEAD`. Context sections, tags, status and relationships can be changed without a reference. ## Supersede without a reason `supersedes-reason-missing` blocks a current requirement or ADR that supersedes another without a `## Why this changed` section of at least 12 words. Add the section to the new entity's body: name the evidence (a failing test, a measured cost, a constraint the old decision missed, a new requirement) and answer the old decision's reasoning. A preference is not evidence; propose it instead of superseding. `decision-firm-superseded` blocks a replacement of a firm decision that is not firm itself: ask the person who stated the rule, and record their agreement as `firmness: firm` with `origin.ref` to their words. ## Proposition-complete ingestion failed on a relationship update `kb_upsert` on an existing requirement that only adds relationships (for example `specified_by` to a new scenario) keeps the stored proposition ledger: when the payload has no `semantic_*` or `logic_claims` field and its `title` and `text_ref` (if given) equal the stored values, Kibi merges the stored `semantic_text`, `semantic_inventory`, `semantic_inventory_version`, `semantic_source_field`, `semantic_source_hash`, `semantic_clauses` and `logic_claims` (and the stored `text_ref` when the payload omits it) under the payload, and checks the merged requirement. If you still see `semantic_inventory_version must be 'kibi.semantic-inventory.v1' ... received 0`, the payload changed the prose or supplied part of the ledger: either send only `title`, `status` and the relationships, or send the complete ledger returned by `kb_model` with `mode: "analyze"` for the new prose. ## ` would be written as a current requirement without a complete proposition inventory` `kb_upsert` judges an update of a stored requirement as its file will read after the write: the stored status, prose and ledger with the payload's fields on top. A payload such as `{"title": "...", "status": "closed"}` on a `draft` requirement that never had an inventory passes on its own fields, but would leave a current requirement whose prose has no inventory, which `kibi sync` rejects with `proposition-complete ingestion failed: semantic_inventory must contain exactly N proposition(s); received 0`. Kibi refuses it at the write instead. Run `kb_model` with `mode: "analyze"`, the requirement's `id` and its complete `semantic_text`, then send the returned inventory contract (`semantic_inventory`, `semantic_inventory_version`, `semantic_source_field`, `semantic_source_hash`, `logic_claims`) in the same `kb_upsert`; propositions you cannot model stay as `ontology_gap` or `missing` entries. To retire the requirement instead, supersede it. `kibi migrate` does not derive an inventory for a requirement that has none; it only re-derives one that drifted. The same check applies when the store does not hold the requirement but its file exists, for example a file `kibi sync` could not extract because of a legacy `status: implemented`: `kb_upsert` reads that file's front matter as the stored state, so a status-only write on a file with pinned `semantic_text` and no inventory is refused here too, and nothing is written. ## Uncompiled authored source (`source-relationship-parity`, `source_extraction_failed`) ` cannot be compiled, so the entities and relationships it declares are missing from the KB: ` means `kibi sync` could not extract an authored `.kb/` file, so `kb_query`, `kb_coverage` and `kb_upsert` do not see what it declares. `kb_check` reports it as a blocking `source-relationship-parity` violation, and `kb_status` reports the stale reason `source_extraction_failed` (and `dirty: true`) until the file compiles. An error on `/status` usually means a legacy requirement status: run `kibi migrate --yes`, which maps `implemented`, `done` and `completed` to `closed` with the tag `implemented`, or set `open`, `in_progress`, `closed` or `retired` (with `retired_reason`) in the file. For any other error, fix the named front matter field (edit the file, or rewrite the entity with `kb_upsert` so the write replaces the failing field), then run `kibi sync`. `Upsert of refused: exists in but is not compiled (), and this write would leave the file uncompilable: ` means the write merges into that existing file and the result still would not compile. Send the field that fixes the error (for example a valid `status`). `... exists but kibi sync cannot compile it (...), and its front matter does not parse` means the YAML itself is broken; fix it in the file. A successful write into such a file returns the warning ` was not in the compiled KB; this write updated its authored file ...`; run `kibi sync` to compile it. ## Duplicate entity declaration (`source-relationship-parity`, `duplicate_entity`) ` is declared N times ('' in <file>; ...), so the KB keeps only one of the declarations and the staged gate refuses every commit until one remains` means authored `.kb/` sources declare one entity id more than once: two records in `.kb/symbols.yaml`, two entity files with the same `id`, or both. The compiled store keeps one entity per id, so `kb_check` reports it as a blocking `source-relationship-parity` violation (evidence `direction: duplicate_entity` lists every declaration), and `kibi check --staged` refuses every commit with `Duplicate snapshot entities` until one declaration remains. Copies like these usually come from a line-based Git merge of two branches that each added the record, in a clone without the Kibi merge driver (`kibi doctor` reports how to set it up). When the copies in `.kb/symbols.yaml` differ only in their links, a `kb_upsert` of the id with its title and status merges them into one record. Otherwise keep one declaration with the fields and links of every copy by hand, then run `kibi sync` and `kb_check` again. ## Semantic advisor clauses must be verbatim fragments of the requirement prose `kb_compile_intent` and `kb_model` (`mode: "analyze"`) refuse a `clauses` entry that does not occur in the intent or `text`, naming each such clause. Clauses split the prose; they do not restate it. Copy each clause from the prose unchanged (whitespace layout, a leading list marker and closing punctuation may differ), or omit `clauses` to let Kibi split the prose. To change what the requirement says, change the intent itself. ## `semantic_source_field must be '<field>' for the current requirement prose` The payload declared no `semantic_source_field`, or one that is not `semantic_text`, `text_ref` or `title`. Kibi then derives the prose field by a fixed rule, `semantic_text` when it is set, else `text_ref`, else `title`, and the message says which field it derived and why (for example "no semantic_source_field was sent; the prose comes from text_ref because semantic_text is unset"). Set `semantic_source_field` to that field and make `semantic_source_hash` the SHA-256 of that field's text, or declare one of the three fields explicitly; a declared field among those three is honored as given, so the expected field never flips between calls that send the same properties. ## Semantic inventory no longer matches the advisor If `kibi sync` reports `N requirement(s) failed proposition-complete ingestion` after an upgrade, the stored `semantic_inventory` of each listed requirement was written by an older semantic advisor. Run `kibi migrate`: its `semantic_inventory_rederive` actions rewrite the inventories that can be re-derived without losing grounding, and its `semantic_inventory_review` actions carry the re-derived contract for the rest. Fix those in the requirement file itself (sync rejects them, so `kb_upsert` and `kb_delete` cannot reach them), then run `kibi sync`. When a review exists only because some grounding links point at claims that are no longer modeled, the plan also lists a `semantic-inventory-rederive-drop-grounding-<REQ>` action; approve it by id (`kibi migrate --apply-safe --approved-plan-hash <hash> --approved-action <id>`) to write the re-derived contract and remove exactly those links, then run `kibi sync`. ## Apply plan failed: only ready plans may be applied `kb_apply_plan` applies only a plan whose `status` is `ready`; the message names the plan's actual status and the remedy. A compile plan in `needs_resolution` still has `ontology_gap` or `missing` propositions, or a step its diagnostics name: model each proposition with `kb_model` (`mode: "requirement"` or `"predicates"`), call `kb_compile_intent` again and apply the ready plan it returns, or write the requirement with `kb_upsert` carrying the plan's inventory contract with the unmodeled propositions kept as `ontology_gap` entries. A `blocked` compile plan conflicts with a current requirement: resolve the contradiction (supersede or change the conflicting requirement, or change the intent), then compile again. A bootstrap plan in `needs_context` needs the context it asks for before planning again. ## Unsafe or unverifiable rule fact `fact_kind: rule` requires a `kibi.logic.v1` `rule_ir`, a deterministic full `rule_hash`, a `semantic_key`, a `rule_schema_id`, and `rule_name`. Submit the typed object through `kb_model` with `mode: "requirement"`; do not provide Prolog source. `rule-safety` rejects function symbols, raw goals, cuts, meta-calls, dynamic predicates, I/O, unsafe/unbound variables, existential rule heads, unstratified negation, incompatible units, and unbounded aggregation. `rule-verifiability` requires `requires_rule` to target a real `rule_schema` and a safe rule fact. Analysis that is timed out or resource-limited is `unresolved`, not proof of consistency. If validation reports `Logical Claim Provenance Mismatch`, the fact's `claim_key` was copied, invented, or derived from different text. Re-run `kb_model` with `mode: "analyze"` for the exact atomic clause and preserve its returned `claim_key` and canonicalized `claim_text` together. ## Relationship source mismatch Same-call relationship rows must start from the entity being upserted. To link `REQ-mcp-search-discovery -> TEST-mcp-search-discovery`, create `TEST-mcp-search-discovery` first, then upsert `REQ-mcp-search-discovery` with `verified_by`. ## Relationship endpoint does not exist (`RELATIONSHIP_ENDPOINT_MISSING`) `Failed to upsert entity <id>: Target entity does not exist: <other>` (or `Source entity does not exist`) means a relationship names an entity the KB does not hold yet, often because the earlier write that would have created it was refused. Nothing is written, and resending the same payload fails the same way. Create `<other>` first, then resend, or write both entities as steps of one `kb_apply_plan`. `kb_validate_upsert` reports the same refusal without writing. ## Invalid relationship tuple `kb_upsert` (dry run or real) rejects relationship source/target type pairs that are not part of the relationship schema. For example, facts are not directly verified by tests: do not write `verified_by fact -> test` or `validates test -> fact`. Create or update a requirement, link the requirement to the fact with `constrains`, `requires_property`, or `requires_predicate`, and link the requirement or its scenario to the test with `verified_by` / `validates`. ## Strict-lane mismatch - `constrains` targets `fact_kind: subject`. - `requires_property` targets `fact_kind: property_value`. - `requires_predicate` targets `fact_kind: predicate`. - `requires_rule` targets `fact_kind: rule` whose `rule_schema_id` points to `fact_kind: rule_schema`. Legacy prose facts may remain readable during migration, but they do not provide the same strict contradiction semantics. ## Contradiction detected Create an append-only replacement requirement and add `supersedes`, or deprecate the conflicting requirement before writing the new one. Then set the replaced requirement to `status: closed`. The check runs at commit time (`stage=contradiction_check`), after every validation passed, and `kb_upsert` with `dryRun: true` previews the same check for a `req` against a staged, rolled-back copy of the store, so a dry run refuses what the commit would refuse. A refused commit rolls back the authored file, the relationship shards and, for an untracked file written by an earlier `kb_upsert`, its pending-source receipt, so `kb_check` and `kb_status` stay clean afterwards; verify with both before retrying with the supersession in place. ## Pending source hash drift (`source-relationship-parity`, `SYNC_ERROR`) `Pending source hash drift blocks sync for .kb/<lane>/<id>.md; expected <hash>, found <hash>` means the pending-source receipt that binds an untracked file written by `kb_upsert` no longer matches the file's bytes (for example after an edit outside Kibi). There is no separate repair tool: rewrite the entity with `kb_upsert` (its current `title` and `status` are enough for an existing entity) and the receipt is republished against the current bytes, or `git add` the file: the next sync retires the receipt of a tracked file without comparing its hash. A `kibi migrate` rewrite (re-derived inventory, source path repair, lifecycle repair) republishes the receipt itself. Before the first compile the entity is not stored yet, so `kb_upsert` judges the payload against the entity's file as it reads now; `git add` the file is the simpler repair there. `Pending source is missing` means the untracked file was deleted: run `kibi branch recover --apply` if that was intended. Each receipt records the branch it was written on, and sync skips a receipt from another branch whose file is absent here, so checking out a branch that lacks a file committed on another branch does not cause this finding. Receipts that name no branch, written by older Kibi versions, are still checked on every branch. A receipt whose file Git tracks on the current branch is retired whichever branch wrote it. So is a receipt whose file is absent here but committed on another local branch, for example a file written on `main` and committed on a feature branch made afterwards with no sync there; once no local branch holds the file, the finding comes back. With no resolvable branch (a detached HEAD during a rebase or bisect) every receipt is checked, so a file committed on another branch can still cause this finding there; check out a branch and sync again. A refused `kb_upsert` restores the receipt it found, so a commit-time refusal alone does not cause this finding. ## Branch store not compiled (`branch-store-not-compiled`, `branch_store_not_compiled`) `The KB store for branch <branch> does not exist yet` (or `is empty (generation-1:0: nothing compiled)`) `, while .kb/ holds <n> authored source file(s)` means this branch was never compiled. Kibi keeps one store per branch and never copies another branch's; the `post-checkout` hook `kibi init` installs compiles a new branch, so this appears on a branch created without the hooks. Every other rule would read an empty KB, so `kb_check` reports only this violation and `kb_status` reports it as one blocking stale reason. Run `kibi sync`, or apply the `branch-store-compile` action of the returned `migrationPlan` with `kb_apply_plan`. `kibi branch ensure` alone does not fix it: it creates an empty store. Run `kibi init` once to install the hooks. ## Superseded requirement still open (`superseded-requirement-open`) `kibi check` blocks a requirement that another requirement `supersedes` while its status is not `closed`. Upsert it with `status: closed`, or run `kibi migrate` (action `close_superseded_requirements`), which edits only the status line. If the requirement still states current intent, delete the `supersedes` link instead. A finding that starts with `Supersession cycle:` names requirements that supersede each other; nothing closes them automatically. Decide which one is current, delete the `supersedes` link that points at it, then close the others. ## Retired requirement without a reason (`retired-reason-missing`) `status retired requires retired_reason` (from `kb_upsert`) and the blocking `retired-reason-missing` finding (from `kibi check`) mean a requirement says it is retired but not why. Add `retired_reason`: why the behavior no longer exists, with the date or change that retired it. If the requirement still states current intent, set its status back to `closed` or `open` instead. ## Current entity owned only by retired requirements (`retired-owner-only`) A current fact, scenario or test is owned only by retired requirements, so it describes behavior that no longer exists while search and coverage still read it as current. Link it to the current requirement that took over the behavior (for a fact, a grounding link such as `constrains`; for a scenario, `specified_by`; for a test, `verified_by` or `validates`), archive a fact or scenario with `status: deprecated`, or delete a test whose behavior is gone with `kb_delete`. The finding's `evidence.owners` lists the retired requirements. ## Entity has no body context (`entity-context-missing`) `kibi check` blocks a current `req`, `scenario`, `test`, `adr` or observation/meta `fact` whose body has fewer than 12 words of context, or whose context only restates the title (for a requirement, also `semantic_text`). For a requirement only text under a `Context`, `Rationale`, `Why`, `Background`, `Source`, `Notes` or `Evidence` heading counts. Add a `## Context` section (requirement) or prose body stating why, who asked, the source and anything that does not fit front matter, and pass it as `document.body` to `kb_upsert`; the upsert result and dryRun warn about the same finding. Never invent a reason the requester did not give: write "Reason not stated". Entities the schema 8 `kibi migrate` acknowledged (tagged `review:context-missing` and listed in `.kb/manifest.json` under `contextAcknowledged`) do not block and are counted by the advisory `entity-context-acknowledged` diagnostic. The tag is reserved for them: on any other entity `kibi check` still blocks with "review:context-missing is reserved for entities acknowledged by the schema 8 migration; add context instead". Do not tag an entity to clear the finding; write who asked, the source and "Reason not stated" in the Context section. Remove the tag once real context is added. The pre-commit `kibi check --staged` blocks the same finding on an entity document the commit adds or edits, unless the entity already had it at the last commit or is acknowledged. ## Component without a design requirement (`policy-ownership`) Only reported when a package is activated for `kibi.check-policy.v1`, such as `kibi-plugin-ui`. A production symbol in the policy's file set (for `kibi-plugin-ui`, components in `*.tsx`, `*.jsx` and `*.component.ts`, tests and stories excluded) implements no current requirement linked `requires_predicate` to one of the policy's predicates. The finding names the policy rule and the requirements the symbol does implement. Fix it by linking the symbol `implements` to the design requirement it renders, or by modeling one: a requirement grounded in `ui_pattern`, `same_pattern`, `ui_container` or `visual_layout_rule` (see `docs/ui-requirements.md`). A superseded design requirement no longer counts, so a component that only implements one needs the successor. When the component genuinely has no design constraint, tag the symbol `review:ui-unconstrained`. A finding whose entity is the policy package means the policy could not be read (not installed, `kibi.checkPolicy` missing, a path outside the package, or an invalid document); fix the install or the activation rather than removing the rule. ## Pattern marker missing (`policy-markers`) Only reported under an activated check policy with marker rules. A file implementing a requirement that names a pattern (for `kibi-plugin-ui`, `ui_pattern(subject, pattern)`) no longer contains a marker the KB declares for that pattern (`pattern_marker(pattern, marker)`); the files searched are the symbol's source file plus siblings with the same stem and the policy's extensions (`.html` for `kibi-plugin-ui`). This usually means the component was rewritten to a different pattern. Restore the agreed pattern, or, if the human decided the design changes, supersede the requirement with one naming the new pattern and its markers. If only the marker's spelling changed, update the `pattern_marker` fact; `timeline_dot` and `timeline-dot` already match each other. ## Dangling source (`source-path-dangling`) An authored `source` frontmatter field must name an existing workspace path (a `#anchor` suffix is fine), an existing entity id, or an http(s) URL. The field is dead data: the compiled `source` is always the entity's own file, and Kibi never writes the field, so `kb_upsert` cannot fix it and an agent must not hand-edit `.kb/`. Run `kibi migrate` instead; its automatic `source_path_rewrite` action repairs the finding. When the value names another knowledge file by its pre-canonical path (`documentation/<lane>/...`, or `<lane>/...` relative to the knowledge root) and that file exists under `.kb/<lane>/`, the finding carries `evidence.rewrite` and the action points the field there. Otherwise the finding carries `evidence.remove` and the action removes the line: `self` when the value names the entity's own file (in any spelling, compared case-insensitively), `dangling` when it names nothing Kibi can map. Only when the edit is not safe, for example a value spanning several lines, does the finding carry `evidence.refused`; `kibi migrate` then plans a `review_source_path_dangling` action, and a person edits the field by hand. The rule also covers a `text_ref` whose value is one workspace file path (a directory, a file name with an extension, no spaces) that does not exist, typically a path under a retired knowledge folder. Those findings carry `evidence.field: text_ref`. `text_ref` is evidence, so it is never removed: when the file moved under `.kb/`, `source_path_rewrite` points the field there; otherwise (or when the `text_ref` is a requirement's semantic source) the finding carries `evidence.refused`, and a person points it at the evidence's current path or deletes it when the evidence is gone. ## Symbol lacks qualifying coverage (`symbol-coverage`) A production symbol needs `covered_by` a test that covers one of the requirements it implements. When the requirement has a scenario (`specified_by`), the test must verify the scenario (`validates(Test, Scenario)` or `verified_by(Scenario, Test)`); a test that verifies the requirement directly counts only while the requirement has no scenario. `kibi check` reports every uncovered symbol; `kibi check --staged` reports the same rule for the symbols the commit changes (changed source symbols and symbols whose staged `.kb/symbols.yaml` entry changed), so a commit cannot pass the gate with coverage the full check rejects. Link the test to the scenario, or point `covered_by` at a test that already does. When the symbol already has `covered_by`, the finding names the missing link instead of asking for `covered_by`: which test does not verify which implemented requirement, and the relationship that would connect them (`verified_by(SCEN-…, TEST-…)` through the requirement's scenario, or `verified_by(REQ-…, TEST-…)` when it has none). When the test is already linked that way, the finding says its `verification_scope` or `verification_perspective` does not match what the requirement requires. ## Coarse symbol link (`symbol-granularity`, `symbol_granularity_violation`) A symbol with traceability links covers its source file more coarsely than the declarations available there, for example a class symbol `Greeter` while `Greeter.greet` exists. Move the `implements`/`covered_by`/`executable_for` links to the narrow behavioral symbol, or add an allowed `granularity_reason` when the coarse link is intentional. Full `kibi check` reports this for every symbol against its whole working-tree file; `kibi check --staged` reports it as `symbol_granularity_violation` when a staged hunk touches a narrower declaration. `kb_upsert` (dryRun included) refuses the same coarse link when it is written, also when the payload only adds links to a stored symbol, so the debt never reaches the commit; the refused write is a coded error (`SYMBOL_GRANULARITY_VIOLATION` on MCP and in the CLI JSON route). The message lists methods, functions and accessors first, then properties (behavioral in the schema, but usually plain fields), so the first names are the likely places to move the link. When the message says the extractor does not produce the symbol's title, the title names a private class member (`private` or `#private`) or a declaration that was removed, renamed or is not exported: coordinate refresh can never bind it, so re-point the symbol to the public declaration that owns the behavior by changing its `title` with `kb_upsert` (or move its links to an existing symbol for that owner), or delete it. Give it a coarse `granularity_reason` (`module-level-behavior`, `config-artifact`, `extractor-miss`, `test-suite`) only when it intentionally covers the whole file. ## Audit journal or snapshot lock `Audit journal is locked by another Kibi runtime; restart the stale MCP/CLI session before retrying` means an older engine still owns the branch's journal lock. Kibi does not terminate unrelated sessions; use `kibi engine status`/`kibi engine stop` for the current workspace, or restart the stale MCP/CLI process, then retry the validated upsert. A `rdf/lock` file present after an MCP session ended is usually not stale. Calls such as `kb_apply_plan` run in the workspace's detached engine daemon, which keeps the lock while it serves later MCP and CLI sessions and exits after 10 idle minutes (`KIBI_ENGINE_IDLE_TIMEOUT_MS`). `kibi engine status` shows the live daemon; a lock whose process no longer exists is reclaimed when the next engine starts, and `kb_status` then lists a `store_lock_taken_over` notice for 24 hours. Only stop the daemon (`kibi engine stop`) when you need the lock released now. `KB snapshot is stale; reattach or refresh the runtime before retrying` means another current runtime published the branch after this process attached. Reattach the branch (or restart the runtime) and rerun the read/preflight/mutation sequence. Timeout diagnostics include `stage=<name>` and the child PID. The stage is one of the bounded commit markers (`runtime`, `lock`, `rdf_mutation`, `contradiction_check`, `entity_audit`, `relationship_audit`, `snapshot_save`, or `audit_sync`); use it to distinguish a stale lock from a filesystem or Prolog failure without relying on entity payload logging. ## `Pending source hash drift blocks sync` (`PENDING_SOURCE_HASH_DRIFT`) **Cause:** `kb_upsert` wrote a `.kb/` file that Git does not track yet, and the file was then edited outside Kibi. Sync never guesses which bytes are meant, and `kibi branch recover --apply` refuses for the same reason. **Fix:** to keep the edit, stage the file (`git add <path>`) and run `kibi sync` again: Git-tracked bytes are the authored input. Or write the change through `kb_upsert` (CLI: `kibi upsert`), which records the new bytes. A pending source deleted on purpose (`PENDING_SOURCE_MISSING`) is the case `kibi branch recover --apply` handles. ## Coded tool errors on MCP (`VALIDATION_FAILED` and others) A tool that rejects its input with a Kibi error code, such as `kb_compile_intent` or `kb_model` mode `analyze` with a `clauses` entry that is not a verbatim fragment of the prose (`VALIDATION_FAILED`), returns `isError: true` with an error envelope in `structuredContent`: `status: "error"` and `error.code`, `error.message`, `error.retryable`. The CLI JSON route prints the same `error` for the same input (exit code 2 for input errors, 1 for operation errors). Branch on `error.code`, fix the input the message names, and call again; `retryable: false` means the same input fails again. The text content repeats the code: `Tool <name> failed: [<code>] <message>`. ## Retrying a failed CLI JSON call (`retryable`) `error.retryable` says whether the same call, sent again unchanged, may succeed. A refusal is never retryable: a KB rejection (a validation failure, a contradiction, a firm-decision lock, a missing relationship endpoint), which the CLI JSON route reports as `OPERATION_FAILED`, and a refusal with its own code such as `SOURCE_PATH_INVALID`, `SOURCE_FORMAT_UNSUPPORTED`, `PROTOCOL_VALIDATION_FAILED` or `PROLOG_UNAVAILABLE`. Fix what the message names before calling again. `retryable: true` is kept for failures the same call may get past, such as `SOURCE_MUTATION_LOCK_TIMEOUT` while another writer holds the lock, or an `OPERATION_FAILED` that is not a rejection. ## Read stopped at its engine limit (`QUERY_LIMIT_EXCEEDED`) The read ran under `KIBI_ENGINE_READ_TIME_LIMIT_MS` or `KIBI_ENGINE_READ_INFERENCE_LIMIT` and was stopped before it computed an answer; `error.details.limitExceeded` names the `kind` (`time` or `inferences`) and the `limit`. Nothing was read partially and nothing was written. Narrow the request (a type, id, tag, or smaller page), or raise or unset the limit in the CLI or MCP server environment, then retry. ## Result over its size ceiling (`RESULT_TOO_LARGE`) A list or report read's data was still larger than 64,000 characters after it was cut to its 24,000-character [result size budget](mcp-reference.md#result-size-budget). Nothing was written. Narrow the call (filters, a smaller `limit`, or `fields: "summary"`) and try again; the same call repeated unchanged fails the same way, so it is not retryable. A result cut to the budget is not an error: it carries `truncated: true`, `truncation` and a `RESULT_TRUNCATED` info diagnostic, and its `nextActions` name the call with the next `offset`. ## KB dependency errors (`DEPENDENCY_*`) A read with `kb` (MCP) or `--kb` (CLI), and `kibi deps lock|fetch|status`, fail with one of these codes instead of answering from the project's own KB: - `DEPENDENCY_UNKNOWN`: `.kb/dependencies.json` declares no dependency with that name. The message lists the declared names; fix the name or add the dependency. - `DEPENDENCY_NOT_LOCKED`: the dependency is declared but has no pin in `.kb/dependencies.lock.json`. Run `kibi deps lock <name>` and commit the lock file. - `DEPENDENCY_LOCK_STALE`: the lock pins the dependency for a different `git` URL, `ref` or `directory` than `.kb/dependencies.json` now declares. Run `kibi deps lock <name>`. - `DEPENDENCY_REF_NOT_FOUND`: the repository has no tag, branch or ref with the declared name. Fix `ref` (or remove it to follow the remote `HEAD`). - `DEPENDENCY_FETCH_FAILED`: `git` could not list or fetch the repository. Check the URL, the network, and that git already has credentials for a private repository (it runs without a terminal prompt). - `DEPENDENCY_NOT_A_KB`: the pinned commit has no `.kb/manifest.json`. Pin a commit that has a Kibi KB, or set `directory` when the workspace is in a subdirectory. - `DEPENDENCY_SCHEMA_UNSUPPORTED`: the dependency's KB schema is older than 6 or newer than this Kibi reads. Pin another commit, upgrade Kibi, or run `kibi migrate` in that repository. A write that names a dependency is refused: MCP tools without a `kb` input fail with "`<tool>` does not take a kb scope: KB dependency '`<name>`' is read-only", and the CLI JSON routes report `VALIDATION_FAILED` for the extra `kb` property. Drop `kb` to write this project's KB. ## Write refused on a detached HEAD `<operation> writes the branch KB, but HEAD is detached at <sha> ...` (code `DETACHED_HEAD`, not retryable) means the checkout has no single branch identity (zero or several local branches point at HEAD). Reads still work from the read-only snapshot and carry a `detached_head_read_only` diagnostic. To write, check out a branch (`git switch <branch>` or `git switch -c <branch>`) or set `KIBI_BRANCH` to name the branch explicitly, then retry. ## Working without Git (`no_git_repository`, `GIT_REQUIRED`) Kibi works in a directory that is not inside any Git repository. It keeps one knowledge store for the directory (the reserved store `kibi-internal/no-git`, which `KIBI_BRANCH` cannot name), treats every file under `.kb/` on disk as authored input, and search, query, record, upsert, check and sync work as usual. `kibi init`, `kibi doctor`, the host session-start notes, `kibi status`, `kibi check` and the first MCP result of a session carry the advisory `no_git_repository` (a warning, not a failure): it names what is off until there is a repository and recommends `git init`, then `kibi init`. Until then, finish a change with `kibi check`. When Git itself is not installed, the advisory says to install it first. The features that read Git refuse with `GIT_REQUIRED` (`retryable: false`), naming the Git-free alternative: the commit gate (`kibi check --staged`, `kibi check-generated --staged`), `kibi check-diff`, `kibi hooks install`, `kibi branch ensure` and `kibi branch migrate`, `kibi gc`, impact review and `kibi signoff`. After `git init`, the first Kibi call carries the knowledge over: every `.kb` source Git does not track yet gets a pending-source receipt for the new branch, so the branch store compiles the same bytes, and the old store is kept under `.kb/recovery/no-git-adoption/` (nothing is deleted). Kibi prints one notice; run `kibi init` to install the hooks and refresh the agent instructions, then commit `.kb/`. ## Git cannot read the repository (`GIT_REPOSITORY_UNREADABLE`, `GIT_NOT_AVAILABLE`, `BRANCH_UNRESOLVED`) A `.git` entry that Git refuses (for example `safe.directory` ownership, or a broken `.git` file) is not treated as "no repository": Kibi fails with `GIT_REPOSITORY_UNREADABLE`, because working without Git there would split the knowledge from the branch it belongs to. Run `git status` to see why Git refuses it and fix that. `GIT_NOT_AVAILABLE` means a `.git` entry exists but Git is not installed or not on `PATH`: install it, then retry. `DETACHED_HEAD` is the [detached HEAD refusal](#write-refused-on-a-detached-head), and `BRANCH_UNRESOLVED` covers every other case (an unborn or ambiguous branch) and carries the resolver's own diagnostic. All of these are `retryable: false`. ## Plan application journal (`kb_apply_plan`) `Apply plan failed ...; no change was applied` means the compile plan failed before its single store commit. Its source writes were restored from the journal and the store is unchanged. Fix the cause and apply the same plan again. `PLAN_APPLY_RECOVERY_REQUIRED` (non-retryable) means a plan application was interrupted and could not be settled yet: the store could not be inspected, or a committed plan's pending-source receipts failed. Run `kb_apply_plan` with the named `recoveryJournalId` once the engine or filesystem is available. Do not re-apply the original plan. `PARTIAL_COMMIT_REPAIR_REQUIRED` from a plan journal means a journaled file holds neither its journaled before nor after bytes, or the journal is unreadable. Recovery changed nothing. Restore each listed file to its before or after bytes and retry, or reconcile the workspace and store by hand (`kibi sync`) and remove the named journal file. `MUTATION_ALREADY_COMMITTED` means the plan was already applied. Compile a fresh plan instead. An error ending in `[settled before this failure: ...]` comes from a mutating call that first completed or rolled back an interrupted plan from its journal, then failed on its own work. The settlement stands; read it to learn which plan was completed or rolled back. A plan compiled before that settlement usually fails its snapshot check and must be compiled again. ## Deletion plan approval (`kb_delete` with `approvedPlanHash`) `DELETE_PLAN_HASH_MISMATCH` means the `approvedPlanHash` passed to `kb_delete` is not the hash of the deletion plan computed from the current sources: the `ids` differ from the call that returned the plan, or an authored source or relationship shard changed since. Nothing was written. Call `kb_delete` again without `approvedPlanHash`, review the new `deletionPlan`, and approve its `planHash`. `REQUIREMENT_SUPERSESSION_REQUIRED` from `kb_delete` or `kb_apply_plan` means the plan covers an authored requirement. Requirements are not deleted: upsert a replacement requirement with a `supersedes` relationship and close the old one, as the `supersession_required` result's `nextActions` entry shows. `VALIDATION_FAILED` from `kb_delete` with `approvedPlanHash` means the approval cannot apply: it was combined with `relationships` or `dryRun: true`, an id was not resolved into the plan (missing, or has dependents), or no id produced an authored-entity plan. Nothing was written. ## Low-confidence requirement modeling downgrade (`kb_model` mode `requirement`) When confidence is below `0.70`, Kibi emits a non-blocking `fact_kind: observation`. If the prose is normative, retry with explicit `subjectKey`, `propertyKey`, `operator`, and `value` so the tool can produce strict facts. ## Predicate suggestion ontology gap (`kb_model` mode `predicates`) If no candidate meets `minScore`, Kibi emits a `review:ontology-gap` observation. Keep it as review evidence, or add a project-local `fact_kind: predicate_schema` when the language is recurring domain ontology. If a candidate exists but returns `binding_status: incomplete`, this is not an ontology gap and its `applyPlan` is intentionally empty. Review the declared argument roles and call the tool again with exact `argumentBindings` for every name in `unbound_arguments`; do not persist the literal marker `unknown`. If lexical ranking prefers a reviewed false positive, retry with the exact candidate `schema.id` as `schemaId`. Use `polarityHint` only when the prose's surface negation is not denial of the selected predicate. An unavailable `schemaId` returns `resolve_schema_reference` and no write plan; refresh or correct the schema reference rather than recording a false ontology gap. ## Inspecting domain contradiction evidence `domain-contradictions` violations may include `evidence.witnesses`. Strict-property and ground-predicate witnesses identify both requirements, both source-bound fact claims, and the exact normalized terms. Rule witnesses also include source spans, rule hashes/IR, and a symbolic comparison. A rule witness with `status: unresolved` means overlap could not be proven or excluded; it keeps requirement proof at `analysis_incomplete` and must not be reported as consistency. ## Joint contradiction (`kb-consistency`) The facts in the violation's core cannot all hold at once, even when every pair of them is compatible, so `domain-contradictions` does not report it. The violation names the core facts, the requirements behind them, and for each fact a model showing the others hold once it is dropped; the certificate is under `evidence.certificate`. Resolve it by changing one of the values or by superseding one of the requirements (a new requirement that `supersedes` it, with the old one set to `status: closed`). Do not edit a firm requirement's value in place. A certificate the independent checker rejects also blocks: rerun `kibi check`, which regenerates the bundle from the current KB. `kibi check --certificates <file>` rejects a saved bundle once the KB has changed (for example "core names a fact outside its context or repeats one" when a core fact is no longer current); write a fresh one with `--write-certificates`. `kb-consistency-unresolved` is advisory: the checker could not compare a context (mixed value types or units, an unsupported operator or polarity, validity windows that never overlap). Model the values in one unit and type if they should be comparable; until then the context is unresolved, not consistent. ## Advisory quality diagnostics are present but checks pass Kibi has a two-lane check contract. Hard correctness failures appear in `violations[]` and fail checks. Auditability findings appear in `qualityDiagnostics[]`; `review`, `info`, and non-blocking `warning` diagnostics are intentionally advisory so they can guide agents without breaking otherwise valid KB operations. Fix the underlying modeling issue when the diagnostic points to real drift, but do not move advisory findings into `links` or prose-only workarounds to silence them. Use the suggested MCP workflow instead: `kb_search` → `kb_query`, update narrower requirements/scenarios/tests/symbols/facts through `kb_upsert`, and rerun `kb_check`. Telemetry diagnostics are also advisory in `kb_check`, but `kibi usage-metrics --require-acceptance` converts their versioned report into an explicit process gate. Common IDs and repairs are: - `repeated_mutation_failures`: stop retrying, query endpoints, validate a reduced exact payload, repair runtime health, and retry once. - `mutation_validation_bypassed`: run `kb_upsert` with `dryRun: true` (catalog operation `kb_validate_upsert`) for the exact payload within one hour before sequential `kb_upsert`. - `semantic_advisor_bypassed`: rerun `kb_model` with `mode: "analyze"` (catalog operation `kb_semantic_advisor`) for the same requirement and current source hash before writing it. - `lookup_before_first_edit_bypassed`: a host session edited a requirement-linked file before any `kb_search` or `kb_query`. Before the first edit of such a file, ask `kb_search` about the change (or `kb_query` with `sourceFile`) and read the requirements it names. The evidence comes from host plugin hook rows, which are written only in diagnostic mode. - `e2e_receipt_freshness_low`: query the affected requirements/tests, run `kibi prove` for the covering integrations, let receipts append idempotently with preserved history, and rerun complete coverage. - `proof_gap_recovery_stalled`: apply reviewed ready repair batches and demonstrate a lower complete-scope gap count. - `source_lookup_zero_result_rate_high`: inspect and refresh the cited source links before repeating focused lookups. - `telemetry_completeness_low`, `telemetry_evidence_stale`, or `telemetry_acceptance_incomplete`: capture current complete diagnostic events; do not waive missing evidence as success. ## Bootstrap write validation `BOOTSTRAP_PLAN_INVALID` refuses an approved plan before any bootstrap write or journal is created. Re-plan; do not recover the invalid plan. Candidates suppressed as `invalid_write` include the validation message and become cited requirement-authoring follow-ups. `BOOTSTRAP_PLAN_REJECTED` marks a deterministic failure after application began. Inspect `actionResults` for the actions that committed, then request a corrected plan from the current state. The terminal journal cannot be replayed; `kibi status` lists incomplete bootstrap applications. IO interruptions and derived-effect repairs continue to use `recoveryJournalId`. ## Legacy storage migration blocked `kibi migrate` prints `Blocked: ...`, `kibi doctor` fails `Canonical storage`, and the plan's `schema-config-upgrade` action (`legacy_storage_migration`) is `blocked` for an `operator` when a legacy knowledge file outside `.kb/` cannot be moved. All three report the same resolution: - `... is a stale subset of .kb/symbols.yaml`: every symbol of the legacy manifest is already in `.kb/symbols.yaml`. Remove the legacy copy with `git rm`. - `... is a generated coordinates file`: remove the legacy copy (`git rm`); every `kibi sync` derives `.kb/symbol-coordinates.yaml`, which is never committed. - `... names no symbols manifest`: the legacy config places its lanes under another folder and Kibi cannot tell which symbols manifest is current. Set `paths.symbols` in `.kb/config.json`, or remove the stale copy. - `Destination ... already exists with different content`: compare both copies and keep the current one. Then run `kibi migrate --yes`. A legacy copy identical to its `.kb/` file is not a blocker: `kibi migrate --yes` removes it. ## Untracked knowledge sources (`untracked_knowledge_sources`) When `kibi check` reports `source-relationship-parity` violations whose evidence names `untrackedSources`, the migration plan collapses them into one `untracked-knowledge-sources` review action listing the files. The relationships are missing because Git does not track those files and they have no pending-source receipt. Stage them (`git add`), then run `kibi sync`. Files moved by `kibi migrate` get a receipt, so sync compiles them before they are staged. ## Invalid dry run (`UPSERT_DRY_RUN_INVALID`) `kb_upsert` with `dryRun: true` (CLI `kibi upsert` with `"dryRun": true`) on a payload the write would refuse returns an error envelope with code `UPSERT_DRY_RUN_INVALID` (MCP `isError: true`, CLI exit code 1). Nothing was written. The message and `data.errors` carry the validation errors; fix them and run the dry run again before the write. ## Migration plan refusal `MIGRATION_PLAN_REFUSED` (`kb_apply_plan` / `kibi apply-plan` with a `kibi.migration-plan.v2`, `data.outcome: refused`) means no action was applied and every failed action was refused before it changed anything: a proof-integration create plan whose `.kb/proof/integrations.json` already exists, a planned source or fact that changed since planning, or an action with no automatic executor. The message carries the refused action's `detail`. Nothing needs reconciling; request a new plan (for the proof-integration case, `kibi proof inspect --update <id> --json`). `data.outcome: reconciliation_required` is different: an action failed without being refused, so inspect its effect before retrying. `over_limit` lists each discovered candidate excluded by `maxCandidates`, after deduplication and existing-entity suppression. Declared intent claims are never capped and do not use the `maxCandidates` budget; typed requirements are selected ahead of provider observations, and provider facts that state no claim (provenance stubs, `fact_kind: meta` tagged `bootstrap:provenance-stub`) are selected last. Each `over_limit` row says whether it is a stub (`provenanceStub`), and the diagnostic counts them ("N of them provenance stubs that state no claim"): raise the limit only when a candidate with a claim is over it, never for stubs. `duplicate_entity` marks a candidate that would rewrite an entity another planned candidate already writes with different content, and a candidate whose requirement grounds on planned facts with mismatched `claim_key`s is suppressed as `invalid_write` before apply. A `Knowledge source …` diagnostic reports each declared source's claims as planned, already in the KB, filtered out (`filtered_by_entity_type`, `below_min_confidence`), or not planned, and names why each not-planned claim was left out: `suppressed_by_activation` (the activation mode plans no declared claims; compile them with `kb_compile_intent`), another `suppressedCandidates` row, a `sourceOnlySignals` follow-up, or only a diagnostic; a plan whose authoritative source has none of its claims planned, existing or filtered stays `needs_context`. `extraction_failed` names a source the planner could not extract, and an existing-ID read failure blocks plan binding. An `entity_exists` row with `matchedBy: "restatement"` means the claim restates current requirement `matchedId` (its normalized statement or excerpt equals that requirement's title, semantic text or one of its sentences): it is counted as already in the KB and not planned. If the claim says something the requirement does not, reword the claim to state the difference, or change the requirement with `kb_compile_intent` (mode `update`). A diagnostic "Intent claim at … closely restates current requirement …" marks a planned claim that overlaps one by 0.8 or more without matching it; review it before approving the plan. --- # Entity schema URL: https://getkibi.dev/reference/entity-schema.html > The eight entity types, their fields, and every typed relationship the knowledge graph supports. This document describes the entity and relationship schema for the Kibi Knowledge Base. It covers all supported entity types, their properties, relationship types, and provides frontmatter examples for each entity and relationship. --- ## Entity Types Kibi intentionally supports **eight core entity types**, organized into two logical groups: ### Common Authoring Entities (Standard Workflow) | Type | Description | |------|-------------| | req | Software requirement specifying functionality or constraints | | scenario | BDD scenario describing user behavior (Given/When/Then) | | test | Unit, integration, or e2e test case | | fact | Atomic domain fact; includes strict lanes and observation/meta notes | ### Supporting & System Entities (Context & Infrastructure) | Type | Description | |------|-------------| | adr | Architecture Decision Record documenting technical choices | | flag | Runtime or config gate (feature flag, kill-switch, deferred capability) | | event | Domain or system event published/consumed by components | | symbol | Abstract code symbol (function, class, module) - language-agnostic | --- ## Entity Choice: When to Use Each Type This section provides guidance on selecting the appropriate entity type for your documentation needs. ### Decision Table | What you are documenting | Entity Type | Notes | |--------------------------|-------------|-------| | Intended or corrected behavior | `req` | Requirements specify what the system should do | | Bug, incident, or workaround | `fact` (observation/meta) | Use `fact_kind: observation` or `meta` for non-blocking evidence | | Runtime/config gate controlling feature access | `flag` | Feature flags, kill-switches, deferred capabilities | | Executable verification or reproduction | `test` | Unit, integration, or e2e tests | | Technical decision or tradeoff rationale | `adr` | Architecture Decision Records | ### Important Rules **Do NOT create a `flag` for bugs or workarounds unless there is an actual runtime/config gate.** Use `fact` with `fact_kind: observation` or `meta` instead. **When a bug is mitigated by a feature gate:** Create TWO records - a `fact` describing the issue and a `flag` representing the gate. Link them with `relates_to` since no typed relationship exists for this case. ### Canonical Mapping Summary - `flag` = Runtime/config gate (includes kill-switches, deferred capabilities) - NOT for bug records - `fact` (observation/meta) = Bug records, incident notes, workarounds - `req` = Intended/corrected behavior - `test` = Executable verification/reproduction - `adr` = Durable design rationale --- ### Common Properties (All Entities) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier (SHA256 or explicit frontmatter)| | title | Yes | string | Short summary/name | | status | Yes | string | Entity status (see below for values) | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | The entity's own file (workspace-relative). Always compiled from the file path; Kibi ignores an authored `source` frontmatter field and never writes one, so `kb_upsert` cannot set it. A leftover authored value must name an existing workspace path (`#anchor` allowed), an existing entity id, or an http(s) URL, or `kibi check` blocks it under `source-path-dangling`; `kibi migrate` (`source_path_rewrite`) removes values that name the entity's own file or nothing, and rewrites pre-canonical paths to another moved knowledge file | | tags[] | No | array[string] | Array of metadata/search tags only | | owner | No | string | Owner/assignee | | priority | No | string | Priority level (must, should, could) | | severity | No | string | Severity level | | links[] | No | array[string] | Array of URLs | | text_ref | No | string | Pointer to Markdown/doc blob; a value shaped like one file path must name an existing file (`source-path-dangling`) | | origin | No | object | Provenance: who authored the entity and on what authority (see [Entity origin](#entity-origin)). Valid on every type; optional on symbols | | firmness | No | string | Requirements and ADRs only: `firm`, `default` or `exploratory`; when absent, `default` if an agent wrote the entity and `firm` otherwise (see [Decision firmness](#decision-firmness)) | | required_evidence | No | string | Requirements only: the weakest evidence level it accepts, `proved`, `tested`, `asserted` or `unverified`; when absent, `tested` for a firm requirement or one a person approved (`origin.approved_by`) that states no `firmness`, and `unverified` (no floor) otherwise. The `evidence-floor` check fails while the requirement's evidence level is lower (see [Evidence floors](./proof-ladder.md#evidence-floors)) | ### Entity origin `origin` records who authored an entity (KB schema 6 and later): | Field | Required | Type | Description | |---------------|----------|----------|-------------| | `kind` | Yes | string | `human`, `agent`, `migration` (backfilled by `kibi migrate`) or `import` | | `ref` | No | string | Where the content came from: URL, document path, ticket, commit or conversation id | | `approved_by` | No | string | The person who reviewed and approved the entity's content. For an exception requirement this corroborates the requirement-level `approved_by` | | `recorded_at` | No | ISO 8601 | When the provenance was recorded | ```yaml origin: kind: agent ref: https://tracker.example/ISSUE-42 approved_by: Dana Lee recorded_at: '2026-10-01T09:30:00Z' ``` How `kb_upsert` (and `kibi upsert`) sets it: - A new entity written without `origin` is recorded as `{kind: agent, recorded_at: <write time>}`; `kb_upsert` is the agent write path, so a human or an import says so explicitly. - Updating an entity without `origin` never changes the stored origin. An entity that has no origin (written before schema 6 or by hand) stays without one; editing it does not make the editor its author. - A supplied `origin` is written as given (unknown kinds and unknown fields are rejected); when it has no `recorded_at`, the write time is filled in. - `kibi migrate` (schema 5 to 6) stamps `{kind: migration, ref: "kibi migrate v5->v6", recorded_at}` on every authored entity without an origin. Kibi cannot verify a person's approval. The advisory checks `exception-unapproved`, `exception-approval-self-attested` and `agent-requirement-unapproved` make missing or agent-recorded approvals visible so a human can confirm them (see `docs/cli-reference.md`). ### Decision firmness `firmness` (KB schema 9 and later) records how firmly a requirement or ADR was decided, so a later agent knows whether it may rework the decision on evidence or must ask a human first. An explicit value is independent of `origin`: a human's "do whatever you think" is `default` and as open to rework as an agent's pick. A missing value follows the origin (KB schema 10 and later): `default` when an agent wrote the entity (`origin.kind: agent`), `firm` otherwise, because a decision a person wrote, imported or carried over from before origins were recorded is theirs. Write the value explicitly when recording a decision. Bootstrap does so for the rules it imports: a requirement planned from a cited intent claim, or from a normative line in repository Markdown, gets `origin: {kind: import, ref: <sourceId:reference or path#Lline>}` and `firmness: firm`. Other entity types reject the field: `kb_upsert` of, say, a fact with `firmness` fails with `firmness is only valid on req and adr entities; remove it from this fact`. | Value | Set when | What a later agent may do | |---|---|---| | `firm` | A human stated it as a rule ("must", "never", "we decided X because Y"). Needs `origin.ref` (or `approval_ref` on a requirement) pointing at their words. Assumed when the field is absent and the entity was not written by an agent | Follow it; to change it, ask first | | `default` | A human delegated the choice, or an agent chose. Assumed when the field is absent and an agent wrote the entity | Follow it unless the task gives evidence against it; then supersede it with a reason | | `exploratory` | An agent was unsure and flagged it as a guess | Revisit it when the area is touched | ```yaml firmness: firm origin: kind: human ref: https://tracker.example/ISSUE-42#comment-7 ``` `kb_search` answers and `kb_query` rows always show the effective firmness of requirements and ADRs (from the origin when the field is absent); hook snippets label current firm decisions `[firm: ask before changing]` and exploratory ones `[exploratory]`. A firm decision is not edited in place. `kb_upsert` (including `dryRun` and `kb_apply_plan` steps) refuses a write that changes a current firm requirement's or ADR's claim unless the write cites new human words: a changed `origin.ref`, or `approval_ref` on a requirement. The claim is a requirement's `title`, its stated meaning (`semantic_text`, or the statement its body derives), its recorded reason (`rationale`, or, without one, the body section search quotes as the reason, such as `## Context` or `## Why`) and its `## Source` section, and an ADR's `title` and whole body. Giving a source where none was recorded is allowed, but giving a reason where none was recorded (or over "Reason not stated") also needs new human words, because search credits the reason to the person; a requirement's other sections (such as `## Notes`), tags, priority, status and relationships stay editable. Lowering a firm decision's firmness, replacing its origin with an agent's, retiring it (`deprecated`, `retired`, `archived` and the other retired statuses) or bringing it back from a retired status counts as a change; `closed` and `in_progress` do not, and a firm requirement in either still guards its code. The error reads `Entity validation failed: <ID> is a firm decision, so kb_upsert does not change its <fields> in place` and names the two ways forward: write the change with a reference to the person's words, or supersede the decision with a new `firmness: firm` one that cites them. Four blocking checks keep it honest: - `decision-firm-unreferenced`: a current decision marked `firmness: firm` without `origin.ref` (or `approval_ref` on a requirement). `kb_upsert` rejects such a write up front. A decision that reads as firm only from its origin is not reported: it already names its author. - `decision-firm-superseded`: a requirement or ADR that supersedes a firm decision, explicit or read from its origin, without being firm itself. Retired superseders count too, so replacing the non-firm superseder does not clear the finding. Supersede edges whose target only reads as firm since schema 10 and that existed before it are listed in `.kb/manifest.json` as `firmSupersedeAcknowledged` (`FROM -> TO`) by `kibi migrate` and are exempt; an explicitly firm target never is. On a KB still below schema 10, the finding's suggestion says the schema upgrade acknowledges such edges. - `decision-firm-edited`: a current requirement or ADR that was firm at `HEAD` and whose claim changed in the working tree since then without new human words, for example a direct edit of its Markdown file. Decisions new since `HEAD`, retired ones and changes outside the claim are not reported; outside a Git checkout, or before the first commit, the check has nothing to compare and reports nothing. - `supersedes-reason-missing`: a current requirement or ADR that supersedes another without a `## Why this changed` section of at least 12 words. The section is context, never part of a requirement's checked meaning. Supersede edges recorded before schema 9 are listed in `.kb/manifest.json` as `supersedesReasonAcknowledged` (`FROM -> TO`) by `kibi migrate` and counted by the info diagnostic `supersedes-reason-acknowledged`; no reason is written for them. Only the listed edges are exempt: a new supersede on the same entity must explain itself. On a KB whose manifest is still below schema 9, the finding's suggestion adds that the plan's `schema-config-upgrade` (`kibi migrate --yes`) acknowledges such edges without an edit. Kibi checks that a firm decision names a reference; it cannot check that the reference is real or that a person wrote it, as with approvals. A reviewer reads the reference. Code that implements a current firm requirement is guarded as well. `kibi check --staged` blocks a staged change inside such a symbol, whatever kind of declaration it is, including lines only removed from it and a symbol removed with its record (`firm_edit_unreviewed`) until the agent records its verdict with `kb_review_firm_edit` (CLI `kibi review-firm-edit`): a `keeps` receipt under `.kb/firm-edit-reviews/`, bound to the requirement's statement and the symbol's code, clears it; a `changes` receipt (`firm_edit_breaks_rule`) keeps the change blocked until the requirement is superseded with the person's words. A requirement the same commit restates (a new statement, or a superseding requirement) is left to the checks above; a note, link or status added to its document is not a restatement, and a firm requirement that is `closed` or `in_progress` still guards its code. Receipts are the agent's judgment, not approvals, and `kibi signoff` lists them as such (see `docs/cli-reference.md`). --- ### Retired requirements A requirement has two ways to stop governing: - **Superseded**: a newer requirement links to it with `supersedes` and takes over its intent. The old one is `closed`. - **Retired**: the behavior is gone and nothing replaces it. Set `status: retired` with `retired_reason`: ```yaml status: retired retired_reason: Retired on 2026-10-30 because branch storage no longer writes audit.log. ``` A retired requirement is not current: the proof ladder reports it `not_applicable` ("requirement is retired"), `kb_search` lists it under `notGoverning` instead of `governing`, hooks and impact reviews stop offering it, and no current-intent rule reads it. Requirements that are only done keep `status: closed`; they still govern. Retiring a requirement leaves what it owned. `kibi check` blocks (rule `retired-owner-only`) a current fact, scenario or test whose every owning requirement is retired: the requirements that ground a fact (`constrains`, `requires_property`, `requires_predicate`, `requires_rule`), that specify a scenario (`specified_by`), or that a test verifies directly or through a scenario. Link each one to the current requirement that took over the behavior, archive a fact or scenario with `status: deprecated`, or delete a test whose behavior is gone. Symbols that implement only retired requirements are listed by the advisory `symbol-owner-superseded`. From KB schema 14, `kibi migrate` lists every `closed` requirement that nothing supersedes and whose own source says it was retired (its `proof_exempt_reason` or title says retired or archived, its body says "this requirement was retired", or a `historical-status:` tag records retired, archived, deprecated or superseded) as a `req_retired_status_suggest` review action. Approving one by id sets `status: retired` and a `retired_reason` quoting those words; Kibi never retires a requirement on its own. ### Entity Type Details & Example Frontmatter #### Requirement (`req`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Requirement summary | | status | Yes | string | open, in_progress, closed, retired. `closed` means done and still valid: the requirement keeps governing search, hooks and checks. `retired` means the behavior it stated no longer exists: the requirement stops governing, needs `retired_reason`, and nothing current may be owned only by it (see [Retired requirements](#retired-requirements)). ADR vocabulary such as `accepted` compiles but is not a requirement status: it silently removes the requirement from the proof ladder, and `kibi check` reports it under `req-status-vocabulary`. A superseded requirement (the target of a `supersedes` link from its successor) must be `closed`; `kibi check` blocks an open one under `superseded-requirement-open`. | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | must, should, could | | severity | No | string | Severity level | | links[] | No | array[string] | URLs or entity IDs (for relationships) | | text_ref | No | string | Independent code/doc evidence pointer; a value shaped like one file path must name an existing file (`source-path-dangling`) | | proof_exempt | No | boolean | Marks a current requirement as intentionally outside E2E-proof scope. Requires `proof_exempt_reason`; coverage reports the requirement `not_applicable` with that reason | | proof_exempt_reason | No | string | Required when `proof_exempt` is true — the reviewable justification surfaced in coverage rows | | retired_reason | No | string | Required when `status` is `retired`: why the behavior no longer exists, with the date or change that retired it. `kb_upsert` refuses `status: retired` without it, and `kibi check` blocks a hand-edited one under `retired-reason-missing` | | approved_by | No | string | Exception requirements only: the human who approved the exception. An exception that `exempts` a requirement makes its specified success scenarios feasible only when `approved_by` is non-empty; without it the advisory `exception-unapproved` check reports the exception | | approval_ref | No | string | Optional reference to the exception's approval record (ticket, ADR or review link). When an agent recorded the exception (`origin.kind: agent`), the advisory `exception-approval-self-attested` check asks for `approval_ref` and `origin.approved_by` | | rationale | No | string | Why the requirement exists, in one or two sentences from whoever stated the intent. Explanation only, never part of the checked meaning. The advisory `requirement-rationale-missing` check asks human- and agent-authored requirements for it unless the body has a `## Rationale` or `## Why` section or an ADR is linked | | exempts_claims[] | No | array[string] | Exception requirements only: claim keys (`CLAIM-...`) of the exempted requirement's clauses this exception waives. Absent, it waives the whole requirement; present, only constraints grounded by facts carrying a listed `claim_key`. The canonical `exception-claim-keys` check requires every key to be a claim of a requirement it `exempts` | | semantic_text | No | string | Requirement-only normalized authored prose that anchors semantic byte spans | | logic_claims | No | array[string] | Requirement-only manifest of stable atomic claim keys | | semantic_clauses | No | array[string] | Reviewed atomic decomposition override used against the exact semantic source | | semantic_inventory_version | No | string | `kibi.semantic-inventory.v1` for source-bound ledgers | | semantic_source_field | No | string | `semantic_text`, `text_ref`, or `title`, identifying the field that owns ledger byte spans; new authored requirements prefer `semantic_text` | | semantic_source_hash | No | string | SHA-256 of the exact semantic source text | | semantic_inventory | No | array[object] | Proposition ledger with exact claim text, UTF-8 byte span, role, status, and optional semantic key | | pair_reviews[] | No | array[object] | Verdicts on a pair of requirements whose unmodeled claims cannot be modeled, which settle `related-requirement-unmodeled` (see [Related requirements with unmodeled claims](inference-rules.md#related-requirements-with-unmodeled-claims)). Each entry has `with` (the other requirement, linked by a `relates_to` edge), `verdict` (`no_conflict` with `separated_by`, `interacts` with `resolved_by`, or `conflict`, which never settles the pair), `claims` (the `claim_key` of each unmodeled claim) and `origin` (`kind` `human` or `agent`; on a pair with a must or firm requirement, an agent verdict counts only with `approved_by` from a person). Model the claims first; a verdict is the fallback | **Canonical Example: REQ + SCEN + TEST (Golden Path)** ```yaml # .kb/requirements/REQ-auth-login.md --- id: REQ-auth-login title: User authentication status: open created_at: 2026-03-10T10:00:00Z updated_at: 2026-03-10T10:00:00Z source: .kb/requirements/REQ-auth-login.md links: - type: specified_by target: SCEN-auth-login-success --- # .kb/scenarios/SCEN-auth-login-success.md --- id: SCEN-auth-login-success title: Login with valid credentials status: active created_at: 2026-03-10T10:01:00Z updated_at: 2026-03-10T10:01:00Z source: .kb/scenarios/SCEN-auth-login-success.md --- # .kb/tests/TEST-auth-login-success.md --- id: TEST-auth-login-success title: Login test status: passing created_at: 2026-03-10T10:02:00Z updated_at: 2026-03-10T10:02:00Z source: .kb/tests/TEST-auth-login-success.md links: - type: validates target: SCEN-auth-login-success --- ``` **Generic Link Shorthand:** ```yaml links: - ADR-session-token-storage - FACT-auth-session-ttl ``` Plain string Markdown `links` entries are imported as generic `relates_to` relationships. Use typed link objects or relationship rows when the semantic relationship matters. **Relationship Rows Example:** ```yaml # Relationship: REQ-auth-login specified_by SCEN-auth-login-success relationship: type: specified_by source: REQ-auth-login target: SCEN-auth-login-success created_at: 2026-03-10T10:03:00Z created_by: analyst source: .kb/requirements/REQ-auth-login.md --- # Relationship: REQ-auth-login verified_by TEST-auth-login-success relationship: type: verified_by source: REQ-auth-login target: TEST-auth-login-success created_at: 2026-03-10T10:04:00Z created_by: qa source: .kb/requirements/REQ-auth-login.md ``` > **Rule:** Never embed scenarios or tests inside requirement records. Always create separate files for each entity and link them with explicit typed `links` entries or relationship rows (`specified_by`, `verified_by`). Plain string `links` are generic `relates_to` only. **Strict Fact Modeling (Normative Lane):** - Preserve readable requirement prose, but decompose the entire assertive body into atomic propositions with `kb_semantic_advisor`. Context-only rationale, examples, and subjective commentary remain in the inventory as `nonlogical` and do not enter `logic_claims`. - For a current requirement write, persist the receipt's `inventory_contract` as `semantic_inventory_version`, `semantic_source_field`, and `semantic_source_hash`. Ledger spans are UTF-8 byte offsets into that exact field; the advisor canonicalizes repeated identical normalized claims to one proposition at the first source occurrence, while duplicate keys/spans in a submitted ledger, source drift, and silent omission are rejected before mutation. - Store exactly all returned assertive keys in the requirement `logic_claims` manifest. Each `modeled` entry must resolve through exactly one `requires_property`, `requires_predicate`, or `requires_rule` edge to a fact carrying the same `claim_key`; explicit `ambiguous`, `ontology_gap`, or `missing` entries remain ingestible but unresolved. - `logic-coverage` checks manifest-to-ground-fact correspondence and is enabled by default. Requirements without manifests remain a gradual-backfill case; quality diagnostics identify every current requirement with this debt, while the default rule prevents explicitly modeled manifests from drifting. - New contradiction-sensitive requirements should use the strict fact lane: - one `fact_kind: subject` fact linked via `constrains` - one `fact_kind: property_value` fact linked via `requires_property` - For v1, the supported evolution path is append-only: create a new requirement and link it to the prior one with `supersedes`. - Automated modeling via `kb_model_requirement` can produce deterministic write plans. `/kibi-bootstrap` returns `kibi.bootstrap-plan.v1`; bootstrap writes require a user-facing preview and explicit approval before calling `kb_apply_plan`. - **Low-confidence downgrade:** If confidence is < 0.7, requirements are downgraded to `observation` facts to avoid false-positive contradictions. - Use `observation` and `meta` facts for runtime evidence, historical notes, and governance context that should not participate in contradiction blocking. **Canonical Contradiction-Safe Example:** ```yaml # .kb/facts/FACT-USER-ROLE.md --- id: FACT-USER-ROLE title: User Role Assignment status: active created_at: 2026-03-24T00:00:00Z updated_at: 2026-03-24T00:00:00Z source: .kb/facts/FACT-USER-ROLE.md fact_kind: subject subject_key: user.role_assignment --- # .kb/facts/FACT-LIMIT-3.md --- id: FACT-LIMIT-3 title: Maximum of Three status: active created_at: 2026-03-24T00:00:00Z updated_at: 2026-03-24T00:00:00Z source: .kb/facts/FACT-LIMIT-3.md fact_kind: property_value subject_key: user.role_assignment property_key: max_roles operator: lte value_type: int value_int: 3 --- # .kb/requirements/REQ-user-role-limits.md --- id: REQ-user-role-limits title: Users can now have 3 roles status: open created_at: 2026-02-20T13:06:00Z updated_at: 2026-03-24T00:00:00Z source: .kb/requirements/REQ-user-role-limits.md links: - type: constrains target: FACT-USER-ROLE - type: requires_property target: FACT-LIMIT-3 - type: supersedes target: REQ-user-role-assignment --- ``` ``` **Schema Migration:** Older KBs can be upgraded to the latest schema using the `migrate` command. This ensures all entities are compatible with the latest contradiction and validation rules. ```bash # Check if migration is required kibi status # Perform the migration kibi migrate --yes ``` Schema version 2 introduces strict symbol granularity. During migration, existing coarse file/module links that can be explained by older ontology data are marked with `granularity_reason: legacy-link`; new or updated symbol traceability should target the narrow function, class method (`ClassName.methodName`), class, or other behavioral symbol whenever one exists. Interfaces, type aliases, and enums are `type-shape` symbols; they describe code shape and do not by themselves block a coarse behavioral link. **Invalid Example (Prohibited):** ```yaml # WRONG - embedded scenario --- id: REQ-auth-login title: User authentication scenarios: - given: user is on login page when: they enter valid credentials then: they are logged in --- ``` #### Scenario (`scenario`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Scenario summary | | status | Yes | string | draft, active, deprecated | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | | expects | No | enum | Intended outcome: `success`, `rejection` or `error` | A scenario that sets `expects: success` and links the values its outcome depends on with `assumes` (scenario → `property_value` fact) is checked against current requirements by the canonical `scenario-feasibility` rule, through their `requires_property` facts and their typed `requires_rule` rules alike. A rule restricting an action ("checkout may happen only when the cart total is positive") governs the scenarios that perform it: those `specified_by` the requirement, or that assume a predicate fact naming the action. A requirement constraint only applies inside the validity window (`valid_from`/`valid_to`) of the fact that grounds it, and a scoped one only in its scope. When a current requirement forbids an assumed value (for example it requires `client.call_quota.remaining > 0` and the scenario assumes `= 0`), or several assumptions can only hold together with a value the requirements forbid (it requires `<= 5` and the scenario assumes `>= 5` and `!= 5`), `kb_check` reports the scenario, the requirements and the facts involved, and every requirement the scenario specifies gets the `infeasible_scenario` proof gap. Reuse the requirement's `subject_key` and `property_key` in the assumption fact: a differently named property is not compared, and no violation is not proof the scenario is feasible. Scenarios that expect `rejection` or `error` are not checked by `scenario-feasibility`. To allow an intended exception without weakening the rule, record a human-approved exception requirement that `exempts` the base requirement, is `specified_by` the scenario, and sets `approved_by` (optionally `approval_ref`). The base requirement stays current and unchanged, and the exception covers only the scenarios it specifies. An exception without `approved_by` does not exempt anything; the violation then says the exception is not approved. To waive one clause of a multi-clause requirement, list that clause's claim key in `exempts_claims`: the other clauses still govern the scenario. A claim that quantifies over a collection (`each`, `every`, `all`) or bounds a cardinality (`exactly`, `at least`, `at most`, `no more than`) must be grounded on what varies: an integer count or bound, a set fact, a rule over a variable, or a state machine. While every fact grounding it is a boolean `property_value` or a ground `predicate`, the requirement gets the `dimension_unrepresented` proof gap. When the quantifier word ranges over nothing, the grounding fact can record `dimension_waiver` (why) and `dimension_waiver_approved_by` (the person who accepted it); only an approved waiver closes the gap. See [proof-ladder.md](proof-ladder.md#5b-quantified-claims). A typed property claim also yields edge cases: the bound and the class past it, zero, one and many for an integer count, each set member and the value outside the set. Each case the claim predicts is refused needs a scenario that assumes a value in that class and expects rejection; otherwise the requirement gets the `uncovered_case` proof gap. When the cases are covered another way, the grounding fact can record `case_waiver` (why) and `case_waiver_approved_by` (the person who accepted it); only an approved waiver closes the gap. See [proof-ladder.md](proof-ladder.md#5c-edge-cases). A requirement that grounds a claim is not `tested` while only its happy path is covered: at least one scenario it specifies must set `expects: rejection` (or `error`) and `assumes` a fact that breaks the requirement, either a value the scenario-feasibility analysis finds the requirement forbids or a fact that opposes one of its claim facts directly (the same subject and property with a conflicting value, the opposite polarity of the same predicate, or a predicate fact instantiating an atom of a rule over predicates). Without one the requirement gets the `happy_path_only` proof gap, whose `suggestedNegatives` propose an opposing fact per claim. A requirement whose claims state only a capability or an output shape, with nothing to refuse, can instead record `failure_side_waiver` (why) and `failure_side_waiver_approved_by` (the person who accepted it). Only an approved waiver closes the gap. A scenario that expects rejection or error while current requirements govern and permit everything it assumes is reported by the canonical `scenario-outcome-mismatch` rule. See [proof-ladder.md](proof-ladder.md#5a-failure-side). A success scenario whose feasibility cannot be decided (it assumes nothing, its assumptions contradict each other, it assumes a property no current requirement governing it constrains, an assumption's type, unit or operator cannot be compared with the requirement's, the governing requirements admit no common value, the assumptions neither satisfy nor refute a governing rule's conditions, or it conflicts only with constraints whose validity window may or may not cover its time) is reported by the advisory `scenario-feasibility-unknown` rule and the `unknown_scenario_feasibility` proof advisory; it is never counted as feasible. **Example:** ```yaml --- id: SCEN-auth-login-success title: Sample scenario SCEN-auth-login-success status: active created_at: 2026-02-17T13:00:00Z updated_at: 2026-02-17T13:00:00Z source: https://example.com/fixtures/scenarios/SCEN-auth-login-success tags: - sample --- ``` #### Test (`test`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Test summary | | status | Yes | string | passing, failing, skipped, pending | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | | verification_scope | No | enum | `unit`, `integration`, or `end_to_end` | | verification_perspective | No | enum | `internal` or `consumer` | | proof_contract | No | object | `kibi.proof-contract.v1`: explicit `required_proofs` obligations (`symbol_id` + ecosystem-neutral `target`) executed by one configured integration; requires `verification_scope`. Optional `kind` (`e2e` when absent, `example`, `property`, `exhaustive`, `typecheck`, `arithmetic`, `smt`, `rule`, `state_machine`, `regex`, `source`), `source: {reader, ...}` (required for `source`; `reader` is one of `json`, `yaml`, `glob`, `openapi`, `references`, `schema`, `routes`, `validator` or `prolog`, and each reader's fields are listed in [Project sources](proving-requirements.md#project-sources-routes-schemas-configuration-and-references)), `domain_source: {symbol_id, export?, field?, arg?}` (required for `exhaustive`, `typecheck` and `state_machine`, where it names the transition table or next-state function; `field` reads one field of each record in an `exhaustive` domain, and `arg` the 1-based argument of a SWI-Prolog predicate), `witness: {path}` (required for `typecheck`), `constraint_source: {fact_ids}` or `value_source: [{symbol_id, export?, arg?, measure?} | {source, measure: count}]` (`measure: count` reads a collection's size) (one required for `arithmetic` and `smt`), `predicate_source` and `domains` (maps of `{symbol_id, export?}` keyed by predicate and argument type, required for `rule`; a `domains` entry may instead be `{source}`, and a `predicate_source` entry with `harness_for: [SYM-...]` proves the claim at harness scope; `domains: {state, event}` for a next-state function), `initial_source: {symbol_id}` (`state_machine`), `pattern_source: {symbol_id}` (required for `regex`) and `proves: [CLAIM-...]`, the requirement claims a certificate-kind contract proves (required from schema 12); see [Certificate proof kinds](proving-requirements.md#certificate-proof-kinds) | | proof_bindings | No | array[object] | Optional native-runner bindings (`native_id`, aliases, source coordinates) for proof obligations; provenance metadata, never a contract replacement | | proof_receipts | No | array[object] | Append-only proof-receipt execution history; Kibi writes `kibi.proof-receipt.v2` and still reads `kibi.proof-receipt.v1`; requires `verification_scope` | `proof_receipts` is append-only for authors: never remove or rewrite existing entries, and include the full history when authoring a test file directly. Only the engine shortens a history: `kibi prove` compacts it on ingest to the receipts that can still decide proof, and `kibi proof compact` and `kibi proof prune` are the maintenance commands. Receipts are engine-derived from `kibi.proof-run.v1` producer artifacts — see [proving requirements](proving-requirements.md) for contracts, the `kibi prove` workflow, and the artifact reference. `tags` remain metadata only. They do not alias or replace typed verification fields. Coverage-depth reporting uses typed verification fields before legacy hints. A test with `status: passing` and `verification_scope: end_to_end` supplies structural depth evidence even if it has no `e2e` tag; tag or path heuristics are only fallback evidence for older records. Durable status never supplies conservative proof evidence by itself. Requirement coverage rows can therefore report deterministic depth labels without changing the underlying covered/uncovered decision: - `direct_passing_e2e` — the requirement is directly linked to a passing e2e test. - `scenario_passing_e2e` — a linked scenario is validated by a passing e2e test. - `unit_only` — passing evidence exists, but only at unit scope. - `open_or_nonpassing_tests_only` — tests exist but none are passing. - `scenario_only_no_test` — scenarios exist without executable test evidence. - `no_test_evidence` — no scenario or test evidence is linked. Conservative requirement proof uses receipt history instead. Each `kibi.proof-receipt.v2` (and each older `kibi.proof-receipt.v1`) binds `receipt_id`, `test_id`, typed `scope`, `outcome`, `code_snapshot`, `environment_hash`, `started_at`, `finished_at`, `artifact_digest`, `contract_hash`, execution `fingerprint`, `integration_id`, `producer`, and `command_argv`; a v2 receipt also records the contract `kind`, the `evidence_level` it supports (`proved` or `tested`) and, for a certificate kind, the re-checked `certificate` with its `certificate_digest` or the `certificate_rejection`. History is capped at 50 entries, receipt IDs are unique, finish times increase strictly, and existing entries cannot be removed, changed, or reordered through upsert or incremental sync. Proof accepts only the newest receipt for the deterministic current workspace snapshot when it passed, is not future-dated, and is at most seven days old. Missing, wrong-snapshot, stale, failed, malformed, or future-dated evidence produces explicit proof gaps. `kibi.workspace-snapshot.v2` hashes current versionable code plus requirement, scenario, fact, test-contract, and symbol-manifest inputs. It excludes `.kb/` derived runtime trees, release changesets, general `docs/`, and the `proof_receipts` frontmatter field inside every tracked Markdown file, preventing a receipt from invalidating its own code hash without hiding changes to the surrounding test contract. A receipt bound to an older snapshot hash is not proof of the current snapshot. Rerun `kibi prove` so the receipt matches the snapshot the branch is on now. #### Check output diagnostics `kibi check`, MCP `kb_check`, staged impact checks, and OpenCode scheduled checks use a two-lane output contract rather than modeling audit findings as new entity types: - `violations[]` is the hard correctness lane. Graph, schema, contradiction, query-plan, and staged blocking failures stay here and continue to fail checks. - `qualityDiagnostics[]` is the audit-quality lane. Modeling reviews, coverage-depth reviews, broad requirement fanout, duplicate coordinates, symbol fanout, status misuse, and strict-fact modeling suggestions are advisory unless a diagnostic explicitly sets `blocking: true` or `severity: "error"`. The public severity values are `error`, `warning`, `review`, and `info`. `review` and `info` do not fail checks by default; `warning` is also non-blocking unless paired with `blocking: true`. Integrations should inspect both `severity` and `blocking` instead of treating every diagnostic-like record as a failure. **Example:** ```yaml --- id: TEST-auth-login-success title: Sample test TEST-auth-login-success status: passing created_at: 2026-02-17T13:00:00Z updated_at: 2026-02-17T13:00:00Z source: https://example.com/fixtures/tests/TEST-auth-login-success tags: - sample verification_scope: end_to_end verification_perspective: consumer proof_contract: version: kibi.proof-contract.v1 integration: self-proof required_proofs: - symbol_id: SYM-test-auth-login-success target: default success_policy: all_required_first_attempt proof_receipts: - version: kibi.proof-receipt.v1 receipt_id: PR-TEST-auth-login-success-20260217T1305 test_id: TEST-auth-login-success scope: end_to_end outcome: passed code_snapshot: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa environment_hash: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb started_at: 2026-02-17T13:00:00Z finished_at: 2026-02-17T13:05:00Z artifact_digest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc contract_hash: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd fingerprint: eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee fingerprint_components: contract: 111111111111111111111111111111111111111111111111111111111111111a integration: 222222222222222222222222222222222222222222222222222222222222222a command: 333333333333333333333333333333333333333333333333333333333333333a bindings: 4444444444444444444444444444444444444444444444444444444444444444a producer: 5555555555555555555555555555555555555555555555555555555555555555a integration_id: self-proof producer: name: kibi-command-producer command_argv: [node, scripts/run-proof-producer.mjs] run_outcome: passed proof_results: - symbol_id: SYM-test-auth-login-success target: default outcome: passed binding: aggregate_run attempts: status: unavailable --- ``` See `docs/examples/test-verification-fields.md` for a complete example using both typed fields. #### ADR (`adr`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | ADR summary | | status | Yes | string | proposed, accepted, deprecated, superseded | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | **Example:** ```yaml --- id: ADR-session-token-storage title: Sample ADR ADR-session-token-storage status: accepted created_at: 2026-02-17T13:00:00Z updated_at: 2026-02-17T13:00:00Z source: https://example.com/fixtures/adrs/ADR-session-token-storage tags: - architecture --- ``` #### Flag (`flag`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Flag summary | | status | Yes | string | active, inactive, deprecated | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | **Example:** ```yaml --- id: FLAG-login-rate-limit title: Sample flag FLAG-login-rate-limit status: active created_at: 2026-02-17T13:00:00Z updated_at: 2026-02-17T13:00:00Z source: https://example.com/fixtures/flags/FLAG-login-rate-limit tags: - rollout --- ``` #### Event (`event`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Event summary | | status | Yes | string | active, deprecated | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | **Example:** ```yaml --- id: EVT-user-logged-in title: Sample event EVT-user-logged-in status: active created_at: 2026-02-17T13:00:00Z updated_at: 2026-02-17T13:00:00Z source: https://example.com/fixtures/events/EVT-user-logged-in tags: - domain --- ``` #### Symbol (`symbol`) | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Symbol summary | | status | Yes | string | active, deprecated, removed | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | | sourceFile | No | string | Code source path | | sourceLine | Generated | integer | One-based start line persisted during sync | | sourceColumn | Generated | integer | Zero-based start column persisted during sync | | sourceEndLine | Generated | integer | One-based end line persisted during sync | | sourceEndColumn | Generated | integer | Zero-based end column persisted during sync | **Example:** ```yaml --- id: SYM-login-handler title: Sample symbol SYM-login-handler status: active created_at: 2026-02-17T13:00:00Z updated_at: 2026-02-17T13:00:00Z source: https://example.com/fixtures/symbols/SYM-login-handler tags: - code --- ``` #### Fact (`fact`) Facts support two authoring lanes: - **Strict lane** for normative, contradiction-sensitive knowledge - `subject`: requires `subject_key` - `property_value`: requires `subject_key`, `property_key`, `operator`, `value_type`, and exactly one value field - A scalar obligation such as "Exports must include headers" uses `operator: eq`, `value_type: bool`, `value_bool: true`, and `polarity: require` (or `forbid` for "must not"). Polarity modifies a typed comparison and never replaces it. Schema 7 makes malformed strict fact shapes blocking; `kibi migrate --yes` converts legacy polarity-only facts without changing IDs. - An enumerated set such as "Order status is one of open, paid or shipped" uses `operator: eq`, `value_type: set` and `value_set: [open, paid, shipped]`. An `exhaustive` or `typecheck` certificate can prove a claim grounded by a set fact (see [Binding a certificate to claims](proving-requirements.md#binding-a-certificate-to-claims)); a legacy `allowed_values` fact with a `|`-joined `value_string` reads as the same set. - A claim that every member of a set has a property, such as "Every role in owner and admin must be able to invite members", uses `operator: includes`, `value_type: set`, `value_set: [admin, owner]` and a `property_key` naming the property. `includes` is only valid on set facts: every listed member has the property and other members may have it too, so two such facts never contradict each other, and one contradicts an `eq` set only when it names a member the `eq` set leaves out. A `rule` certificate over the property's predicate proves it. - `subset_of` and `excludes` are also only valid on set facts. "Every environment variable the app reads must be one of DATABASE_URL, PORT or SECRET" uses `operator: subset_of`: the set the code has must stay within the listed members. "Billing must never import node:child_process" uses `operator: excludes` with `property_key: imports`: none of the listed members may appear. A `source` certificate proves both against what Kibi reads from the project (see [Project sources](proving-requirements.md#project-sources-routes-schemas-configuration-and-references)). Set facts with `property_key` `required_fields`, `nullable_fields` or `middleware`, and `reachable_pairs` or `required_waypoints` facts on a state machine, are read the same way. - A required format such as "Invoice numbers must match `INV-[0-9]{6}`" uses `operator: matches`, `value_type: string` and `value_string` holding a JavaScript pattern (read with the `u` flag) that must match the whole string; `matches` is only valid on string facts. A `regex` certificate proves it against the code's pattern. - A `property_value` fact may list `distinct_from: [<subject_key>.<property_key>, ...]`: other value facts that state a different quantity although they share its value. From KB schema 19 `quantity-duplicate` blocks two value facts of current requirements that state one quantity under different keys (equal values, requirements implemented in one source file, and a shared symbol, proof value source or shared key or claim words; see [One quantity under two keys](inference-rules.md#one-quantity-under-two-keys)), unless either names the other there. Say in the fact's body how the two differ; an entry that names no active value fact is reported. - **Context lane** for non-blocking knowledge - `observation` - `meta`: metadata about the KB or the repository rather than a claim about the product. A bootstrap provider fact that records only where an entry came from (a source module, package manifest or layout root with no stated claim) is a `meta` fact tagged `bootstrap:provenance-stub`; search ranks it last, the answer layer never lists it as a note, and gap and coverage reports do not count it as knowledge. - **Ontology lane** for project-local predicate modeling - `predicate_schema`: defines an allowed predicate signature; requires `predicate_name`, `predicate_arity`, `argument_names`, and `argument_types`. May close argument vocabularies with `argument_constants` (allowed values keyed by argument name) and `argument_aliases` (legacy spellings keyed by argument name, each mapped to a declared constant); unlisted arguments stay open. Optional `key_arguments` (a non-empty list of declared argument names) states that those arguments determine the rest; rule contradiction analysis identifies two atoms of the predicate only when their key arguments are identical - `predicate`: stores a ground predicate claim; requires `predicate_name`, non-empty `predicate_args`, and `canonical_key`; may use `polarity: assert` or `deny`; logical coverage also uses the paired `claim_key` and `claim_text` provenance fields - **Logic lane** for conditional and modal requirements - `rule_schema`: declares the stable `kibi.logic.v1` signature used by rule facts - `rule`: stores schema-validated canonical Logic IR JSON, a full `rule_hash`, semantic key, provenance span, and `rule_schema_id` #### Subject facts A `fact_kind: subject` fact is the definition of one thing the product talks about, named by its `subject_key`. Its body is the definition: what the subject is in the product, what it includes and what it is not. From KB schema 16 `kibi check` reads it as such: - `subject-definition-missing` blocks a body shorter than 8 words (each Chinese or Japanese character counts as a word), one that only restates the title or key, one that adds fewer than 3 words of its own beyond the title, the key and function words ("The cart is the cart of the cart." says nothing), and a definition that 3 or more subjects repeat with only their key or title changed. When nobody has said what the subject is, write `Definition not stated:` followed by where it is named and who could define it; that records the gap instead of inventing a definition, and is what bootstrap, `kb_model` and `kb_compile_intent` write on the subjects they create. The older bootstrap body `Subject <key>, shared by the requirements bootstrap planned from ...` is read the same way. - `subject-duplicate` blocks two facts with the same `subject_key`, and two keys that read as one: the same words up to simple plurals (`report.export` and `report.exports`), or key and title words that mostly coincide. An ancestor and its descendant (`report.export` or `report_export` and `report.export.pdf`) and siblings under different parents (`web.drawing.view` and `mobile.drawing.view`) are not duplicates. - Subjects nest. A dotted key sits under its nearest defined prefix (`kibi.cli` is broader than `kibi.cli.check`), and three optional lists name other subject keys: `part_of` (this subject is a part of that one), `kind_of` (this subject is a kind of that one) and `distinct_from` (a similar subject this one is not). Listing the other key in any of them also settles a `subject-duplicate` pair. Every key they name must be defined (`claim-subject-undefined`), and `subject-hierarchy-invalid` blocks a subject that names itself in one of them and a chain of `part_of`, `kind_of` and dotted prefixes that leads back to where it started. ```yaml # .kb/facts/FACT-SHOP-CART.md --- id: FACT-SHOP-CART title: Shopping cart fact_kind: subject subject_key: shop.cart part_of: [shop] distinct_from: [shop.wishlist] --- The products a signed-in customer has chosen to buy and not yet paid for. It holds quantities and prices; it is not the saved wishlist. ``` A requirement's unmodeled claims name the subjects they are about in their inventory entries (`subjects`, below), so `kb_query` with `factKind: subject` and a `subjectKey` lists every current requirement, claim and scenario about a subject or a narrower one. Legacy prose facts without `fact_kind` remain readable during migration, but new requirements should prefer the strict lane when the fact expresses a rule that should block contradictions. `fact` entities represent atomic domain concepts and invariants (for example domain nouns, cardinalities, property values, ontology predicates, and safe rules). Requirements can link to strict facts using `constrains` and `requires_property`, ontology predicate facts using `requires_predicate`, or safe Logic IR rules using `requires_rule`, so domain claims become structural and queryable. When `claim_key` is supplied, `claim_text` is required too, and a fact of any other kind that supplies `claim_text` must also supply `claim_key`. An `observation` or `meta` fact is a non-grounding review note and may quote the claim it is about in `claim_text` without `claim_key`. **Migration note:** schema v4 adds `semantic_inventory`, its source-binding contract, `rule_schema`, `rule`, and `requires_rule` additively. Existing Markdown requirements receive a one-time semantic-hash baseline; the next semantic edit, or any newly added requirement after that baseline, must carry a complete ledger. Projects can adopt the logic lane incrementally by preserving advisor proposition ledgers, adding rule schemas, then linking modeled requirements to safe facts while leaving unresolved states explicit. ### Logic IR facts `rule_ir` is a JSON object with `version: kibi.logic.v1`; it is validated and canonicalized before persistence. It supports typed atoms, variables, conjunction/disjunction, comparisons, bounded counts, temporal intervals, exceptions, and the modalities `assert`, `deny`, `oblige`, `permit`, and `forbid`. `rule_hash` is the full SHA-256 of canonical IR; `semantic_key` is a shorter stable identity for paraphrase convergence. Kibi renders Prolog for inspection, but never evaluates stored source text. `rule-safety` and `rule-verifiability` are blocking checks for new rule records. Requirements also retain a `semantic_inventory` proposition ledger. Each entry binds a claim key and exact claim text to a UTF-8 byte span and one of `modeled`, `ambiguous`, `ontology_gap`, `nonlogical`, or `missing`. An assertive proposition that is not modeled must be explicitly unresolved; prose alone is not logical coverage. From KB schema 16 an unresolved entry (`ambiguous`, `ontology_gap` or `missing`) whose role is `normative`, `condition`, `exception` or `definition` names the subjects it is about as `subjects: [<subject_key>, ...]` (`claim-subject-missing`), and each key must be defined by an active subject fact (`claim-subject-undefined`; see [Subject facts](#subject-facts)). `kibi migrate` suggests a subject for each such entry when its words clearly match one defined subject. Symbol coordinates are generated compiler state. Callers cannot author `sourceLine`, `sourceColumn`, `sourceEndLine`, or `sourceEndColumn` through `kb_upsert`: source-first symbol upserts re-extract the canonical manifest plus `.kb/symbol-coordinates.yaml` before committing, so partial payloads can no longer erase persisted coordinates, and coordinate refresh failures abort the mutation instead of being reported as complete. A file the parser reads only partly because of a local gap (a C `#include`, a Rust macro, a nested HCL block) is not a failure: symbols declared outside its uncovered ranges keep their coordinates, symbols declared inside one get none, and one warning names the file, lines and diagnostics. A file the analyzer cannot read as a whole (a syntax error, which a grammar can also report for valid code such as an `#ifdef` inside an `if`, a timeout, a changed grammar) gives its own symbols no coordinates and is named as a failed refresh; every other file still refreshes. Files past the 64-diagnostic cap merge their local gaps into the fewest ranges that fit, closing first the gaps that hold no symbol start, instead of turning into a whole-file limit. C and C++ include guards, linkage guards and `#if 0` blocks, and Terraform nested blocks, are not gaps. The artifact is version 2: every record carries an identity hash bound to the extraction that produced it and a hash of the source file it was read from, malformed artifacts fail explicit refreshes and mutations closed, and publication is atomic. This lets conservative proof reporting validate the exact source-bound symbols that carry implementation and executable-test evidence; the authored manifest remains coordinate-free and `.kb/symbol-coordinates.yaml` remains the generated source of truth. From schema 13 the artifact is a gitignored local cache, never committed: every `kibi sync` re-extracts only the symbols whose identity or source bytes changed and rebuilds a missing or damaged file, so parallel branches never conflict on it. | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | id | Yes | string | Unique identifier | | title | Yes | string | Fact summary | | status | Yes | string | active, deprecated | | created_at | Yes | ISO 8601 | Creation timestamp | | updated_at | Yes | ISO 8601 | Last update timestamp | | source | Yes | string | Provenance | | tags[] | No | array[string] | Tags | | owner | No | string | Owner/assignee | | priority | No | string | Priority level | | severity | No | string | Severity level | | links[] | No | array[string] | URLs | | text_ref | No | string | Markdown/doc pointer | **Example:** ```yaml --- id: FACT-USER-ROLE title: User Role Assignment status: active created_at: 2026-02-20T13:00:00Z updated_at: 2026-02-20T13:00:00Z source: .kb/facts/FACT-USER-ROLE.md tags: - domain - auth --- ``` --- ## Relationship Types Kibi supports relationship types listed below. Each relationship has metadata: | Property | Required | Type | Description | |--------------|----------|----------------|--------------------------------------------------| | created_at | Yes | ISO 8601 | Creation timestamp | | created_by | Yes | string | Creator identifier | | source | Yes | string | Provenance | | confidence | No | string/number | Optional confidence level | ### Relationship Table | Relationship | Source Entity | Target Entity | Description | |---------------------|----------------------|----------------------|--------------------------------------------------| | depends_on | req | req | Requirement depends on another requirement | | specified_by | req | scenario | Requirement is specified by a scenario | | verified_by | req/scenario | test | Requirement or scenario is verified by a test | | validates | test | req/scenario | Test validates a requirement or scenario | | implements | symbol | req | Symbol owns or implements requirement behavior | | covered_by | symbol | test | Production symbol has coverage evidence from a test | | executable_for | symbol | test | Symbol is executable test code for a test entity | | constrained_by | symbol | adr | Symbol constrained by ADR | | constrains | req | fact | Requirement constrains a specific domain fact | | requires_property | req | fact | Requirement requires a property fact/value | | requires_predicate | req | fact | Requirement requires a ground ontology predicate fact | | requires_rule | req | fact | Requirement requires a schema-validated kibi.logic.v1 rule fact | | guards | flag | symbol/event/req | Flag guards symbol, event, or requirement | | publishes | symbol | event | Symbol publishes event | | consumes | symbol | event | Symbol consumes event | | supersedes | adr | adr | The source ADR formally replaces the target ADR. The target is expected to carry status: archived or deprecated | | supersedes | req | req | The source requirement replaces the target requirement; the target stops being current | | restates | req | req | The source requirement intentionally restates a current requirement (e.g. a product requirement echoed in a platform requirement). Both stay current; `domain-redundancy` is suppressed for the pair | | assumes | scenario | fact | The scenario's outcome depends on this `property_value` fact holding; checked by `scenario-feasibility` when the scenario expects success | | exempts | req | req | An approved exception requirement exempts the scenarios it specifies from the target requirement's property and rule constraints (only the clauses in `exempts_claims` when set); the target stays current | | relates_to | a | b | Generic relationship (escape hatch) | --- ### Relationship Examples **depends_on** ```yaml # req REQ-auth-login-lockout depends_on req REQ-auth-login relationship: type: depends_on source: REQ-auth-login-lockout target: REQ-auth-login created_at: 2026-02-17T13:10:00Z created_by: analyst source: https://example.com/fixtures/requirements/REQ-auth-login-lockout ``` **specified_by** ```yaml # req REQ-auth-login specified_by scenario SCEN-auth-login-success relationship: type: specified_by source: REQ-auth-login target: SCEN-auth-login-success created_at: 2026-02-17T13:15:00Z created_by: analyst source: https://example.com/fixtures/requirements/REQ-auth-login ``` **verified_by** ```yaml # req REQ-auth-login verified_by test TEST-auth-login-success relationship: type: verified_by source: REQ-auth-login target: TEST-auth-login-success created_at: 2026-02-17T13:20:00Z created_by: qa source: https://example.com/fixtures/tests/TEST-auth-login-success ``` `verified_by` has one frozen meaning: a requirement or scenario is verified by a test. Direct `req -> test` is fallback only when no scenario exists. Prefer `req -> scenario -> test`. Facts are not directly verified by tests. Model the behavior through a requirement: link the requirement to strict or observation facts with `constrains`, `requires_property`, or `requires_predicate`, then link the requirement or scenario to the test with `verified_by` / `validates`. **validates** ```yaml # test TEST-auth-login-success validates scenario SCEN-auth-login-success relationship: type: validates source: TEST-auth-login-success target: SCEN-auth-login-success created_at: 2026-02-17T13:22:00Z created_by: qa source: https://example.com/fixtures/tests/TEST-auth-login-success ``` `validates` is the inverse edge for req/scenario ↔ test links. **implements** ```yaml # symbol SYM-login-handler implements req REQ-auth-login relationship: type: implements source: SYM-login-handler target: REQ-auth-login created_at: 2026-02-17T13:25:00Z created_by: dev source: https://example.com/fixtures/symbols/SYM-login-handler ``` `implements` is frozen to requirement ownership only (`symbol -> req`). **covered_by** ```yaml # symbol SYM-login-handler covered_by test TEST-auth-login-success relationship: type: covered_by source: SYM-login-handler target: TEST-auth-login-success created_at: 2026-02-17T13:30:00Z created_by: dev source: https://example.com/fixtures/tests/TEST-auth-login-success ``` `covered_by` is frozen to production coverage evidence only (`symbol -> test`). **executable_for** ```yaml # symbol SYM-test-auth-login-success executable_for test TEST-auth-login-success relationship: type: executable_for source: SYM-test-auth-login-success target: TEST-auth-login-success created_at: 2026-02-17T13:32:00Z created_by: dev source: https://example.com/fixtures/symbols/SYM-test-auth-login-success ``` `executable_for` is frozen to executable test code identity only (`symbol -> test`). For the canonical symbol taxonomy, integration/e2e N/A rubric, and anti-blanket requirement checklist, see [Symbol Traceability Taxonomy](symbol-traceability-taxonomy.md). **constrained_by** ```yaml # symbol SYM-login-handler constrained_by adr ADR-session-token-storage relationship: type: constrained_by source: SYM-login-handler target: ADR-session-token-storage created_at: 2026-02-17T13:35:00Z created_by: architect source: https://example.com/fixtures/adrs/ADR-session-token-storage ``` **guards** ```yaml # flag FLAG-login-rate-limit guards req REQ-auth-login relationship: type: guards source: FLAG-login-rate-limit target: REQ-auth-login created_at: 2026-02-17T13:45:00Z created_by: devops source: https://example.com/fixtures/flags/FLAG-login-rate-limit ``` **publishes** ```yaml # symbol SYM-login-handler publishes event EVT-user-logged-in relationship: type: publishes source: SYM-login-handler target: EVT-user-logged-in created_at: 2026-02-17T13:50:00Z created_by: dev source: https://example.com/fixtures/symbols/SYM-login-handler ``` **consumes** ```yaml # symbol SYM-login-handler consumes event EVT-user-logged-in relationship: type: consumes source: SYM-login-handler target: EVT-user-logged-in created_at: 2026-02-17T13:55:00Z created_by: dev source: https://example.com/fixtures/symbols/SYM-login-handler ``` **constrains** ```yaml # req REQ-user-role-assignment constrains fact FACT-USER-ROLE relationship: type: constrains source: REQ-user-role-assignment target: FACT-USER-ROLE created_at: 2026-02-20T14:00:00Z created_by: analyst source: .kb/requirements/REQ-user-role-assignment.md ``` **requires_property** ```yaml # req REQ-user-role-assignment requires_property fact FACT-LIMIT-2 relationship: type: requires_property source: REQ-user-role-assignment target: FACT-LIMIT-2 created_at: 2026-02-20T14:01:00Z created_by: analyst source: .kb/requirements/REQ-user-role-assignment.md ``` **relates_to** ```yaml # Generic relationship between any two entities relationship: type: relates_to source: ENTITY-A target: ENTITY-B kind: custom created_at: 2026-02-17T14:00:00Z created_by: analyst source: https://example.com/fixtures/entities/ENTITY-A ``` **supersedes** ```yaml # adr ADR-session-token-storage-v2 supersedes adr ADR-session-token-storage relationship: type: supersedes source: ADR-session-token-storage-v2 target: ADR-session-token-storage created_at: 2026-02-20T10:00:00Z created_by: architect source: https://example.com/fixtures/adrs/ADR-session-token-storage-v2 ``` **restates** ```yaml # req REQ-billing-invoice-retention restates req REQ-platform-record-retention relationship: type: restates source: REQ-billing-invoice-retention target: REQ-platform-record-retention created_at: 2026-09-28T10:00:00Z created_by: analyst source: .kb/requirements/REQ-billing-invoice-retention.md ``` **assumes** and **exempts** ```yaml # scenario SCEN-promo-zero-quota-call expects success and assumes zero quota links: - type: assumes target: FACT-quota-remaining-zero # exception req REQ-quota-promo-exception exempts REQ-quota-call and specifies the scenario approved_by: Product owner approval_ref: DEC-quota-promo # optional: waive only these clauses of REQ-quota-call exempts_claims: [CLAIM-0123456789ABCDEF] links: - type: exempts target: REQ-quota-call - type: specified_by target: SCEN-promo-zero-quota-call ``` --- ## Body contract The Markdown body is where context lives; front matter is the checked meaning. Sections are split by ATX headings. The context headings are `Context`, `Rationale`, `Why`, `Background`, `Source`, `Notes` and `Evidence` (case-insensitive prefix match); a context section runs to the next heading of the same or higher level. | Type | What counts as context | Body should carry | | --- | --- | --- | | `req` | Only text under context headings | The statement, `## Context` (why, who asked, constraints), `## Source` (blockquoted excerpt and reference) | | `scenario` | All non-heading prose | Given/When/Then prose and the assumptions it depends on | | `test` | All non-heading prose | What it asserts, how (fixture, entry point), what would make it a false pass | | `adr` | All non-heading prose | Context, Decision, Consequences | | `fact` (`observation`, `meta`) | All non-heading prose | What was seen, where, when, how confirmed | | `symbol`, `flag`, `event`, other fact kinds | Exempt | Front matter is the content | The blocking `entity-context-missing` check requires at least 12 words of context that are not a restatement of the title (normalized token-set Jaccard below 0.8; a requirement is also compared with `semantic_text`). Never invent a reason: write "Reason not stated" and the source. Context sections of a requirement are excluded when `semantic_text` is derived from the body, and Kibi writes `semantic_text` explicitly in front matter on every requirement it authors, so adding context never changes claim spans or hashes. Entities that predate the rule are tagged `review:context-missing` by the schema 8 migration (see `kibi migrate`), which records their ids in `.kb/manifest.json`; those are counted by the advisory `entity-context-acknowledged` diagnostic instead of blocking. The tag is reserved for them: on any other entity it is still a violation, so add context (who asked, the source, or "Reason not stated") instead of tagging. ## Notes - The schema is the eight entity types and the relationship catalog in this document. - IDs must be stable and unique. Set an explicit frontmatter `id` named by what the entity governs (`<TYPE>-<area>-<behavior>`, e.g. `REQ-cli-gc`) and keep the filename stem equal to it; never pick the next free number. A missing `id` falls back to a path-and-title hash that changes on rename. `entity-id-style` reports stem mismatches and newly created numeric IDs; legacy numbered entities are grandfathered. - Relationship metadata supports audit and conflict resolution. - Status values are entity-type specific (see above). --- End of schema documentation. --- # Inference rules URL: https://getkibi.dev/reference/inference-rules.html > The deterministic validation, contradiction, and coherence rules Kibi enforces. Kibi includes deterministic derived predicates for internal analysis and automation. These predicates are not exposed as a raw public inference surface. ## Core Predicates (`packages/core/src/kb.pl`) - `transitively_implements(Symbol, Req)` - `transitively_depends(Req1, Req2)` - `impacted_by_change(Entity, Changed)` - `affected_symbols(Req, Symbols)` - `coverage_gap(Req, Reason)` - `untested_symbols(Symbols)` - `stale(Entity, MaxAgeDays)` - `orphaned(Symbol)` - `conflicting(Adr1, Adr2)` - `deprecated_still_used(Adr, Symbols)` - `current_adr(Id)` - `superseded_by(OldId, NewId)` - `adr_chain(AnyId, Chain)` - `contradicting_reqs(ReqA, ReqB, Reason)` - `predicate_schema(FactId, Namespace, Name, Arity, ArgumentNames, ArgumentTypes)` - `predicate_fact(FactId, Namespace, Name, Args, Polarity)` - `logic_rule_from_props(Props, Rule)` - `logic_rule_safety(Props, Errors)` - `logic_rule_conflict(RuleA, RuleB, Status)` ## Must-priority coverage semantics `coverage_gap(Req, Reason)` (rule `must-priority-coverage`) applies only to a current must-priority requirement. A requirement owes no scenario or test coverage when another requirement `supersedes` it, when its status is `deprecated`, `superseded`, `archived`, `removed`, `deleted` or `rejected`, or when it is `closed` without the `implemented` tag (the same reading of `closed` the coverage-depth review uses). A closed requirement tagged `implemented`, and a requirement with any other status or no status, keeps the obligation. ## Symbol coverage semantics **Scenario-aware coverage**: When a requirement has `specified_by(Req,Scenario)`, direct `verified_by(Req,Test)` or `validates(Test,Req)` does NOT satisfy symbol-coverage. The canonical path requires `verified_by(Scenario,Test)` or `validates(Test,Scenario)`. **One rule for full and staged checks**: `symbol_no_req_coverage(Symbol, Reason)` decides `symbol-coverage` in `kibi check`. The staged gate evaluates the same predicate through `changed_symbol_no_req_coverage(ExtraSymbols, Symbol)`, restricted to the changed source symbols (the `changed_symbol/1` overlay facts) plus `ExtraSymbols`, the symbols whose staged `.kb/symbols.yaml` entry changed. `checks:check_changed_symbol_coverage(ExtraSymbols, Violations)` renders those as the same `symbol-coverage` violations full check reports. The staged knowledge base projects the requirement, scenario and test graph from the index, so scenario-awareness holds for the commit being made. ## Symbol granularity semantics `symbol-granularity` (full check) and `symbol_granularity_violation` (staged gate) share one TypeScript predicate: a symbol with an `implements`, `covered_by` or `executable_for` link and no allowed `granularity_reason` violates it when its source file has a narrower behavioral declaration (a member of the symbol's title, or any declaration when the title itself is not extracted). The staged gate judges only declarations a staged hunk touches; full check judges every declaration of the working-tree file, so a clean full check leaves no granularity violation for a later commit to expose. ## Requirement contradiction semantics `contradicting_reqs/3` uses strict requirement semantics only for current requirements and **strict domain facts**. - `current_req/1` excludes deprecated and superseded requirements. - A contradiction requires both requirements to: - `constrains` the same `fact_kind=subject` fact (matched by `subject_key`) in the **strict lane** - `requires_property` a `fact_kind=property_value` fact for that same subject in the **strict lane** - **Non-blocking lane:** `observation` and `meta` facts are explicitly excluded from contradiction inference. They serve as non-blocking notes for bugs, workarounds, and historical context. - Conflict classes currently covered: - exact-value conflicts like `eq pending` vs `eq granted` - numeric conflicts decided exactly: two comparisons conflict when no real value satisfies both. Strict bounds count, so `gt 0` vs `eq 0` and `lte 0` vs `gt 0` conflict while `gte 0` vs `eq 0` does not (`packages/core/src/intervals.pl`). When both sides are `value_type: int` the comparison is over the integers: `gt 0` vs `lt 1` conflicts (no integer lies between them), fractional bounds tighten to the nearest integer, and an `eq` with a fractional value admits no integer. A mixed `int`/`number` pair is compared over the reals, and a `number` keeps real semantics after unit canonicalization even when its value is integral (`number gt 0` vs `number lt 1` do not conflict) - polarity conflicts like `require` vs `forbid` on the same normalized tuple - Scope and validity windows only conflict when they intersect. - **Readiness Levels:** Requirements must pass strict readiness checks (e.g., valid `subject_key`, matching `property_key`, valid operator) before participating in contradiction checks. - Contradiction detection covers exact-value, boolean/enum, numeric range, and polarity conflicts. Prose-only requirements without strict fact modeling are not checked for contradictions. - **Semantic advisor receipts:** MCP preflight and write responses may warn that prose looks machine-checkable but unmodeled, and may include draft strict-property, predicate, ambiguity-observation, or ontology-gap suggestions. These suggestions are advisory. They do not add contradiction semantics unless the requirement is linked to strict facts or predicate facts. - **Automation:** The modeling pipeline is fully automated and does not require human approval for high-confidence (>= 0.7) claims. ### Writes the contradiction check refuses `kb_upsert` runs the check at commit time and in its dry run. A requirement write is refused when the requirement contradicts any current requirement. A fact write is refused when it makes two current requirements grounded on the fact (`requires_property`, `requires_predicate`, `requires_rule` or `constrains`, from the store or from the write's own relationships) contradict where they did not before; a contradiction the KB already held is `kb_check`'s finding and does not block an unrelated edit of the fact. The refusal (`SEMANTIC_CONTRADICTION`) names every pair. `kb_apply_plan` stages every step and then runs the check once for the whole plan, so a change to a fact and to the requirement it would otherwise conflict with lands together. A value fact write that is accepted, and changes the fact's operator, value or unit or creates the fact, lists the other current requirements on the same quantity under `siblings`: those grounded on the fact (`shared_fact`), and those grounded on another fact with the same `subject_key` and `property_key`, or on a fact the `quantity-duplicate` pairing below matches by the value before or after the write (`same_quantity`). Each entry has the requirement's id, title and firmness, the fact, its subject, property and value, the requirement's claim text, and `statesOldValue`: the claim text still contains the old value and not the new one (a literal comparison), or a `same_quantity` fact still holds the old value. Each sibling is also the first lines of `warnings` and a required entry in `nextActions` with a ready input: a `kb_upsert` of a `default` or `exploratory` sibling (its `type`, `id`, `title` and `status`), to which the new value is added so it is updated in the same change, and a `kb_query` of a `firm` one (`includeBody: true`), which the person decides on before anything touches it. Supersede or scope the requirements when the person's change does not cover a sibling. ### Rule (logic IR) conflicts Typed `kibi.logic.v1` rules with opposing modalities (oblige or permit vs forbid) are compared three-valued: - `contradiction`: neither rule has an exception, and either the two rules are identical (up to variable names) or one rule's conditions always imply the other's; in both cases the shared condition must provably hold for some instance. A condition is only proven satisfiable when every comparison in it was translated exactly, the declared functional dependencies are consistent, it contains no negation, disjunction, count or temporal relation, and its constraints admit a value. Identical rules whose condition cannot hold (`X > 0` and `X < 0`, `X < X`, or two different values of a keyed predicate) are `disjoint`; identical rules whose condition the fragment cannot read (such as `X < Y` between two different variables) stay `unresolved`. - `disjoint`: the actions differ, the scopes or validity windows do not intersect, the conditions provably cannot hold together, or one rule's exception is implied by the other rule's conditions. - `unresolved`: the rules may overlap but the fragment cannot decide it. Comparisons of a variable with itself are decided exactly (`X < X` never holds, `X =< X` always does). Rule variables declared `int` or `integer` range over the integers, so `N > 0` and `N < 1` cannot both hold for them. A variable shared by both rules (through the action or a keyed predicate) counts as an integer for a `disjoint` verdict only when every declaration of it is `int` or `integer`; `N: int, N > 0` against `N: number, N < 1` is not `disjoint`, since 0.5 satisfies the `number` reading. A `contradiction` verdict needs a witness that satisfies every declaration, so there the variable is an integer as soon as one declaration says so. **Same-fact assumption.** Condition atoms of the two rules are read as the same fact only when their predicate declares a functional dependency: a `predicate_schema` fact with `key_arguments` names the arguments that determine the rest. Two atoms of that predicate whose key arguments are identical must agree on every other argument. With `key_arguments: [sensor]` on `reading(sensor, value)`, `permit act(C) :- reading(C, X), X > 0` and `forbid act(C) :- reading(C, Y), Y =< 0` are `disjoint`. Without the declaration a predicate is multivalued (a sensor may have several readings), so the same pair is `unresolved`, never `disjoint`. The advisory `rule-key-arguments-missing` check lists opposing rule pairs that are `unresolved` only for this reason. For each condition predicate (namespace, name, arity) without `key_arguments`, it tries every candidate key set (each non-empty proper subset of the argument positions, for predicates of arity 2 to 6) on its own, and reports the predicate with the key sets that would decide the pair; when no single declaration does, it also tries declaring all of them keyed on every argument but the last. A pair that stays undecided whatever is declared (for example because of `X < Y`) is not reported. The finding is a prompt, not a proof: declare the keys only when the predicate really is single-valued per key. ### One quantity under two keys Contradiction checks compare facts on one `subject_key` and `property_key`, so a limit recorded twice under two keys is never compared with itself: a change under one key leaves the other stating the old value and every check still passes. From KB schema 19 the canonical `quantity-duplicate` rule blocks that split. Two active `property_value` facts, each grounded by a current requirement through `requires_property`, state one quantity when all three hold: - their values are equal and comparable: numbers after unit canonicalization (`ms`, `s`, `min`, `h`; bytes, `kb`, `mb`) other than 0 and 1, or sets of at least two members. Booleans and strings are never compared; - their requirements are implemented (`implements` in `.kb/symbols.yaml`) by symbols in one source file; - one signal holds: the requirements share an implementing symbol, the proof of one fact reads its value (`proof_contract.value_source`) from a symbol that implements the other's requirement, or the property keys, or the claim texts, share at least half the content words of the shorter. A pair grounded by one requirement is not reported (`subject-key-identity` and `domain-redundancy` read those), and neither is a pair where either fact lists the other's `subject_key.property_key` under `distinct_from`. A `distinct_from` entry on a grounded value fact that names no active value fact is reported too, since it exempts nothing. To settle a pair, either ground both claims on one key (and move the facts scenarios assume on the old key with them), or add `distinct_from` and say in the fact's body how the two quantities differ. ### Unmodeled clauses are not "no conflict" The proof ladder's contradiction stage reports `status: unresolved` with `outcome: analysis_incomplete` (reason `unresolved_propositions`) when a requirement has semantic-inventory propositions that are not modeled, even if no conflict was found among the modeled ones. Absence of a conflict only means something once every clause is grounded. ### Related requirements with unmodeled claims `domain-contradictions` compares grounded facts only, so two related requirements could disagree in claims nobody modeled. From KB schema 18 the canonical `related-requirement-unmodeled` check blocks a current requirement with an unmodeled rule claim (an inventory entry with status `missing`, or `ontology_gap` or `ambiguous` on a `normative`, `condition`, `exception` or `definition` claim) against each current requirement it pairs with, through a `relates_to` edge in either direction or a subject both are about. The pair stays blocked until the claims are modeled, one requirement supersedes the other, or a `pair_reviews` entry on either requirement settles it: `no_conflict` with `separated_by`, or `interacts` with `resolved_by` (an active scenario or fact either requirement links, a third current requirement, or a `condition` or `exception` claim key of either, never the two requirements themselves), naming every unmodeled claim by `claim_key`. A verdict counts only while a `relates_to` edge links the pair, a `conflict` verdict never settles it, and on a pair with a must or firm requirement an agent's verdict counts only with `origin.approved_by`. The field is described in [entity-schema.md](entity-schema.md#requirement-req); the full finding text is in `docs/cli-reference.md` under `kibi check`. ### Must requirements need a positive scenario From KB schema 17 the canonical `must-positive-scenario` check requires every current must requirement to be `specified_by` an active scenario with `expects: success` that `assumes` a `property_value`, predicate or rule fact (the subject fact itself does not count) on one of its subjects or a narrower one. That scenario is what lets `scenario-feasibility` (below) refuse the behaviour the requirement promises when another current requirement forbids it. Must requirements that `kibi migrate` recorded under `positiveScenarioAcknowledged` in `.kb/manifest.json` during the schema 17 upgrade are exempt. ## Scenario feasibility A scenario may declare `expects: success | rejection | error` and link the values its outcome depends on with `assumes` (scenario → `property_value` fact). Every assumed value and every value a current requirement requires on the same `subject_key` and `property_key` (through a `requires_property` fact or a typed rule, see the rule lane below) becomes a constraint on that property: values are unit-canonicalized (`6000 ms` compares with `5 s`), and a `forbid` fact contributes the negated operator. Constraints are grouped per property and per scope (an unscoped fact belongs to every scope). The canonical `scenario-feasibility` check reports a success scenario when, in some group: - one assumption and one requirement fact admit no common value (a pairwise witness), or - the assumptions admit a value on their own and no pair conflicts, but the assumptions together with the governing requirement constraints admit none (a joint witness). For example, with `q =< 5` required, the assumptions `q >= 5` and `q != 5` each fit, but together they leave no value. The witness is irreducible: it names the requirements, the assumption facts and the requirement facts of a minimal conflicting set. Numeric constraints are decided exactly with `packages/core/src/intervals.pl`, over the integers only when every constraint in the set is `value_type: int`; other value types support `eq` and `neq`. A string is never coerced to a number, so a `property_value` fact that stores a plain decimal as `value_type: string` where the comparison is numeric (an ordering operator, or an `int`/`number` fact on the same subject and property) drops out of these checks; the advisory `numeric-string-value` check lists such facts with the typed replacement. The scenario-level outcome, the `scenario-feasibility` violations, the proof ladder and the plan what-if analysis all read the same witnesses, so joint infeasibility blocks exactly like a pairwise conflict. **Rule lane.** A current requirement's typed `requires_rule` rule contributes constraints in the same form as a property fact when its body reads subject properties (an atom `namespace:name(Entity, Value)` reads `subject_key: namespace`, `property_key: name`) and it restricts the scenario's action. A `forbid` (or `deny`) rule with one condition on the one property it reads contributes the negated condition: a rule that forbids `checkout(C)` when `cart:total(C, T)` holds unless `T > 0` ("checkout may happen only when the cart total is positive", or "checkout must not happen unless the cart total is positive") requires `cart.total gt 0`, exactly like a `requires_property` fact would. A `permit` or `oblige` rule of kind `constraint` contributes each of its conditions as stated. A rule restricts the scenario only when the scenario performs its head action: it is `specified_by` the requirement (or by an exception to it), or it assumes a predicate fact with the head's namespace and name. A restricting rule that is not one constraint per property (a `forbid` with several conditions, or a body the property reading cannot translate) is decided on its own: it blocks when the assumptions entail every condition, is irrelevant when they refute one, and is otherwise `undecided_rule`. Approved exceptions and scopes apply to rule constraints exactly as they do to property constraints. **Validity windows.** Each requirement constraint is in force over the validity window of the fact that grounds it (`valid_from`/`valid_to` on the `property_value` fact; for a rule, `validFrom`/`validTo` in its IR, else the rule fact's own window). The scenario's time is the intersection of its assumed facts' windows, and is unspecified when none sets one. An unbounded constraint always applies. A bounded constraint does not apply when its window is disjoint from the scenario's, applies when it covers the scenario's whole window, and is undetermined otherwise, including at an unspecified scenario time. A scenario that would conflict only with undetermined constraints gets `unknown` (`undetermined_validity`) rather than a verdict. A requirement stops governing a scenario when a current exception requirement `exempts` it, is `specified_by` the scenario, and carries a non-empty `approved_by` (the human who approved it). An exception without `approved_by` does not exempt: the violation stays and says an exception exists but is not approved. The base requirement is not edited and stays current. An exception that lists `exempts_claims` waives only the constraints grounded by facts carrying one of those claim keys, so waiving one clause of a requirement does not waive its other clauses; the violation names the exception when it does not cover the conflicting clause. The canonical `exception-claim-keys` check requires an exception with `exempts_claims` to exempt a requirement, and every listed key to be a claim of a requirement it exempts (in its `logic_claims`, its semantic inventory or a grounding fact). Every requirement that specifies an infeasible scenario has its scenario stage set to `blocked` and gets the `infeasible_scenario` proof gap, so it cannot be proven through that scenario. Each success scenario gets one analysis outcome: `infeasible` (blocking, above), `feasible_by_exception` (the assumptions conflict only with constraints an approved exception waives), `not_applicable` (no current requirement governs any assumption, because the requirements that constrain the assumed properties are scoped elsewhere, `disjoint_scope`, or not in force at the scenario's time, `outside_validity`), `feasible` (every assumption was compared with every governing constraint on its property and the conjunction of all of them admits a value), or `unknown`. `unknown` means the check could not decide, reported in this order: the scenario assumes nothing (`no_assumptions`); its assumptions contradict each other whatever the requirements say (`contradictory_assumptions`); an assumed `subject_key`/`property_key` is not constrained by any current requirement that governs this scenario (`unmatched_assumption`; a scenario assuming `basket.amount` is not judged against a rule on `cart.total`); an assumption's type, unit or operator cannot be compared with the other constraints on its property, such as a string against an int or seconds against bytes (`incomparable_assumption`); the governing requirements admit no common value on that property, so the scenario cannot be judged until that requirement conflict is resolved (`conflicting_requirements`); a governing rule reads an assumed property but the assumptions neither satisfy nor refute its conditions (`undecided_rule`); or the scenario would conflict only with constraints whose validity window may or may not cover its time (`undetermined_validity`). Unknown feasibility is never reported as passed: `kb_check` lists it under the advisory `scenario-feasibility-unknown` rule (a non-blocking quality diagnostic), and the proof ladder records it in `proofStages.scenarios.unknownFeasibility` and as the `unknown_scenario_feasibility` proof advisory without changing proof status. `kb_compile_intent` and `kb_apply_plan` stage a plan in a rolled-back transaction and compare its contradiction and infeasibility witnesses with the current KB (`introduced`, `removed`, `unchanged`). Any introduced contradiction or infeasible scenario blocks the plan, whichever requirements it names; `kb_apply_plan` refuses it before the first write. ## Predicate ontology semantics The ontology lane encodes project-local domain predicates: - `fact_kind=predicate_schema` defines an allowed predicate signature and its argument names/types. Optional `key_arguments` declares that those arguments determine the remaining ones (a functional dependency used by rule comparison). - `fact_kind=predicate` stores one ground predicate claim with `predicate_args` and optional `polarity` (`assert` or `deny`). - Requirements link to ground predicate facts with `requires_predicate`. - `predicate_schema/6` and `predicate_fact/5` are read-only helpers for querying stored ontology data. - Agents query the same data without writing Prolog: `kb_query` with `predicate` and named `where` arguments, `subjectKey`/`propertyKey` for strict property facts, or `factKind: "predicate_schema"` for the predicate catalog. Two current requirements contradict through ground predicate facts when they link the same predicate with identical arguments and opposite polarity (`Predicate conflict …`), or when they decide the same case differently (`Decision conflict …`): the predicate's key arguments agree, and its closed `decision` argument is `allow` on one side and `deny` on the other. The built-in `permission_rule(actor, action, resource, decision)` is keyed by `actor`, `action` and `resource`, so `permission_rule(coach, read, unassigned_analysis_request, allow)` contradicts `permission_rule(coach, read, unassigned_analysis_request, deny)`. A deny decision counts as a denial whatever its polarity (kb_model writes "cannot" as decision `deny`, polarity `deny`); an allow decision counts only when asserted. A project-local `predicate_schema` for the same signature replaces the built-in keys: it takes part only when it declares `key_arguments` and names a non-key argument `decision`. The check runs in `kb_check` (`domain-contradictions`) and in the commit-time contradiction check of `kb_upsert` (including `dryRun`). Stored `rule` facts use the versioned `kibi.logic.v1` JSON IR. The interpreter decodes only allowlisted terms and evaluates finite closure under resource bounds; it never calls `consult/1`, `assertz/1`, or source-string evaluation. Negation-as-failure requires an explicit closed-world atom and stratified dependencies. Opposing modalities are checked extensionally over known facts and conservatively symbolically: `contradiction`, `disjoint`, or `unresolved` are distinct outcomes, and incomplete analysis is never treated as consistency. Proof consumers should preserve the rule IDs, claim spans, normalized formula, substitutions, and contributing fact chain. The proposition ledger is the completeness boundary: `semantic-completeness` rejects silently missing assertive spans, while `ambiguous`, `ontology_gap`, and `nonlogical` entries remain visible without pretending to prove a rule. Because `domain-contradictions` compares grounded facts only, `related-requirement-unmodeled` blocks a current requirement that still carries `missing` propositions while it `relates_to` a current requirement modeled with strict property or ground predicate facts: the link says the two overlap, so the unmodeled claims must be modeled against the same subject or predicates, or the older requirement superseded, before the check can mean anything for that pair. These predicates remain useful for product features, automation, and future internal services. Public MCP agents should use the curated public surface instead: - `kb_search` - `kb_query` - `kb_status` - `kb_find_gaps` - `kb_coverage` - `kb_graph` - `kb_upsert` - `kb_delete` - `kb_check` ## Advisory strict-fact validation - `strict-fact-shape` - checks only facts that already declare `fact_kind` - ignores legacy prose facts without `fact_kind` - runs by default as a non-blocking quality diagnostic; it does not fail canonical health - can be selected explicitly with `--rules` for a focused audit without changing enforcement class - `domain-contradictions` - checks for logical conflicts between requirements based on shared strict facts - **strict-lane only:** does not promise contradiction detection over all facts; only those explicitly modeled as `subject` + `property_value` participation rules, ground predicate facts (opposite polarity, or opposite allow/deny decisions on the same key arguments), and typed rules - is **enabled by default** for immediate value on normalized data - `kb-consistency` - checks that the facts current requirements name hold together jointly, not only pairwise: three bounds that are each compatible with every other one can still leave no value, and `domain-contradictions` stays silent on them - re-checks a certificate for every result (a model when consistent, an irreducible core when not) with an independent checker; a re-verified contradiction or a rejected certificate blocks - is **canonical and enabled by default**, and also runs in the staged pre-commit gate - `kb-consistency-unresolved` - reports each context the checker cannot compare (mixed value types or units, an unsupported operator or polarity, a contradiction whose validity windows never overlap) - is advisory and non-blocking, and an unresolved context never counts as consistent For a consistency check, run `kb_check` with all three rules (`domain-contradictions`, `kb-consistency`, `kb-consistency-unresolved`). See [Knowledge-base certificates](./proof-ladder.md#knowledge-base-certificates). ### Bug and Workaround Documentation (Non-Blocking Lane) Bug records, incident notes, and workaround documentation should use `observation` or `meta` facts rather than strict fact modeling. Since `observation` and `meta` facts are excluded from contradiction inference, they are appropriate for non-blocking evidence. **Rule:** Use `observation` or `meta` fact_kind for bug/workaround notes. Do NOT create a `flag` entity for bugs unless there is an actual runtime/config gate. ## Ignored Files and Inference Files and directories that match the repository ignore policy are excluded from Kibi's inference pipeline. Ignored files are not read for candidate synthesis and will not be inferred into KB entities by `kb_plan_bootstrap` or other discovery-oriented tools. See the MCP repository ignore policy in `docs/mcp-reference.md` for the full list of honored ignore sources and hard-denied directories. This behavior prevents editor state, tooling caches, and build outputs from polluting the knowledge base with transient or irrelevant artifacts. Global Git excludes (user-level `core.excludesFile`) are not read. Kibi does not automatically remove entities that were created from files that are ignored now. Run `kibi migrate` when a stored layout or schema still needs the current shape; see [Troubleshooting](troubleshooting.md#upgrading-and-branch-recovery). --- # Symbol traceability taxonomy URL: https://getkibi.dev/reference/symbol-taxonomy.html > How code symbols are classified and linked to requirements, and what counts as sufficient traceability. This rubric freezes how Kibi classifies symbols for ownership, production coverage, and integration/e2e expectations. ## Frozen role split - `implements` = direct requirement ownership - `covered_by` = production coverage evidence - `executable_for` = executable test code identity Never use `covered_by` as ownership and never use `executable_for` as production coverage. A symbol that uses `executable_for` must not also carry `implements` or `covered_by`. Current engine alignment: - `executable_for` marks executable test symbols and excludes them from production ownership gates. - Any symbol without `executable_for` stays in the production ownership lane for `implements` and production coverage checks, except a record whose `symbol_role` is `structural`, `type-shape`, `config` or `module` and that has no `implements` link: it records a declaration without claiming requirement ownership, so `symbol-traceability` and `symbol-coverage` do not flag it. A non-behavioral record that does carry `implements` keeps both rules. - The staged gate accepts such a linkless record for a changed declaration only when the extractor does not report it as a function, class, method, property or accessor, or as a variable whose value is a function (`export const handler = () => ...`, or a plain function call with an inline function argument such as `defineHandler(async (c) => ...)`). Those are behavioral code and always need `implements`. ## Symbol classes ### Behavioral anchors Traceability relationships (`implements`, `covered_by`, `executable_for`) should target behavioral symbols when available. Behavioral symbols include runtime functions, classes, methods, accessors, behavior-bearing class properties, executable test helpers, and manual anchors for behavior composed through factory or expression constructs. Extracted class members use `ClassName.memberName` when they are the narrow behavioral seam. For example, an exported UI component property initialized with `computed(() => ...)`, `effect(...)`, `signal(...)`, a callback, or another non-trivial expression can be a behavioral anchor such as `UploadPageComponent.processingProgressLabel`. Prefer linking that member directly when the requirement ownership is about the member's behavior or UI-facing copy. Interfaces, type aliases, and enums are `type-shape` symbols. They describe data or API shape and should not by themselves block a module/file-level behavioral link. When behavior is composed through factory expressions, generated code, framework conventions, or language constructs the extractor cannot model, declare a manual symbol in `.kb/symbols.yaml` with `symbol_role: behavioral`. If no precise behavioral anchor exists yet, use `granularity_reason: extractor-miss` or `granularity_reason: module-level-behavior` on the coarse symbol and treat it as an audited fallback. ```yaml symbols: - id: SYM-video-player-store-connect title: VideoPlayerStore.connectVideoElement status: active sourceFile: src/video-player.store.ts symbol_role: behavioral relationships: - type: implements target: REQ-video-player-connects-element ``` ### Semantic review after source edits Impact diagnostics intentionally separate graph shape from semantic truth. A changed behavioral member can have complete `implements` and `covered_by` links and still emit `symbol_semantic_review_needed`; that warning tells the agent to inspect whether the linked requirement, scenario, and test still describe the changed behavior or UI copy. Kibi can point at the linked entities, but an LLM or human must review the prose and tests before claiming the KB remains semantically current. Linked symbols are not proof either. Kibi's rules never compare code with a requirement's statement, so for each current requirement a changed behavioral symbol implements, an impact-enabled `kb_check` emits `requirement_statement_unverified` (`warning`): it quotes the requirement's statement with its firmness, and the summary says the check found no structural violations rather than no violations. A change that no longer does what the quoted statement says is a conflict with a recorded rule, to be put to the person before the change is kept. A file with no linked symbol is not a file without rules. For each file named in `sourceFiles` that no manifest symbol links to a requirement (including markup Kibi does not extract symbols from), an impact-enabled `kb_check` emits `source_file_unowned` (`info`): it names the current requirements whose titles share the file's path words, ignoring layout words such as `src`, `app` and `pages` and file extensions, so the agent can confirm one with `kb_query` and link the symbol that implements it (for markup, the component that renders it). The Claude Code and Codex edit hooks name the same candidates before the edit. The match is lexical: candidates are prompts to check, never owners. Run impact-enabled `kb_check` while the edit context is fresh, either through MCP or the equivalent CLI JSON route. Treat `kibi check --staged` and git hooks as the later hard gate for missing impact evidence, stale symbol coordinates, and granularity violations. ## Audit quality diagnostics Kibi separates blocking traceability enforcement from advisory audit diagnostics. Hard graph/schema/staged failures stay in `violations[]`; quality findings such as `multi_requirement_symbol_review`, `duplicate_symbol_coordinate_review`, `component_mixed_purpose_review`, `broad_requirement_review`, `coverage_depth_review`, `requirement_status_review`, and `strict_fact_modeling_review` appear in `qualityDiagnostics[]` and are non-blocking unless a diagnostic explicitly carries `blocking: true` or `severity: "error"`. Use these diagnostics as review prompts, not as proof of incorrectness. A multi-requirement or mixed-purpose symbol may be legitimate, but it should have a narrow behavioral anchor, an explicit `granularity_reason`, or a split requirement/symbol model that explains why one symbol owns several outcomes. OpenCode scheduled checks and normal CLI/MCP checks surface the same advisory lane automatically so agents see modeling drift without adding a separate audit command. ### Production runtime symbols Shipped code that executes product behavior: handlers, services, commands, UI actions, adapters, event publishers/consumers, and other runtime code. Required posture: - Own at least one granular requirement via `implements` - Use `covered_by` for tests that prove the owned production behavior - Never use `executable_for` ### Executable test symbols Test files, fixtures, harnesses, setup helpers, and reusable helpers that are executed as part of a `test` entity. Required posture: - Link the symbol to the test entity with `executable_for` - Do not add `implements` - Do not add `covered_by` These symbols are test identity, not product ownership. ### Metadata / non-executable symbols Symbols that primarily shape behavior without being the runtime seam themselves: schemas, registries, declarative maps, compile-time helpers, barrel metadata, and similar non-executable structure. Required posture: - Still give them direct requirement ownership with `implements` when they exist to satisfy a real behavior slice - Reuse shared behavior-level evidence with `covered_by` when a production or integration test proves the requirement they shape - Never relabel them as `executable_for` just to avoid ownership Metadata / non-executable symbols may share the same behavior-level integration/e2e evidence as the runtime symbols they support. ## When integration/e2e evidence is required Integration or end-to-end evidence is required when a symbol owns behavior whose correctness depends on a real boundary or externally observed flow, for example: - crossing a process, network, filesystem, editor, CLI, or package boundary - proving a user-visible or operator-visible workflow - validating contract behavior between multiple components - confirming wiring that unit tests cannot prove in isolation Use one behavior-level test for all symbols participating in the same granular requirement when that test genuinely exercises the shared outcome. ## Explicit N/A rationale is allowed only when all of the following are true - the symbol is metadata / non-executable, or it is helper code fully subsumed by another owned runtime symbol - the symbol does not introduce its own unique external boundary, user journey, or integration seam - a shared requirement-level test already proves the behavior that this symbol supports, or an additional integration/e2e test would be fake duplication - the rationale names the shared evidence or explains why no honest integration/e2e seam exists - the rationale is written down explicitly in docs/KB instead of being implied by omission N/A is not allowed for production runtime symbols with their own external seam or user-visible workflow. ## Granular vs blanket requirements ### Granular requirement A granular requirement names one coherent behavior slice with one observable outcome. A linked symbol should be able to answer: “what exact behavior do I own here?” without pointing to a whole subsystem. Good signs: - one actor, trigger, or system obligation - one main observable outcome or failure mode - can be specified by one scenario or a tight scenario cluster - can be verified by a focused test or a clearly shared behavior-level test ### Blanket requirement A blanket requirement describes a package, plugin, subsystem, or roadmap chunk instead of one behavior slice. Blanket smells: - the subject is an entire package or subsystem - the sentence chains unrelated verbs with “and” - different symbols would implement unrelated outcomes under the same requirement - no single scenario/test could prove the whole statement honestly - symbols need the requirement only because it is the nearest umbrella doc ## Anti-blanket requirement checklist If any checkbox fails, split the requirement before adding more symbol links. - [ ] Does the requirement describe one observable behavior instead of a subsystem umbrella? - [ ] Can one primary scenario or one tight scenario family specify it honestly? - [ ] Can every linked symbol explain the same outcome, not parallel unrelated outcomes? - [ ] Would one focused test or one shared behavior-level test verify the claim without hand-waving? - [ ] Does the wording avoid vague umbrella verbs like “handles”, “supports”, or “manages” unless the exact behavior is immediately enumerated? - [ ] Would removing one linked symbol leave the requirement mostly intact? If yes, the requirement is probably too broad. - [ ] Is any integration/e2e N/A decision justified by a real lack of seam instead of test-count convenience? ## Repo-specific examples - Broad requirement smell: a single requirement that claims smart enforcement, posture detection, token budgeting, maintenance degradation, and completion reminders all at once is probably blanket and should be split. - Granular baseline: a requirement such as “the VS Code tree opens the symbol’s real source file and line” is narrow enough for direct ownership, scenario coverage, and verification. --- # Architecture URL: https://getkibi.dev/reference/architecture.html > Storage layout, branch isolation, and the data flow between the CLI, MCP server, and Prolog engine. ## System Diagram ```mermaid graph TD subgraph Git Repository D[Markdown/YAML Documents] end D -->|Extract| E[Extractors] E -->|Entities/Relationships| KB[Prolog KB (per branch)] CLI[CLI: flags + JSON routes] --> OPS[shared operation specs] MCP[MCP Server] --> OPS OPS -->|Framed local RPC| ENG[Node kibi-engine\n(single writer per workspace/branch)] ENG -->|One interactive process| KB[SWI-Prolog KB (per branch)] AD[Optional host plugins:\nkibi-claude, kibi-cursor, kibi-codex,\nkibi-opencode, kibi-zcode] -->|calls| MCP MCP -->|Tooling| VSCode[VS Code Extension] CLI -->|Git Hooks| GH[Git Hooks] GH -->|post-checkout/post-merge| KB KB -->|Persist| RDF[RDF Persistence] ``` ## Component Descriptions ### Prolog Core - Located at `packages/core/src/kb.pl` - Implements journaled RDF persistence using SWI-Prolog's `rdf_persistency` - Stores entities and relationships as RDF triples - Enforces validation rules - All operations mutex-protected for concurrency safety ### CLI - Located at `packages/cli/` - Peer public operation surface alongside MCP, plus maintenance and human-oriented commands - Exposes all 21 public operations through `--input <file|->` JSON routes and preserves ergonomic flag commands where available - Node.js 22+ is the supported CLI/MCP runtime and hosts the long-lived `kibi-engine` daemon - Automatically connects to (or starts) one engine per real workspace path and branch over a protected local socket/named pipe - Maintenance commands include init, sync, migrate, gc, branch, doctor, and usage-metrics - Runs extractors for Markdown/YAML - Handles schema validation and audit logging ### MCP Server - Located at `packages/mcp/` - Peer public operation surface alongside the CLI - Provides stdio JSON-RPC transport (newline-delimited, no embedded newlines) - Registers the shared operation specs as host-visible `kb_*` tools - Uses the same Node engine as CLI, so MCP and CLI requests serialize through one SWI-Prolog writer ### Journaled engine - `packages/cli/src/engine.ts` owns the length-prefixed JSON RPC client and daemon lifecycle. - A daemon keeps one interactive SWI process attached for up to ten minutes after the last client disconnects. Requests carry IDs, protocol version, workspace identity, and structured errors over a local socket/named pipe. - New branches use `.kb/branches/<exact-ref-sha256>/branch.json` plus `storage.json`, `rdf/` binary snapshots and journals, and an atomic `CURRENT` value of `<generation-id>:<commit-sequence>`. The manifest is an identity fence; literal branch directories are legacy compatibility storage. - Legacy `kb.rdf`/`audit.log` branches migrate once under `kb.lock` into a staging generation. Canonical triple digests, counts, audit resources, schema fields, and relationship endpoints are checked before publication; originals remain in immutable `legacy/` backups. - Domain triples and audit resources share the same RDF transaction. `audit.log` is only produced by `kibi storage export` and is not authoritative. - Ordinary sync compiles changed/deleted source files and relationship shards into the active journal. `kibi sync --rebuild` is the only path that publishes a replacement generation. - Each attached engine rebuilds disposable ID/type/tag/source/token/coordinate indexes from RDF. Exact and paginated discovery uses the index to materialize only the requested page; a triple/entity-count mismatch rebuilds the index and never repairs RDF. ### Codex Adapter Plugin - Located at `packages/codex/` - Optional package that provides a Codex plugin manifest, skill bundle, and lifecycle hooks - Points Codex MCP wiring to the local `kibi-mcp` server through `mcpServers`; the plugin leaves `cwd` unset so Codex supplies the active task workspace to the project-local `npx --no-install` command. Setting `cwd` to `.` would instead re-root the process in the installed plugin cache. - Provides optional reminders and advisories only; it does not replace `kibi-core`, `kibi-cli`, or `kibi-mcp` ### Cursor Adapter Plugin - Located at `packages/cursor/` - Optional package that provides a Cursor plugin manifest, rules, skills, commands, MCP config, and editor hooks - Points Cursor MCP wiring to the local `kibi-mcp` server - Uses Cursor-specific hooks (`sessionStart`, `preToolUse`, `postToolUse`, `beforeReadFile`, `stop`) for read/write guidance and freshness follow-ups - Provides optional reminders and advisories only; it does not replace `kibi-core`, `kibi-cli`, or `kibi-mcp` ### Other host adapters - `packages/claude/` (Claude Code) and `packages/zcode/` (ZCode) follow the Codex pattern: bundled skills, local `kibi-mcp` wiring, and advisory hooks that stay silent in workspaces whose project root has no `.kb/manifest.json` - `packages/opencode/` (OpenCode) adds prompt guidance and background sync alongside the configured `kibi-mcp` server - Each package README lists exactly what its hooks emit > **Entity Modeling:** `flag` entities represent runtime/config gates. Bug and workaround notes belong in `fact` entities with `fact_kind: observation` or `meta`. **Strict facts** drive contradiction checks; observation/meta are non-blocking notes. See [Entity Schema](entity-schema.md). `domain-contradictions` applies to strict lane; `strict-fact-shape` is a canonical blocking check as of schema 7. ### VS Code Extension - Located at `packages/vscode/` - Explorer tree of requirements, scenarios, tests, decisions, flags, events, and symbols from the workspace knowledge base - MCP integration for queries and updates - Activates when the workspace contains `.kb` ### Git Hooks - Installed in `$GIT_DIR/hooks` or via `core.hooksPath` - `post-checkout`: ensures branch KB exists, runs sync - `post-merge`: runs sync - `kibi gc`: quarantines stale branch KBs and purges them only explicitly after retention ## Data Flow Diagrams ### Write Path (Document → KB) ```mermaid sequenceDiagram participant Dev as Developer participant CLI as CLI participant Ext as Extractors participant ENG as kibi-engine participant KB as SWI-Prolog participant RDF as RDF Persistence Dev->>CLI: kibi sync CLI->>Ext: Run extractors once per changed source Ext->>ENG: Delta entities/relationships ENG->>KB: One serialized RDF transaction KB->>RDF: Append journal / compact while idle ENG->>KB: Validate and append audit resources atomically ``` ### Read Path (KB → Query) ```mermaid sequenceDiagram participant User as User or Agent participant Surface as CLI or MCP participant Ops as Shared Operation participant ENG as kibi-engine participant KB as SWI-Prolog participant RDF as RDF Persistence User->>Surface: CLI JSON/flags or MCP tool call Surface->>Ops: Validate shared operation input Ops->>ENG: Framed local RPC ENG->>KB: Indexed RDF query KB->>RDF: Query RDF store KB->>Ops: Return bindings Ops->>Surface: Structured operation result Surface->>User: Return CLI JSON or MCP content ``` ## Per-Branch KB Architecture - Each exact Git branch identity has a compiled store under `.kb/branches/<sha256(exact-ref)>/` with a versioned `branch.json` identity fence. - `kibi sync` materializes a missing store from the current checkout's tracked Markdown/YAML/manifests and never copies another branch's compiled store. - Git remains the sole branch/merge authority: unresolved authored-file conflicts block compilation, and Kibi never selects merge winners. - Worktree-local branches remain live for collection; remote-only refs do not. - Legacy literal-path migration is explicit old/new, preview-first, and preserves a recoverable backup. Deleted stores are quarantined before purge. - Git hooks invoke normal `kibi sync` only; they do not create or clone a Kibi-specific branch model. ## Source-First Mutation and Recovery Tracked Markdown/YAML, symbol manifests, and relationship shards are the authoritative project artifacts. `kb_upsert` and approved plan application may write those files transactionally through the runtime, preserving existing document bodies when requested, while Kibi never stages or commits Git state. RDF/Prolog stores are compiled outputs and can be rebuilt with `kibi sync`. Source writes carry before/after hashes, stay inside the workspace (including symlink checks), and use a recovery journal with staged preimages/postimages. Failures before the authoritative commit roll back; failures after it are reported as `committed_with_repairs` with typed repair actions rather than repeating the original mutation. ## RDF Persistence Details - Uses SWI-Prolog `library(semweb/rdf_persistency)` - Directory layout: `storage.json`, `CURRENT`, `rdf/` binary `.trp` snapshots plus incremental `.jrn` journals, and a legacy sentinel `kb.rdf` - File locking: lock file with timestamp, PID, hostname prevents concurrent access - Multi-step updates guarded with `with_mutex/2` for atomicity - Journals compact automatically while idle once they exceed 16 MiB; `kibi storage compact` forces compaction - `library(persistency)` remains only for legacy migration/import; journaled audit resources live in the RDF graph - Writes are acknowledged only after the transaction and journal are durable ## MCP Stdio Transport - JSON-RPC messages sent via stdio (newline-delimited) - No embedded newlines in messages - Only valid MCP messages on stdout; logs sent to stderr ## Git Hook Automation - `post-checkout`: ensures branch KB exists, runs sync - `post-merge`: runs sync - `kb gc`: quarantines stale branch KBs and purges them only explicitly after retention ## Directory Structure - Authored knowledge lives in canonical `.kb/` lanes: `requirements/`, `scenarios/`, `tests/`, `facts/`, `adr/`, `flags/`, `events/`, plus `symbols.yaml`. See [Entity Schema](entity-schema.md). - Derived, Git-ignored runtime state lives under `.kb/branches/`, `.kb/recovery/`, `.kb/proof/runs/`, `.kb/briefs/`, `.kb/migrations/`, and `.kb/usage.log`, plus `.kb/symbol-coordinates.yaml`, the symbol source spans every sync derives from the working tree. --- # Proving requirements URL: https://getkibi.dev/reference/proving.html > Proof contracts, the kibi prove workflow, and the kibi.proof-run.v1 producer artifact contract. This guide explains how a requirement goes from "implemented" to "tested": fresh evidence from any proof producer, bound to the current code snapshot, evaluated against explicit proof obligations, and recorded in an ordered proof history that only ever drops receipts that can no longer decide proof. Kibi does not support test runners. Kibi supports **proof evidence**. Playwright, pytest, JUnit, TAP, Go tests, shell commands, database harnesses, device farms, and proprietary systems are all just producers of `kibi.proof-run.v1` artifacts. Producers report what happened; **Kibi evaluates proof**. ## The proof chain ``` REQ-* --specified_by--> SCEN-* --verified_by--> TEST-* <--executable_for-- SYM-* ^----covered_by---- SYM-* TEST-* --proof_contract--> obligations --integration--> configured producer ``` A requirement counts as **tested** (`proofStatus: tested`, evidence level `tested`) only when every required proof obligation on its contracted test has fresh, passing evidence at the required `verification_scope` and `verification_perspective`: - bound to the **current workspace snapshot**, - bound to the current **proof contract hash** and **execution fingerprint**, - derived from a validated `kibi.proof-run.v1` artifact (never caller-authored), - the newest valid receipt within the 7-day freshness window. ## The three integration levels Bootstrap picks the strongest available mechanism automatically; every project has a floor. | Level | Mechanism | Fidelity | Example | | --- | --- | --- | --- | | 1 | Native producer | Complete attempt history, native IDs, per-target results | Playwright with `kibi-cli/playwright-reporter` | | 2 | Standard-format adapter | Native-case outcomes; retry history per source format | pytest/JUnit XML, Go/TAP | | 3 | Command proof | Aggregate process outcome bound to contracted obligations | `cargo test`, custom scripts | Level 3 is the universal fallback: **if the project can run a command and observe its exit code, the project can prove requirements with Kibi.** ## The canonical command: `kibi prove` ```bash kibi prove --all # prove every proof-bearing test kibi prove --test TEST-mcp-search-discovery # one test kibi prove --requirement REQ-cli-check kibi prove --integration self-proof kibi prove --stale # only tests without a current passing receipt kibi prove --all --resume # continue an interrupted run kibi prove --all --shard 2/3 # the 2nd of 3 disjoint parts, for parallel CI ``` `--stale` narrows any selector (all tests by default) to the tests whose receipt is missing, stale, failed or bound to an older contract, judged the way coverage judges them, so re-proving after a change only reruns what the change invalidated. Receipts are written as each integration finishes, and `kibi prove` prints each integration it starts and ingests on stderr. When a long run is stopped, rerun the same selector with `--resume`: integrations already ingested at the same workspace snapshot, for every test the run selects, are skipped (the record lives in `.kb/proof/runs/prove-progress.json`). After the workspace changes, `--resume` runs everything again. To spread a long run over several CI runners, give each runner the same selector and `--shard K/N` (`1/N` to `N/N`). The parts are disjoint and together hold every selected test, so the receipts from all runners are exactly one full run. `kibi prove --all --list` (with or without `--shard`) prints the selected ids, which a join job can compare against the union of the shards before it gates on fresh evidence. When `--test`, `--requirement` or `--stale` selects a subset and the integration's producer is `playwright`, a direct `playwright test` command is narrowed to the selected tests' `proof_bindings[].source_file` spec files, so proving one test runs its specs instead of the whole suite. Narrowing needs a `source_file` on every selected test's bindings; otherwise, or when the command is a wrapper such as `npm run e2e`, the whole integration runs and `kibi prove` says why, on stderr and in the JSON summary's `notNarrowed` list (`{"integration", "reason"}` per integration). Every producer gets the selected tests' bound files in `KIBI_PROOF_SOURCE_FILES` (a JSON array), so a wrapper can narrow itself. A narrowed run's artifact records the narrowed command; Kibi accepts it for a test only when the appended arguments are the spec files of the tests ingested from that run and include every spec file of that test. For each configured integration, `kibi prove`: 1. captures the workspace snapshot, 2. runs the integration's producer **once**, 3. revalidates the snapshot (proof execution must not change tracked state), 4. validates the complete `kibi.proof-run.v1` artifact, 5. evaluates it independently against every selected test's proof contract, 6. derives idempotent `kibi.proof-receipt.v2` receipts and appends them (re-checking any certificate the run left, see [Certificate proof kinds](#certificate-proof-kinds)), 7. reports gaps with expected versus received values. One suite run can satisfy many TEST contracts; unrelated results are ignored per contract. ### CI proof reuse for pull requests The canonical `kibi.workspace-snapshot.v2` verification snapshot, rather than a Git commit or branch name, identifies the source state proven by Kibi. On each successful `develop` push, the strict proof workflow uploads a `kibi-proof-attestation` artifact with the snapshot version and hash, source commit, outcome, and workflow run provenance. The artifact is emitted only after full proof, baseline enforcement, and report generation succeed. For a PR targeting `master`, the same workflow checks out GitHub's merge commit and computes its snapshot through Kibi's production snapshot code. It reuses proof only for a same-repository `develop` PR whose head still equals the current `develop` branch, whose checkout is the expected merge commit, and whose exact head has one successful `develop` push proof run with a matching attestation. If the canonical snapshots match, the workflow records a reused proof decision and skips the full proof steps. If lookup, provenance, version, or snapshot comparison is uncertain, it runs the full proof on the merge checkout using the `master` KB branch identity. For a same-repository PR targeting `develop`, the workflow compares the merge commit's snapshot with the attestation of the PR's base commit instead. The snapshot leaves out general `docs/`, release changesets and the derived `.kb/` trees, so a PR that only changes those paths has the same snapshot as its already proven base and skips the full proof. Any change to code, tests, requirements, symbol manifests, `README.md` or the docs site changes the snapshot and runs the full proof. Scheduled, manual, fork, and push proof runs remain full runs. Reuse is a CI gate decision only. It does not execute tests again, create new proof receipts, or attach `master` to the `develop` KB branch. The decision artifact and job summary say whether proof ran or was reused. Attestation artifacts expire after seven days; expiration simply causes a full proof run. ## Proof contracts A `TEST-*` entity declares its semantic obligations: ```yaml verification_scope: end_to_end # unit | integration | end_to_end verification_perspective: consumer # internal | consumer proof_contract: version: kibi.proof-contract.v1 integration: self-proof # id in .kb/proof/integrations.json required_proofs: - symbol_id: SYM-e2e-packed-cli-check target: default # browser, runtime, db, device, or default success_policy: all_required_first_attempt proof_bindings: # optional provenance metadata - symbol_id: SYM-e2e-packed-cli-check target: default native_id: documentation/tests/e2e/packed/cli-workflows.test.ts::check ``` Contracts are semantic. Native test IDs, aliases, and source coordinates live in `proof_bindings`, not in the contract. Bindings never replace obligations; they help adapters map native results to symbols. ### Explicit obligations, not Cartesian matrices Each `required_proofs` entry is an explicit `(symbol_id, target)` pair. A suite must demonstrate exactly what the contract declares — no implicit `cases × projects` combinations. ## Certificate proof kinds A test samples cases. When a requirement is about a finite domain (every entity type, every evidence level, every built-in schema), a test can cover every case, and Kibi can then report the requirement as **proved** instead of tested. The contract says so with `kind`: | Kind | Checker | Evidence it supports | | --- | --- | --- | | `e2e` (default), `example`, `property` | the test runner | tested | | `exhaustive` | the test checks every member of a domain it imports from the code | proved | | `typecheck` | Kibi compiles a witness that fails to compile when a member goes unhandled | proved | | `arithmetic` | Kibi decides a one-variable claim exactly from the typed facts in `constraint_source` or the code constants in `value_source` | proved | | `smt` | Kibi re-runs z3 or cvc5 on a query that asserts those assumptions and needs `unsat` | proved | | `rule` | Kibi calls the code's predicate functions on every combination of the finite domains the code exports and model checks a rule, predicate or every-member claim | proved | | `state_machine` | Kibi reads the code's transition table or next-state function and checks the transitions, initial, terminal or reachable states a claim names | proved | | `regex` | Kibi decides whether the code's pattern (or string constant) accepts exactly the strings a string fact describes | proved | | `source` | Kibi reads a project source itself (a JSON or YAML file, a glob, an OpenAPI document, the references the code makes, a data schema, a route table, a validator) and decides a set, field or middleware claim against it | proved | "Proved" here is what the certificate supports; a requirement is proved only for the claims a certificate binds to (see "Binding a certificate to claims"). ```yaml proof_contract: version: kibi.proof-contract.v1 integration: self-proof required_proofs: - symbol_id: SYM-test-evidence-levels-exhaustive target: default success_policy: all_required_first_attempt kind: exhaustive domain_source: symbol_id: SYM-cli-evidence-levels # the symbol that defines the domain ``` `exhaustive` and `typecheck` need `domain_source`; `typecheck` also needs `witness: {path}`. `arithmetic` and `smt` need `constraint_source: {fact_ids: [...]}`, the typed numeric `property_value` facts (one subject and property, `value_type: int` or `number`) the claim rests on: ```yaml kind: arithmetic constraint_source: fact_ids: [FACT-RETRY-MIN, FACT-RETRY-MAX] # retry_count >= 0, retry_count < 4 ``` The arithmetic certificate's variable is the facts' `property_key`, its assumptions are exactly the facts' constraints and its claim is what the test proves from them; an SMT query declares the property as a constant and asserts each fact constraint (`(assert (>= retry_count 0))`) before the negated claim. These kinds prove that the knowledge base's facts entail the claim; they say nothing about code that does not follow those facts, so pair them with a test of the code when the code is what matters. A certificate-kind test leaves a `kibi.code-certificate.v1` JSON file in the directory `kibi prove` names in `KIBI_PROOF_CERTIFICATES` (outside `kibi prove` the variable is unset and nothing is written). The `kibi-cli/proof-certificates` module builds and writes them: ```ts import { exhaustiveCertificate, failedMembers, writeCodeCertificate, } from "kibi-cli/proof-certificates"; import { EVIDENCE_LEVELS } from "../src/evidence-levels.js"; const certificate = await exhaustiveCertificate({ testId: "TEST-evidence-levels-exhaustive", domain: { symbolId: "SYM-cli-evidence-levels", members: EVIDENCE_LEVELS }, check(level) { // throw when the claim fails for this member }, }); writeCodeCertificate(certificate); expect(failedMembers(certificate)).toEqual([]); ``` ### Where the domain comes from `domain_source.symbol_id` names the symbol that defines the domain. Kibi loads that symbol's file and reads one export from it: the symbol's title by default, or `domain_source.export` when the export has another name (a symbol titled `ENTITY_LANES` whose export is `entityLanes`, or a module-level anchor): ```yaml domain_source: symbol_id: SYM-order-status export: OrderStatus ``` When the export is a list of records, such as an operation catalog, `domain_source.field` names the field of each record that is the domain member, and the certificate's members are that field's values (`key: (operation) => operation.name` in `exhaustiveCertificate`). A record without the field fails the read. `field` applies only to `exhaustive`. ```yaml domain_source: symbol_id: SYM-operation-catalog field: name ``` - **TypeScript and JavaScript**: Kibi tries bun, then the workspace's own `tsx` (`node_modules/.bin/tsx`), then node with type stripping and a resolve hook that maps extensionless and `.js` relative imports to their `.ts` sources. A domain whose module imports runtime-only dependencies needs one of these runners to resolve them. - **Compiled output**: when the proof file imports the domain from build output (`dist/status.js`), Kibi maps the import back to the source through the nearest `tsconfig.json` (`outDir` to `rootDir`) before checking that the proof file imports the domain. - **Python**: a `.py` domain is loaded with the first interpreter found among `KIBI_PYTHON`, the active virtualenv (`VIRTUAL_ENV`), a `.venv` or `venv` directory from the domain file's directory up to the workspace root, then `python3` (or `python`) on `PATH`, so the domain's own dependencies import. It is imported under its package name so absolute and relative imports inside it resolve. When loading fails, the rejection quotes the exception line of the traceback (`ModuleNotFoundError: No module named 'x'`). An `Enum` contributes its member values, a `dict` its keys, and a list, tuple, set or frozenset its items. The proof file must import the module (`from app.status import OrderStatus`, `from .status import OrderStatus` or `import app.status`). - **SWI-Prolog**: a `.pl` or `.plt` domain is loaded with the same SWI-Prolog Kibi runs on (`KIBI_SWIPL`, then the bundled runtime, then `swipl` on `PATH`). A module file loads as its module and a plain file into `user`. `export` names a predicate indicator (`status/1`, `phrase//1` or `operators:operator/2`), and the domain is the distinct solutions of its argument. For a predicate with more than one argument, `arg` names the 1-based argument that holds the members (`arg` and `field` are not both allowed). Kibi refuses a read whose solutions leave that argument unbound, a predicate with more than 100,000 solutions, and a predicate with several arguments and no `arg`. Members are atoms and strings as text, numbers as written. The proof file must name the predicate and load its file (`:- use_module('../prolog/operators')`, `library(operators)` for a pack's `prolog/` directory, `consult/1` or a `:- [...]` list), or be the `.plt` file beside it. A value_source reads a predicate with one solution that is a number, and the rule, state_machine and regex kinds below read Prolog predicates too. A Python test has no helper module: it writes the certificate JSON itself to a file in the directory named by `KIBI_PROOF_CERTIFICATES` (skip writing when the variable is unset): ```python import json, os from app.status import OrderStatus members = [m.value for m in OrderStatus] results = [{"member": str(m), "outcome": "passed"} for m in members] # check each directory = os.environ.get("KIBI_PROOF_CERTIFICATES") if directory: os.makedirs(directory, exist_ok=True) with open(os.path.join(directory, "TEST-order-status-exhaustive.json"), "w") as f: json.dump({ "version": "kibi.code-certificate.v1", "kind": "exhaustive", "test_id": "TEST-order-status-exhaustive", "domain": {"symbol_id": "SYM-order-status", "members": [str(m) for m in members]}, "results": results, }, f) ``` A SWI-Prolog test writes its certificate with the `kibi_certificate` module the kibi-usage skill ships in `resources/prolog-proofs.md` (copy it into the project's test directory). It reads the domain with `findall/3` over the predicate, never a hand-written list: ```prolog :- use_module('../prolog/operators'). :- use_module(kibi_certificate). :- initialization(main, main). operator_name(Name) :- operator(Name, _). main :- findall(Name, operator_name(Name), All), list_to_set(All, Names), kibi_exhaustive_certificate('TEST-operators', 'SYM-operator', Names, [N]>>atom(N), Certificate), kibi_write_certificate(Certificate). ``` ```yaml domain_source: symbol_id: SYM-operator export: operator/2 arg: 1 ``` ### Wiring a certificate test into the KB A certificate only counts when the KB links it to the requirement it proves: 1. The proof file is an executable test symbol: `required_proofs` names it and it links `executable_for` to the test. 2. The domain symbol links `implements` to the requirement and `covered_by` to the test (and to the requirement's end-to-end test). 3. The test `validates` a scenario that the requirement is `specified_by`; that scenario's end-to-end test still has to pass. 4. The test has a `proof_contract` with `kind` and `domain_source`, and the integration's command runs the proof file. 5. The contract names the requirement claims the certificate proves in `proves` (see below). `kibi proof explain REQ-...` shows each link it found, and `certificateRejections` says why a certificate did not count. ### Binding a certificate to claims A requirement's prose is split into claims (its `semantic_inventory`), and each modeled claim is grounded by one typed fact. A certificate proves claims, not requirements: the contract names them in `proves`, and Kibi derives from each claim's fact what the certificate has to establish. ```yaml proof_contract: kind: exhaustive domain_source: symbol_id: SYM-cli-evidence-levels proves: - CLAIM-3F2A9C0D11E4B7A8 # "The evidence levels are proved, tested, asserted and unverified" ``` | The claim's fact | Kind | What the certificate must establish | | --- | --- | --- | | a set fact (`value_type: set`, `value_set: [...]`) | `exhaustive` | the domain Kibi loads is exactly the fact's set | | a set fact | `typecheck` | the domain export, as a type, is exactly the fact's set (Kibi compiles a set-equality witness itself) | | a numeric fact (`value_type: int` or `number`, a comparison) | `arithmetic` | the certificate's claim is the fact's constraint (negated for `polarity: forbid`) | | a numeric fact | `smt` | the query asserts the negation of the fact's constraint | | a set fact with `property_key: required_fields` | `typecheck` | every member is a required, non-nullable field of the domain type (Kibi compiles that witness itself) | | a set fact whose `property_key` names a predicate (`eq` or `includes`) | `rule` | the code decides the predicate true for every member | | a rule fact (`kibi.logic.v1`, from `kibi model-requirement` with `logic`) | `rule`, `state_machine` | the rule holds for every assignment of its variables over the domains the code exports | | a predicate fact (a ground atom, or a decision predicate such as `permission_rule`) | `rule`, `state_machine` | the code decides the atom as the fact says (for a decision predicate: the key arguments are allowed exactly when the effective decision is allow) | | a set fact with `property_key` `transitions`, `states`, `initial_states`, `terminal_states` or `reachable_states` | `state_machine` | that projection of the machine is exactly the set (`transitions` members are spelled `from->to`) | | a string fact (`eq`, `neq` or `matches`) | `regex` | the code's string meets the constraint, or the code's pattern accepts exactly the fact's string (`eq`), rejects it (`neq`) or accepts exactly the strings the fact's pattern matches (`matches`); `polarity: forbid` negates it, and a forbidden match means no string matches both | A legacy `property_key: allowed_values` fact whose `value_string` joins the members with `|` reads as a set fact. Each claim gets one binding per test, recorded in the receipt's `claim_bindings`: - **derived**: Kibi checked the certificate against the claim's own fact. Only a derived binding proves a claim. - **attested**: the fact has no derivation for the kind (a boolean placeholder, a rule fact under `exhaustive`). The author says the certificate expresses the claim; Kibi reports it and counts it as tested, never proved. - **rejected**: the key is not a modeled claim of a current requirement the test reaches through its scenarios, its fact is the wrong shape for the kind (a set fact under `arithmetic`), or the certificate does not establish the obligation. The reason says which. Exhaustive and typecheck bindings also need the `domain_source` symbol linked `covered_by` the test, so a change to the domain stales the proof. An arithmetic or SMT certificate that reads its assumptions from facts proves only that the facts entail the claim; its binding has scope `intent` and the claim stays tested. To prove that the code satisfies the claim, read the value from the code with `value_source` (instead of or with `constraint_source`), link those symbols `covered_by` the test, and the binding has scope `code`: ```yaml kind: arithmetic value_source: - symbol_id: SYM-retry-config export: MAX_RETRIES # a number export; Kibi reads it itself proves: - CLAIM-0A1B2C3D4E5F6071 # "Clients retry at most 3 times" ``` A count claim over a collection reads the collection itself: with `measure: count`, Kibi evaluates a list, set, map or object export and uses its size, so "exactly 32 tools" needs no separate number kept beside the list for the proof: ```yaml kind: arithmetic value_source: - symbol_id: SYM-tool-names export: TOOL_NAMES measure: count # the number of members of TOOL_NAMES proves: - CLAIM-5D6E7F8091A2B3C4 # "There are exactly 32 tools" ``` A claim that every member of a closed set has a property ("Every currency in GBP, ILS and ZAR must fail closed") is modeled as a set fact named for the property: the semantic advisor proposes `property_key: fail_closed`, `operator: includes` and `value_set: [GBP, ILS, ZAR]`, so the property stays in the requirement instead of living only in the test. `includes` says every listed member has the property and leaves the others open, so "every role in owner and admin can invite" and "every role in owner, admin and member can invite" are both valid facts; the code decides which holds. `eq` on a set means exactly those members, and an `includes` fact contradicts an `eq` fact on the same property only when it names a member the `eq` set leaves out. A `rule` certificate derives an `includes` fact by checking the property on each listed member, and a `typecheck` certificate derives one on `required_fields`; the kinds that compare the whole set (`exhaustive`, a set-equality `typecheck`, `state_machine`) reject an `includes` fact, because they would read "at least these" as "exactly these". Kibi judges bindings at ingest and judges them again whenever it reports evidence: a binding whose fact changed since ingest (another set, another bound), whose claim is no longer modeled, or whose certificate no longer re-checks against the obligation is rejected. `kibi prove` prints each binding as it ingests a receipt. From schema 12 the blocking `proof-contract-claims` rule reports a certificate-kind contract without `proves` and a named claim no certificate of its kind could prove. `kibi migrate` pins `proves` where the test reaches exactly one claim its kind can derive. For every other contract its review lists each modeled claim the test reaches through its scenarios with the binding a certificate of its kind would get (provable, attested only, or the reason its kind cannot express the fact), so the person binding it knows which keys to name and which facts to remodel. ### Rules, state machines and patterns These kinds prove claims that are not numbers. In each one Kibi reads the model from the code itself at ingest, with the same runners as an exhaustive domain (TypeScript, JavaScript, Python or SWI-Prolog), needs the certificate to be that model, and decides the claim exactly: nothing is sampled. Every symbol a contract names must link `covered_by` the test. A **rule** contract names the function behind each predicate the claims use in `predicate_source`, and the export listing each argument type's values in `domains`. Each function takes the predicate's arguments in order and returns a boolean; Kibi calls it on every combination of its argument domains (up to 100,000 rows) and records the table. A rule holds when, for every assignment of its variables, its head has the value the modality requires (true for `assert`, `oblige` and `permit`, false for `deny` and `forbid`) wherever its body holds and no exception applies. A domain's type name is also a predicate of one argument that holds for its members (`role(R)`), so every variable can be ranged over a domain. A failure names the assignment: ```yaml kind: rule predicate_source: can_share: symbol_id: SYM-can-share # canShare(status, role) -> boolean archived: symbol_id: SYM-is-archived export: isArchived # when the export is not the symbol's title domains: document_status: symbol_id: SYM-document-statuses # ["draft", "active", "archived"] role: symbol_id: SYM-roles proves: - CLAIM-15C388CF1E89C595 # "Archived documents must never be shared" ``` ``` rejected: the rule fails for V1=archived, V2=owner: the code decides can_share(archived, owner) is true, but the rule requires false ``` Rules with existential quantifiers, counts, temporal expressions or durations are refused with the reason. A **state_machine** contract names the transition table in `domain_source`: an object or `Map` from each state to its next states (a list, a set, one state, or an event map), or a list of `[from, to]` pairs. A next-state function `next(state, event)` works too, with `domains: {state, event}` naming the exports it is called on (a throw or `null` means no transition). `initial_source` names the initial state, which reachable states need. A statement such as "Invoice status transitions must be one of draft -> sent, sent -> paid" is modeled as a `transitions` set fact; terminal, initial and reachable states the same way. A rule over a machine can use `transition`, `reachable` (one or more steps), `initial`, `terminal` and `state`. A **regex** contract names the pattern in `pattern_source`: a `RegExp` or a Python `re.compile(...)` (its flags included), or a string constant. A dotted `export` (`BRAND.name`) reads one field of an object, dict or class export, and the proof file counts as importing it when it imports `BRAND`. "Invoice numbers must match `INV-[0-9]{6}`" is modeled as a string fact with `operator: matches`, whose value is a JavaScript pattern (with the `u` flag) that must match the whole string. Kibi compares the two languages exactly (over well-formed UTF-16 strings, with each engine's own rules for `$`, `.`, `\d` and case folding) and, when they differ, reports the shortest string only one of them accepts: ``` rejected: the code's pattern /INV-\d{6}/ does not accept exactly the strings matching /INV-[0-9]{6}/: "0INV-000000" is in the code's pattern only ``` Only the regular subset is decided: backreferences, lookaround, `\b`, Unicode property escapes, the `g`, `y`, `m` and `v` flags (Python `MULTILINE`, `VERBOSE` and `LOCALE`), Python `\d` and `\w` without `re.ASCII`, and non-ASCII letters under case-insensitive matching are refused with the reason. The certificate builders are `ruleCertificate`, `stateMachineCertificate` and `regexCertificate` in `kibi-cli/proof-certificates`; `failedCalls` lists predicate calls that threw. In SWI-Prolog each symbol names a predicate indicator. A rule predicate is called once per row with one argument per argument type and its success or failure is the row's value; an arity that differs from the argument types is refused. A transition table is a predicate of arity 2 (`From, To`) or 3 (`From, Event, To`) whose solutions are the edges; a next-state predicate `next(State, Event, Next)` is driven over its `domains` instead. A pattern is a predicate with one solution that is an atom or string, read like a string constant. The `kibi_certificate` module has `kibi_rule_certificate/4`, `kibi_machine_certificate/5` and `kibi_pattern_certificate/4` for these kinds. One certificate reads one language: a contract that mixes a Prolog domain with a TypeScript predicate is refused. ### Project sources: routes, schemas, configuration and references Many claims in a real product are about sets the project already declares: every route under `/api` runs the auth middleware, every table has `created_at`, the app reads only the environment variables in the deploy docs, a module never imports `node:fs`, every validator field the API accepts is a column of the table. A **source** proof reads that set from the project itself and decides the claim; the test does not have to compute or list anything. The contract names the source: ```yaml kind: source source: reader: routes file: src/app.ts export: app # a Hono or Express app, or a function returning one path_prefix: /api names_from: [src/middleware.ts] # name middleware by the export they are (or that makes them) proves: - CLAIM-... # "Every route under /api must use requireAuth" ``` | Reader | Reads | `select` | | --- | --- | --- | | `json`, `yaml` | `file` at `path` (dotted, or a JSON pointer) | `keys`, `values`, `items` | | `glob` | the files `pattern` matches (`capture: true` reads what each `*` and `**` matched, joined with `/`: `i18n/**/*.json` reads `finance/de` from `i18n/finance/de.json`) | | | `openapi` | `file`'s operations (`GET /invoices`) | `operations`, `unsecured_operations`, `security_schemes`, `responses` | | `references` | the code in `files` (TypeScript, JavaScript, Python, SWI-Prolog; Go, Java, C#, Rust, PHP, C, Bash and Terraform/HCL through `kibi-plugin-treesitter`): `extract` `env`, `imports`, `calls`, `string_args` (with `callee`), `thrown` (the class of `throw new X()`, or the factory of `throw createX()`) or `property` (with `key`; not in Prolog) | | | `schema` | `format: drizzle` or `prisma` (`file`), or `sql` migrations replayed in order (`files`); `table` filters by name or glob | `tables`, `columns`, `required_columns`, `nullable_columns`, `foreign_keys` | | `routes` | a Hono or Express app's route table, with the middleware that runs before each route (mounted routers included); `path_prefix` keeps the routes under a prefix | `routes`, `middleware` | | `validator` | a zod or valibot object (or one wrapped in refine, transform or pipe; any field that is a Standard Schema), or a pydantic model | `fields`, `required_fields`, `optional_fields` | | `prolog` | `file`'s facts with `functor` (`requires/1` in `pack.pl`): argument `arg` (or the only one) of each, a list contributing its items, in file order | | Details that decide what a reader sees: - **Environment variables.** `extract: env` reads `process.env`, `import.meta.env` (without Vite's built-ins `MODE`, `BASE_URL`, `PROD`, `DEV`, `SSR`), `Bun.env` and `Deno.env.get` in TypeScript and JavaScript, and `os.environ` and `os.getenv` in Python, through casts (`(import.meta as X).env`), `!` and parentheses. An environment object, or `import.meta` itself, handed to a variable or a function fails the read, because its later reads could use any name. A framework's own runtime object (`globalThis._NGX_ENV_`) is not an environment object Kibi reads. - **Names in JavaScript and TypeScript.** What a file imports is read under the name it is bound to: `import { execSync as run } from "child_process"` makes `run()` a call of `child_process.execSync`, `import * as cp` and `const cp = require(...)` make `cp.execSync()` one, and `import { env } from "node:process"` or `const { env } = process` make `env.X` an environment read. `node:` names of Node's built-in modules are listed under both spellings, `globalThis.process` and `global.process` are `process`, and `f.call(...)`, `f.apply(...)` and `f.bind(...)` call `f`. An imported function used as a value (`const f = cp.execSync`, `[execSync].forEach(...)`) is listed as called, and a built-in module handed on is listed as `module.*` (any of its members may be called). A module loaded in place (`process.getBuiltinModule`, `createRequire(url)(...)`, `import()`) is read only when a member of it is called directly; otherwise an environment read through it, a non-literal specifier, and code built from text (`eval`, `new Function`, `vm`) fail the read. - **Symbolic links.** A link to a file that `files` matches is read as that file, as git and compilers read it. Links to folders are not walked. - **SQL migrations.** The replay reads `CREATE TABLE` (quoted and schema-qualified names such as `"public"."messages"` included), `DROP TABLE` and the `ALTER TABLE` actions that change columns, nullability or foreign keys, one or several per statement. Actions that change none of them (row level security, triggers, ownership, defaults, column types, statistics, replica identity, other constraints) are skipped. Function bodies in `$$ ... $$` stay whole. Dropping a foreign key by a name the replay never saw fails the read, unless the statement says `IF EXISTS`. A set of files with no `CREATE TABLE` fails the read, as does a glob that matches no file, so a mistyped pattern never proves a negative. - **Middleware names.** `names_from` modules name middleware by the export it is, or by the export that makes it: a zero-argument factory such as `requireAuthentication()` that returns a fresh function per route is called once at read time and its result is recognised by its source text, so routes guarded by `requireAuthentication()` list `requireAuthentication`. Async functions, generators and classes are never called. Without `names_from` a middleware is its function's name, or `(anonymous)`. - **Python.** The references reader parses `.py` files with Python's `ast` and runs none of them. Names the file imports are followed: `import subprocess as sp`, `from subprocess import Popen` and `from os import getenv as g` read as `subprocess`, `subprocess.Popen` and `os.getenv`. `env` reads `os.getenv`, `os.environ[...]`, `os.environ.get`, `setdefault` and `pop`, and `"X" in os.environ`. `calls` lists each call as written and, through an alias, under what it names too (`sp.call` and `subprocess.call`); an imported function used as a value (`f = sp.check_output`, `fn=Popen`) is listed as called. `imports` lists `import a.b` as `a` and `a.b`, and `from urllib import request` as `urllib` and `urllib.request`. `posix` and `nt` are the modules `os` re-exports, so a name through them is listed as the `os` name too: `posix.system("x")` and `from posix import system` are the call `os.system` (as well as `posix.system`) for `calls` and `string_args`, and `import posix` is listed as `os` and `posix` by `imports`. The whole environment handed on, copied or iterated (`os.environ.copy()`, `dict(os.environ)`, `**os.environ`, `env=os.environ`), a getter or the `os` module used as a value, a name computed at run time, `getattr` or `vars` on an imported module, `exec`, `eval`, `compile`, `__import__` and `importlib.import_module` (which `imports` lists when the name is a literal), `pkgutil.resolve_name`, `runpy`, `importlib.util` and `importlib.machinery`, `sys.modules`, `os.path.expandvars`, and a star import (from `os` for `env`, any for `calls`) fail the read with their place. `posix.environ` and `nt.environ` read like `os.environ`. A module reached through another name also fails the read, because Kibi does not follow what another module binds: `os`, `sys`, `subprocess` and the like as an attribute of an imported module (`shutil.os.getenv`, `path.os`, `dotenv.main.os`) or imported from one (`from .main import os`, which `imports` refuses too), a private name of a module (`from tempfile import _os`, `threading._os.popen`, refused by `imports` too; the private names of `os` and `sys` themselves, such as `os._exit`, are read as written), `environ` or `getenv` on any imported name other than `os` (`from .main import o; o.environ`, and a framework's `request.environ` alike), a module's namespace (`os.__dict__`, `f.__globals__`, `globals()`, `locals()`, `vars()` and `vars(module)`, so `getattr(tempfile, "_os")`, `vars(tempfile)["_os"]` and `tempfile.__dict__["_os"]` are refused by `imports` too), and an imported module handed on: a module used as a value rather than called or read through (`_t = tempfile`, `f(shutil)`, `return tf`, `[tempfile][0]`, `p = os.path`), and a name imported from a project or third-party module assigned to another name (`x = h`, since `h` may be a module), fail `imports`, `calls` and `env`. A standard module's member is checked to be a module by importing that standard module; a class or function used as a value (`@dataclass`, `isinstance(x, Path)`) is read. For `calls`, a name imported from a project or third-party module that is, or is used through, a name of an `os`, `subprocess` or `sys` function (`from .cli import Popen`, `from .main import o; o.system()`) fails the read, since it may be that function re-exported; a re-export under an unrelated name is not detected. For `env` and `calls`, any use of `ctypes` or `cffi` (`ctypes.CDLL(None).getenv(b"X")`, `ffi.dlopen`) fails the read: a function of a native library it loads can read the environment or run a program. - **SWI-Prolog.** The references reader and the `prolog` reader read a `.pl` or `.plt` file term by term with SWI-Prolog and run none of it: no directive, `initialization/1` or clause of the project executes. The file's own `op/3` directives, its module export list, the export lists of project modules it loads and the SWI-Prolog libraries it loads give the operators it is read with. `imports` lists each loaded file as written (`library(lists)`, `helpers`, `foreign(fastmath)`) from `use_module`, `ensure_loaded`, `consult`, `reexport`, `load_files`, `include`, `use_foreign_library`, `autoload` and `:- [...]`, in directives and in clause bodies, with string paths written as atoms (`library("utf8")` is `library(utf8)`), plus `library(L)` for each predicate the files call that SWI-Prolog would autoload from `L` (`maplist/2` is `library(apply)`) because no library or project module they load gives it. `calls` lists `Name/Arity` (`Module:Name/Arity` when qualified) of every goal in clause bodies and directives, walking control constructs, grammar rules (a non-terminal `n//0` is the call `n/2`), lambdas and the arguments of meta-predicates (the files' own `meta_predicate` declarations, those of the project modules they load and SWI-Prolog's), `apply/2` as the goal it calls, the arguments of `~@` in `format/2,3`, `debug/3`, `ansi_format/3`, `sformat/2,3`, `print_message(_, format(...))` and message lines (`print_message_lines(_, _, ['~@'-[Goal]])`, and the list elements of `prolog:message//1` rules and of any grammar rule whose element is such a line), a `{Goal}` grammar body handed to `phrase/2,3` or `call_dcg/3`, the goal lists of `first_solution/3` and `concurrent/3`, and the body of a clause asserted from a literal term (`assertz((s(V) :- getenv('X', V)))`). `env` reads `getenv/2`; `string_args` the first argument of calls to `callee` (`format` or `format/2`); `thrown` the error of `throw(error(type_error(...), _))` (`type_error`), the functor of any other thrown term, and the `library(error)` helpers such as `domain_error/2`, while a rethrow of the ball `catch/3` caught is not a new error. A variable called as a goal or closure (`call(Goal)`, `maplist(G, L)`), a goal qualified by a variable module, a clause asserted from a variable, conditional compilation (`:- if(...)`), a `term_expansion` or `goal_expansion` clause (asserted ones too) in the files or in a project file they load, since expansion can produce any clause, an `include` of a file that is not among `files`, a `consult`, `ensure_loaded`, `load_files` or `:- [...]` of a file without a module header that is not among `files` (its clauses join the loading module), a format string Kibi cannot read whose arguments could be goals, message lines Kibi cannot see to their end (a variable list or element, or in a `prolog:message//1` rule a format that is not written out), and any other module-sensitive (`:`) meta argument that is not a clause, predicate, file or operator spec or `[]` (`prolog_listen/2`, `on_signal/3`) fail the read with their place. An include or load through a project alias (`bson(include/common)`) resolves only through the `file_search_path/2` declarations of the files read: a fact or clause for `file_search_path/2` (with `user:` or not) or a directive that asserts one, where Kibi evaluates `prolog_load_context(directory, D)` (the declaring file's directory), `directory_file_path/3` and `atom_concat/3` on known atoms, and the directory is absolute or `Alias(Sub)` of another alias the files declare. The alias resolves when those directories hold exactly one existing file for the aliased path. A file that only ends with the aliased path (a vendored copy, while the real target sits under `node_modules/` or outside the project) is never taken for it. No declaration among the files, one Kibi cannot evaluate (a relative directory, which depends on the working directory at run time, or one computed otherwise), one that goes through an alias SWI-Prolog defines (`library`, `pack`), or several matching files fail the read with its place. The refusal of an include names a file to add to `files` only when it is the file the declarations resolve to; one under `node_modules`, `.git` or `.kb` or outside the project is named as out of reach. - **Go, Java, C# and Rust.** The references reader hands these files to `kibi-plugin-treesitter`, which parses them in its bounded workers and compiles or runs nothing. Activate it for proofs in `package.json`: `{"package": "kibi-plugin-treesitter", "capabilities": {"kibi.reference-extractor.v1": {"mode": "augment"}, "kibi.symbol-extractor.v2": {"mode": "augment"}}}`, with the package and the language's grammar pack (`kibi-lang-go`, `kibi-lang-java`, `kibi-lang-csharp` or `kibi-lang-rust`) in `devDependencies`; a missing pack refuses the read with its install line. A project without a `package.json` creates one that only holds this list. Proofs use the plugin only when its installed files match the release-qualified closure Kibi ships, so a modified or unqualified provider is never imported. Without it the read is refused with what to install, and `kibi init`, `kibi doctor` and `kb_plan_bootstrap` suggest it when such sources are tracked. Members are written as the code names them: `imports` lists Go import paths, Java imports (`java.util.*` for a wildcard), C# `using` targets and Rust `use` paths expanded from their groups (`std::io`, `std::io::Write`) plus `extern crate` names. `calls` lists `os.Getenv`, `System.out.println` (Java method references such as `System.out::println` too), `Console.WriteLine` and `std::env::var`; a method called on an expression Kibi cannot name, such as the result of another call, is `*.name` (`*.toList`). `env` reads `os.Getenv` and `os.LookupEnv`, `System.getenv("X")`, `Environment.GetEnvironmentVariable("X")`, and Rust's `env::var`, `env::var_os`, `env!` and `option_env!` (and Go's `syscall` and `golang.org/x/sys/unix` and `windows` getters). `string_args` reads the first argument of calls to `callee`. `thrown` lists the type of Go `panic(&ConfigError{})` (or the factory of `panic(errors.New(...))`) and of Java and C# `throw new X()`; a rethrow of the caught exception is not a new error. `property` reads keyed Go composite literals and C# object object, indexer and collection initializers (`new Options { Mode = "strict" }`, `{ ["Mode"] = "strict" }`, `{ { "Mode", "strict" } }`); Java and Rust have none. Names the file gives itself are followed: Go import aliases (`o "os"`), Java single static imports (`import static java.lang.System.getenv`), C# `using static System.Environment` and `using E = System.Environment`, and Rust `use` bindings (`use std::env::var as getvar`) read as the canonical name, and the fully qualified forms match too, so `calls` can list both `env::var` and `std::env::var`. Rust paths resolve through the `use`, `mod` and `extern crate` items in their scope: a path whose root the scope does not bind (`env::var` with no `use std::env`, or under a function-local `mod env`) is not the standard library, while `mod m { pub use std::env; }` then `m::env::var`, `self::env`, `extern crate std as s` and `use Command as C` (also for `string_args` with `callee: Command::new`) are followed. Calls on Java's `java.lang` types and C#'s `System` types are also listed under their long spelling (`java.lang.System.getenv`, `System.Console.WriteLine`), so a "never calls" claim holds whichever spelling it uses. C# `imports` also holds the project's `global using` lines from any tracked `.cs` file, the `<Using Include>` items of `.csproj`/`.props` files and the usings `ImplicitUsings` adds, and `global::` prefixes are dropped. A Go identifier that shadows a package the file does not import (a local `os`) is not that package, and neither is a local `os` in a block, parameter, closure, `range` or type switch of a file that imports it; a package imported as `os` that is not the standard library's is listed by its path (`"github.com/joho/godotenv".Getenv`). A Go method on a value is `*.Method`, and also the package's (`logrus.Error`) when its receiver visibly comes from that package (`logrus.StandardLogger().Error`, `l := logrus.New()`, a parameter or struct field of that type), so a never-call claim on the package does not pass over its logger. A Go qualifier that is no import (a package-level logger of another file) or a call result (`logger().Error`) has an unknown type (`*.Error`), and a method value (`g := l.Error`) is listed like a call. A Java receiver is named by its declared type, cast or `new` (`Runtime r; r.exit()` and `((System) null).getenv` are `Runtime.exit` and `System.getenv`), and `import other.System` or a `System` class in the file shadows `java.lang.System`; a call on an imported type is also listed under its import (`java.io.File.delete`). A Java `System` that a supertype or a static import may name is unknown, and a method the class declares shadows a static import. Since another file of the package may declare its own `System` or `Runtime`, a call on a bare one also gets a row that Kibi drops only after finding no such type in the `.java` files of the file's folder; a bare Rust standard macro likewise gets a row that Kibi drops only after finding no `macro_rules!` of that name (nor `#[macro_use] extern crate`) in the crate. For Go `env`, a name the file uses but does not declare gets a row that Kibi drops only when no other file of the package (its test files only for a test file) can read the environment or none names it, and every import other than `os`, `syscall`, x/sys and cgo gets a row that Kibi drops only when the path is no package of the project, or that package cannot read the environment: a package of the project is a relative path, a path under the module path of any `go.mod` in the project or under a local `replace`, or, with no `go.mod`, a folder of that path above the file; it can read the environment when one of its files (not its tests) spells a getter, cgo or `//go:linkname`, or imports a package of the project that can. So `config.Get("X")` over a package that wraps `os.Getenv`, `var Get = os.Getenv` there, or a package-level value it reads at init is refused; third-party packages are not followed. A C# bare call is listed under a type only when the file declares the method, or one `using static` System type has it; `@` verbatim identifiers are read without the `@`. A C# member access on a local, parameter, field or property named like a System type (`Environment`), on a type parameter (`class C<Environment>`, `void M<Environment>()`), on a pattern, `out`, deconstruction or query variable declared in the same member (anywhere in the file for top-level statements), or on a type the file declares, is on a value of unknown type (`*.Exit`), and so is a method group on an expression Kibi cannot name (`Process.GetCurrentProcess().Kill`, `new Process().Kill`, `ps[0].Kill` are `*.Kill`). Rust paths are read without comments between segments, and a plain `type` alias is followed. A function or method used as a value (`logf := logrus.Error`, `apply(logrus.Error)`, a C# method group, also cast or in a conditional, a Rust path such as `env::var` passed on) is listed in `calls`. Rust `#[cfg(...)]` items are read as if every build compiled them (`#[cfg(test)]` items are skipped): a name that gated items bind in several ways (`#[cfg(unix)] use std::process as p;` next to `#[cfg(not(unix))] use mycrate::process as p;`) resolves to each of them, a gated binding may also leave the outer scope's binding in force, and a `cfg_attr` counts as the attributes it applies (`derive(Debug)` is read as usual, `tokio::main` refuses `calls`). `excludes` and `subset_of` then hold in every build; `includes` and `eq` may count a member only some builds compile, as they do for a call in an `if`. A name computed at run time (`os.Getenv(name)`), the whole environment (`os.Environ()`, `System.getenv()`, `os.ExpandEnv`, `Environment.ExpandEnvironmentVariables`), a getter handed on as a value (`g := os.Getenv`, `System::getenv`, `let f = env::var`), a Go dot import, a Java static wildcard or a Rust glob import that could bring a getter or call into scope, a call with no static name (`fs[0]()`, `<T as Tr>::m()`), reflection (Go `reflect` calls such as `MethodByName` and `plugin.Open`, Java `Class.forName` and `Method.invoke`, also fully qualified, C# `Type.GetType`, `Assembly.Load` and `CreateInstance`), C# `dynamic` anywhere (for `calls` and `env` alike, since a reflective call can read the environment), a C# `#if` block, a Rust `cfg_attr` whose attributes cannot be split, for Rust `thrown` any macro invocation (`println!` included), for Rust `calls` a macro other than a standard one or a known crate's formatting macro, also nested in one (the calls in a standard macro's arguments are read: `println!("{}", f())` lists `f`), and for both an attribute macro (`#[tokio::main]`) or derive outside the standard library, for Rust `env` a macro whose arguments mention an environment getter (`eprintln!("{}", env::var("X")?)`), and for `string_args` a macro whose arguments mention the callee fail the read with their place. So do, since the call may be a claimed callee or a getter under a name the file does not show: Go cgo (`import "C"`), `//go:linkname` and any `Environ()` method (`exec.Cmd.Environ`) for `env`; a Java method named like a JDK callee (`getenv`, `exit`, `halt`, `exec`, `load`, `loadLibrary`) on a receiver of unknown type (`Runtime.getRuntime()` is known, a `var` local or an inherited field is not), for `calls` and, for `getenv`, `env`; a C# bare call the file cannot place (a base type's, or one of a `using static` in this file or a project-wide one such as `global using static System.Environment` or `<Using Include="System.Environment" Static="true" />`) for `calls`, an environment getter's name it cannot place (bare, as a method group, or on a project-wide alias) for `env`; a Rust getter's name on a path that cannot be followed (`crate::`, `super::` out of the file, a module file, another crate's `var`) for `env` and `calls`; and for Rust `env`, `imports` and `string_args` any macro other than a standard one or a known crate's formatting macro (`anyhow!`, `log::info!`), such as the file's own `macro_rules!` or `include!`, an `env!` nested in another macro, or (for `env` and `string_args`) any attribute or derive macro outside the standard library (clap's `#[arg(env = "X")]`, `#[derive(FromEnv)]`); a Rust glob of a project module or another crate (`use inner::*`) for a bare getter name and the standard macros; and a Rust alias Kibi cannot follow or a qualified-self callee (`<T>::new`) for `string_args`. A file that does not parse is refused with its line. - **PHP, C, Bash and Terraform/HCL.** These go through the same plugin and need their packs (`kibi-lang-php`, `kibi-lang-c`, `kibi-lang-bash`, `kibi-lang-hcl`). Files are matched by extension: `.php`; `.c` and `.h` (a header is read as C); `.sh` and `.bash`; `.tf` and `.hcl`. - *PHP* reads every extract; `property` reads literal array keys (`'acl' => 'private'`), named arguments, property and constant defaults, enum case values, `define()` and writes such as `$config['acl'] = 'private'`; a promoted constructor parameter holds what each `new` passes, so it refuses. Numbers are compared by value (`0x10` is `16`). In a merge the last literal value wins, and an operand Kibi cannot read after it refuses; a duplicate key, `compact()`, `array_combine`, `array_fill_keys`, `array_flip`, a negative implicit key, and a write through a reference (also a reference element or destructuring `['acl' => &$a]`, a slot passed to a constructor or any function that is not a by-value builtin), `unset`, `foreach` by reference, `++`, `ReflectionProperty::setValue`, `ArrayObject::offsetSet` and a second `define()` of a name refuse. Class names resolve through the namespace and `use` imports (group uses too, each from the line it appears on) and are listed in full (`App\Mail\Mailer::send`, `*.send` for an unknown receiver); function names are listed in lower case, and `die` and `exit` are both listed for either. PHP names ignore letter case, so `excludes` refuses a member that differs from an excluded item only in case. An unqualified call inside a namespace may reach the namespace's own function, so it is refused unless no project file that opens PHP code (any extension, dot folders and `vendor` included) declares that function there. `env` reads `getenv`, `apache_getenv`, `env()`, `Env::get` and `filter_input(INPUT_ENV|INPUT_SERVER, ...)`, and literal subscripts of `$_ENV` and `$_SERVER`; a call on a class that may extend `Illuminate\Support\Env` is refused while a project or `vendor` file names that class (group uses too), and so is one on `new static` or on a trait's `$this`. Callables handed to `array_map`, `call_user_func` and the like are followed; a caught exception passed on as an argument is not a callable when it goes to a PHP exception's constructor or a by-value builtin (`error_log`, `get_class`); any other function or method may replace it through a reference, and so may an `include` in the catch body, so the read refuses. Only a builtin's `callback:` named argument is a callable. A dynamic call, `eval`, `create_function`, a string `assert`, a getter's name in a string, `$$name`, `$GLOBALS`, `get_defined_vars()`, Reflection and its `invoke`-like methods (on any object), `class_alias`, `FILTER_CALLBACK`, `PDO::FETCH_FUNC`, a SOAP `addFunction`, a `new` of a computed class with arguments, an include through a stream wrapper (`data://`, `phar://`), a caught exception whose variable may be replaced (`&$e`, `extract`, `$$`), and an environment getter called on an object Kibi cannot name in a file that names `Env` refuse, and so do a `*.m` member, a named first argument and a first-class callable of the callee (`exec(...)`) for `string_args`. In a closure that the file rebinds (`->call`, `bindTo`, `Closure::bind`), `self` and `parent` are unknown. Backticks are listed as `shell_exec`. For `property`, a slot of the key passed to a function or method other than a by-value builtin (it may take it by reference), a `foreach` that writes the key, a regex named group of the key, and an array rewrite (`str_replace`, `array_map`, `array_change_key_case` and the like) in a file that names the key refuse. Strings are bytes read as UTF-8 (`"\xc3\xa9"` is `é`); a float joined into a string refuses, since PHP writes it with its own precision. - *C* reads `env`, `imports`, `calls`, `string_args` and `property` (the designated fields of an initializer, `.field = value`, GNU `field:` labels too; a field set twice refuses); C has no thrown errors. Only initializers are read: a later `cfg.field = value` is not, and a value is read as written, not converted to the field's type (a bit-field or a narrower integer may hold another value). An initializer written in a macro (`TLS_DEFAULTS`), a union in the file or an included header, and an array designator that is not a number refuse; an array of designated structs is read. Numbers are compared by value (`0x10`, `1'000` and `16u` are `16`), and a character constant refuses. Digraphs are read; trigraphs, a line splice inside an identifier and a backslash followed by blanks refuse. Macros the file defines are expanded, respecting `#undef`, and the names in a macro's body are listed; a header guard with a body is a macro. A function-like macro expands only where `(` follows it; elsewhere its name is the function of that name. A macro defined or undefined under a condition, `#pragma push_macro` or `redefine_extname` (also through `_Pragma`), one that uses `#` or `##`, and an `#if` block that adds members refuse; a macro whose body is a literal does not. `#include`, `#import` and `#include_next` are read. An include may bring macros or function pointers, so it is refused unless the header (a quoted one next to the file, an angle one when any project file has that path) defines no macro the file uses, other than upper-case ones whose body calls nothing (pure builtins such as `__builtin_expect` aside), pastes nothing and names only their parameters, keywords and other such macros (one that ends with a name it does not define, such as `#define HASH SHA256`, counts where the file calls it), and no function pointer it calls (in any spelling, a function-type `typedef` too), and holds no `asm`, `alias`, `weakref`, `__REDIRECT`, `typeof` or symbol-renaming pragma. A call through a variable, a function pointer or a struct field (`ops->exec`), `environ`, a call to an unknown function whose name looks like an environment getter, a `/proc/.../environ` path, a three-parameter `main` or constructor (K&R and macro-written ones too), inline `asm`, a function declared inside a block, a getter handed on as a value, a string with an embedded `\0`, a positional struct initializer and a field set twice (also through a nested designator) refuse. Code in an included file (a header's `static inline` function, an `#include`d `.c` file) is that file's: list it in `files` too. - *Bash* reads `env`, `imports` (`source` and `.`, with the `$(dirname "$0")` script-folder idioms resolved, also through a variable set once at the top, `DIR="$(cd "$(dirname "$0")" && pwd)"`), `calls` and `string_args`. A variable the script expands but never sets is an environment read, and so are `~` (`HOME`), `test -v NAME` and arithmetic in an array index; one it sets only on some paths, or in an assignment with a redirection or in a background job, is refused as a read the environment may supply. Commands run through `sudo`, `env`, `timeout` and similar wrappers are followed; a runner whose command Kibi cannot name refuses, and so do the first arguments `xargs` and `find -exec ... {}` supply. `eval`, `sh -c`, a shell reading its script from input or `/dev/stdin`, `trap` code, `alias`, any mention of `BASH_ALIASES`, `BASH_CMDS` or `BASH_ARGV0`, a prompt variable set to anything but plain text, `${x@P}`, a command name Kibi cannot read (`$cmd`, `"${cmds[0]}"`), arithmetic on a value that is not certainly a number (a value such as `a[$(rm -rf x)]` runs code), a quoted subscript holding `$(...)`, `coproc`, a `/proc` environment path in any form (a glob, a variable, `cd /proc/self`), BSD `ps e`, a word splice across lines, a here-document whose end line has trailing blanks, and a `source` of a computed path (for `env`) refuse, and so does a backtick or `$[ ]` in an unquoted here-document. A `source` relative to `$0` resolves to the script's folder, and is refused when another project script may source this one (by name, a computed path or a glob: `$0` then names that script) or after the script changes directory. Commands a sourced file runs are that file's, as with a C include: list it in `files` too (an alias or function it defines is read there). Code handed to another interpreter (`python -c`, `awk`, `sed e`) is not read, except that an `env` read refuses when the script holds text that reads the environment anywhere (`ENVIRON`, `os.environ`, `%ENV`, `ENV[...]`, `getenv(`, jq's `env`), or hands an interpreter a program from a variable. `unset` of a name some function declares `local` (or `declare`s), `local -I` and `shopt localvar_inherit` refuse for `env`. - *Terraform/HCL* reads `property` only: the literal values of an attribute or object key anywhere in the file (strings with their blanks, numbers as exact decimals, bools, `null`, tuples, plain heredocs with their line ends). Keys are compared after Unicode NFC, as Terraform does, identifiers included. A value that needs evaluation (variables, functions, templates), a computed key (one with `~` strip markers or that NFC may compose with an interpolation too), a duplicate key (also of an object holding it, where the later one wins), a `for` object, `jsondecode` and similar functions, a value evaluation may drop (a conditional branch, an indexed or selected collection, a `for` body, a splat, a `coalesce` or `try` argument, an operand of `==`, `!`, `&&` and other operators, a template `%{ if }` or `%{ for }`), a `merge` whose later argument Kibi cannot read or may replace the key's top-level object, a list expanded into `merge(...)`, a typed variable `default` (or `optional` default) the type converts, a decomposed (non-NFC) attribute name in a type, a number longer than Terraform's 512-bit precision, and a Terragrunt `include` block refuse, and so does any Terraform `override.tf`, `*_override.tf` or `.tofu` file in the same folder, whether or not the read includes it, since it may replace the value, and a `terragrunt.hcl` there with a `generate` or `include` block, which may write one. Values are read as written: a block that `count`, `for_each` or `dynamic` may create zero or many times still shows its values. A folder Kibi cannot list refuses for the same reason. A computed key is allowed only in the `for_each` of a block that takes one (`resource`, `data`, `module`, `dynamic`, `import`, `provider`, `ephemeral`), where keys name instances. - **Importing the app.** The `routes`, `validator` and drizzle readers import the module, so it must load without side effects (no `listen`, no database connection at import). Export a factory or a wrapper when the app needs dependencies. Every reader is exact or refuses: a member Kibi cannot read statically (`process.env[name]`, a dynamic `import()`, an `ALTER TABLE` form it does not know, a router mounted on a pattern) fails the read and names the file and line, so a set claim is never decided over a set Kibi only partly saw. The test leaves no certificate (or `sourceCertificate({testId})` from `kibi-cli/proof-certificates`): Kibi reads the source at ingest and stores its own read as the certificate. What the set fact means depends on its property and operator: | Fact | The source must | | --- | --- | | operator `eq`, `includes`, `subset_of` or `excludes` | have exactly, at least, only, or none of the members | | property `required_fields` | have each member as a required, non-null field of every selected table or object; a bare name (`id`) applies to every table, including tables added later, while `table.field` names one table. Only `eq` and `includes` | | property `nullable_fields` | have each member nullable. Only `eq` and `includes` | | property `middleware` | run the members (by the operator) before every selected route | The `references` reader's members are names, so for it Kibi matches them by segment (`.`, `/`, `::`) in the direction that can never prove a claim the code does not hold: - `excludes` fails on every member that is, or may be, an excluded item: the item itself, a member under it (`java.sql` excludes `java.sql.Connection`; `github.com/labstack/echo/v4` excludes `github.com/labstack/echo/v4/middleware`), a member under the prefix of an item ending in `*` (`java.sql.*`, `os.*`), a wildcard import that may bring the item in (`java.sql.*` for `java.sql.Connection`), a shorter name the item ends with (`File.delete` for `java.io.File.delete`), a longer name ending in the item at a segment boundary (`checkNotNull` excludes `Preconditions.checkNotNull`), and a call on a receiver Kibi cannot name (`*.delete` may be `java.io.File.delete`). The last four are refused with the member, the item it may be and the files read: Kibi cannot decide the claim for them. - `includes` holds only on a member that certainly is the item: the item, a member under `X.*`, or a member ending in `.m` for `*.m`. A `*.m` never satisfies `X.m`, and `java.sql.Connection` does not satisfy `java.sql`. - `subset_of` allows a member only when it certainly is an allowed item, so `os/exec` is not allowed by `os` (write `os/*` for anything under it), and `*.m` only by `*.m` itself. - `eq` compares spellings, as for every other reader. PHP function and class names ignore letter case, so for a PHP read `excludes` also refuses a member that matches an excluded item only when letter case is ignored (`Exec` for `exec`). `includes`, `subset_of` and `eq` stay exact. A references read decides a claim only for the files it reads. A proof is rejected when a symbol the test covers (`covered_by`) or a symbol that implements the claim's requirement lies in a file outside `files` (after `ignore`), naming the symbol and its file: a refused file cannot be dropped from `files` to prove a claim about it on other code. A claim whose subject key or claim text names a project file (`src/match.c`, a file name such as `utils.sh` that Kibi finds in the project, a path with a repository prefix such as `fzy/src/match.c`, another letter case, a slashed name without its extension such as `src/match`, or a quoted path with spaces) is also rejected when none of the files read is that file, so a claim about one file cannot be decided on another. A `string_args` read whose `callee` is an environment getter (`os.Getenv`, `os.getenv`, `System.getenv`, `env::var`, `env::var_os`, `Environment.GetEnvironmentVariable`, `getenv/2` and the like) sees only that getter's first arguments, so it cannot decide an `eq`, `subset_of` or `excludes` claim about what the code reads; Kibi refuses it and names `extract: env`, which reads every getter. `kibi prove` counts a test whose run passed but whose certificate or claim binding Kibi rejected as `refused`, not `passed`. A derived binding on a receipt whose `verification_scope` is not `end_to_end` says that the claim stays unproved until the requirement is tested end to end, and `kibi proof explain` lists each claim's bindings and rejections, and why a derived claim is not yet proved, whatever the requirement's proof status; signoff shows the same rejections. The receipt's binding covers what the read depends on: each file it parses, the list of files a glob matches, and the modules a drizzle schema, route table or validator imports (through relative imports, tsconfig `paths` including those inherited through `extends`, and workspace packages linked into `node_modules`). Change any of them and the receipt is stale. A claim a source proof derives is bound with scope `source`, so coverage and signoff show that the proof rests on project files Kibi read. A rule about what a set of files never does ("files under `src/ui/` never import `x`") needs no `implements` link. When a passing source proof proves every applicable claim, the production-symbol stage of the proof ladder passes with `scope: source_proof` and lists the proving tests in `sourceProofTests`, because the files the proof reads are what the rule constrains. Do not link one of those files to the requirement: that would claim the one file implements the rule. See [Production symbols](./proof-ladder.md#8-production-symbols). The certificate builders (`sourceCertificate`, `readProjectSource`) are in `kibi-cli/proof-certificates` from kibi-cli 2.33.0; a project that pins an older kibi-cli has to upgrade before its tests can import them. Sources also feed the other kinds. An arithmetic or smt `value_source` entry `{source: {...}, measure: count}` counts the members ("at most 40 routes"), and a rule domain `{source: {...}}` ranges a predicate over the members ("every route Kibi reads is guarded"); `readProjectSource` in `kibi-cli/proof-certificates` gives the test the same members. A rule predicate whose function is a test harness that drives the code (it calls the handler for each role) says so with `harness_for: [SYM-...]`; its claims are bound with scope `harness`. The semantic advisor models these statements for you: "Every route under /api must use requireAuth" (middleware, includes), "Every table must have id and created_at" or "Every table in schema.ts must have a required org_id column" (required_fields), "The deleted_at column of organizations must be nullable" (nullable_fields), "Every environment variable the app reads must be one of A, B or C" (subset_of), "The web app must never import node:fs" or "... @supabase/supabase-js" (imports, excludes), "The top-level keys of scenarios.json must be exactly groups and scenarios" (eq), and "The server must expose at least 30 routes under /api/orgs" (count). A field claim needs a schema word (table, object, schema, row, record, model, entity, type, payload, DTO, or field, column or property next to the names): "Every organization must have an owner" is about membership and stays a behavioural claim. `kb_model` in requirement mode writes the same set facts when you pass `operator` (`eq`, `includes`, `subset_of`, `excludes`) and a list `value`. ### Temporal claims on state machines A state_machine set fact can name `reachable_pairs` (`from->to` pairs joined by a path of one or more transitions) and `required_waypoints` (`from->to via state`: the target is reachable and every path to it passes through the state), and any machine projection can use `includes`, `subset_of` or `excludes`. "A cancelled invoice can never become paid" is a `reachable_pairs` fact with `excludes` (and "A member can never become owner", with no machine named, one on subject `workflow`); "Every path from draft to paid must pass through approved" is a `required_waypoints` fact. A failure names the path or the state: ``` rejected: a path from draft reaches paid without passing through approved ``` ### What `proved` covers A requirement is **proved** when it is tested end to end and every applicable claim (every normative claim of its inventory; nonlogical context spans are not claims) has a derived, code-scope binding from a fresh, re-checked certificate. Coverage reports `claimSummary` per requirement (applicable, proved, attested, tested and unresolved claims), lists `unprovedClaims`, and `kibi proof explain` shows each claim with its bindings. A requirement whose claims are only partly proved is tested, and the table and the HTML report show `n/m claims proved`. A claim that is not yet modeled keeps the requirement below proved until it is. `arithmetic` and `smt` certificates pay off only when the requirement rests on typed numeric facts (bounds, limits, counts). For an enumerable domain use `exhaustive` or `typecheck`; for decisions, lifecycles and formats use `rule`, `state_machine` or `regex`; for routes, schemas, configuration and the references the code makes use `source`. Kibi never takes a certificate's word for it. At ingest it re-checks the certificate (every member listed once and passed; the arithmetic decided by the same interval reasoning as contradiction checks; the solver re-run), and it checks the workspace. For an exhaustive proof Kibi loads the `domain_source` symbol's export itself (with bun when it is on `PATH`, else node with type stripping) and needs the certificate to cover exactly its members (or, for non-primitive members, as many of them), so a hand-listed subset is rejected; the proof file must also import the symbol. A typecheck witness must import the domain and be the file in the workspace (its sha256), and Kibi compiles it itself with the workspace's TypeScript under fixed strict options, so a test cannot report a pass the compiler would not give. Imports resolve the way the nearest `tsconfig.json` says (`module`, `moduleResolution`, `paths`, ...), and the declaration files that tsconfig includes (a `reset.d.ts`, for example) are part of the witness program; without one, NodeNext. When the test's own compile failed, the rejection adds the first error Kibi's compile of the witness reports, or that Kibi's compile accepts it. TypeScript 7 ships without the compiler API, so Kibi falls back to an older `typescript` further up the workspace and otherwise asks for `typescript@6` as a dev dependency. A contract without `proves` rests on the witness alone, so the witness must also contain an exhaustiveness check, a `never` type or a `satisfies` map, read from its syntax (the word in a comment does not count). With `proves`, Kibi checks each claim with a witness it writes itself, and a rejection names the fields that are missing, optional or nullable. Arithmetic and SMT certificates must match their `constraint_source` facts as described above. The receipt (`kibi.proof-receipt.v2`) records `kind`, `evidence_level`, the certificate and its digest (the sha256 of its canonical JSON, computed by `code_certificates.pl`), or `certificate_rejection` with the reason. Whenever it reports evidence, Kibi re-checks the stored certificate's digest and structure (and re-decides an arithmetic claim); the solver and workspace checks run at ingest only. The digest is an unsigned hash: it catches edited or corrupted receipts, not deliberate forgery, which review of the receipt diff is for. A receipt that claimed proved but no longer re-checks counts as tested, and coverage and `kibi proof explain` name the test and the reason (`certificateRejections`). A certificate strengthens end-to-end evidence; it never replaces the journey test. `required_evidence: proved` makes the evidence-floor rule demand proved, and its finding lists the claims no certificate derives (`gapDetails.unprovedClaims`). A `bun test` proof step that runs a `*.proof.test.*` file is never satisfied by reused unit results, because reuse would leave no certificate. ## Integration configuration Evidence production is configured in tracked, Kibi-managed `.kb/proof/integrations.json`: ```json { "version": "kibi.proof-integration.v1", "integrations": [ { "id": "self-proof", "producer": "command", "command": ["node", "scripts/run-proof-producer.mjs"], "artifact": ".kb/proof/runs/self-proof.json", "targets": ["default"], "description": "Packed end-to-end step commands" }, { "id": "web-e2e", "producer": "playwright", "command": ["npx", "playwright", "test"] }, { "id": "api-tests", "producer": "junit", "command": ["pytest", "--junitxml=.kb/proof/runs/api-junit.xml"], "artifact": ".kb/proof/runs/api-junit.xml" } ] } ``` - `command` is executed with `shell: false`, exactly as configured. - The child environment always includes `KIBI_PROOF_RUN=1`. Runner configurations that must behave differently under a proof run (for example, Playwright `retries: 0`) should branch on this stable marker instead of guessing which output-path variable implies a proof run. - `producer: command` lets Kibi synthesize the envelope from the process outcome (aggregate-run provenance). One process runs the steps of every selected test, so by default one failing step fails every test in the run. To have each test judged by its own steps, the command writes a `kibi.proof-test-report.v1` to the path in `KIBI_PROOF_TEST_REPORT` (see [per-test attribution](#per-test-attribution-for-command-integrations)). - `producer: playwright` (or a custom id) expects the child to emit `kibi.proof-run.v1` at `KIBI_PROOF_OUTPUT`. - `producer: junit` / `tap` make Kibi convert the native report at `artifact` into bound proof results using each test's `proof_bindings`. - `description`, labels, and comments are cosmetic: editing them never invalidates proof. Execution-relevant edits (command, artifact, targets, options, bindings, contract) change the effective execution fingerprint and stale prior evidence. `kibi init` never creates this file, and agents never hand-write it. `kibi proof inspect --json` proposes a `command` integration for the detected test runner (the `package.json` `test` script when there is one) and returns `integrationPlan`, a hash-bound `kibi.migration-plan.v2` with one `proof_integration_configure` action, plus the `contractDefaults` a proof-bearing test's `proof_contract` uses. Review it, then apply it through Kibi: ```bash kibi proof inspect --json > inspection.json jq '{plan: .integrationPlan, approvedPlanHash: .integrationPlan.planHash, approvedActionIds: [.integrationPlan.actions[].id]}' inspection.json \ | kibi apply-plan --input - ``` MCP hosts pass the same three fields to `kb_apply_plan`. The plan binds the hashes of the files the proposal came from (`package.json`, lockfiles, runner configs) and is refused once one changed. A create plan is refused once the file exists; `kibi proof inspect --update <id> --json` plans adding or replacing one named integration and is bound to the file's current hash. `--command "<command>"` (space-separated words or a JSON argv array) proposes that command instead of the detected one, on a create or an update plan. A `command` integration judges each selected test by the exit code of the whole run, so when it runs the package's whole `test` script, any failing test anywhere fails every proof obligation that names it and a suite with unrelated failures proves nothing; `integrationPlanReason` says so. Narrow the command to the proof-bearing tests (`kibi proof inspect --update <id> --command "<command>" --json`) or have it write a per-test report (below). Greenfield repositories without a harness record proof integration as **deferred** — Kibi does not install test frameworks. ## The canonical artifact: `kibi.proof-run.v1` Most consumers never hand-write artifacts — `kibi prove` and its producers do. Direct `kb_ingest_proof` calls are an integration path for custom producers and agents. ```json { "version": "kibi.proof-run.v1", "producer": { "name": "kibi-playwright-producer", "version": "1.0.1" }, "executor": { "name": "playwright", "version": "1.57.0" }, "integration": "web-e2e", "command_argv": ["npx", "playwright", "test", "--project=chromium"], "code_snapshot": "<64-hex snapshot captured before the run>", "environment": { "os": "linux", "arch": "x86_64", "runtime": { "name": "node", "version": "v24.15.0" }, "artifacts": { "lockfile_digest": "<…>" } }, "run": { "outcome": "passed", "exit_code": 0, "started_at": "2026-08-30T09:00:00.000Z", "finished_at": "2026-08-30T09:02:03.000Z" }, "proof_results": [ { "symbol_id": "SYM-PW-4F2A9C61B7D03E85", "target": "chromium", "outcome": "passed", "binding": "native_case", "native_id": "tests/checkout.spec.ts:4:5 › checkout › accepts a card", "attempts": { "status": "complete", "entries": [{ "outcome": "passed", "duration_ms": 2415 }] } } ] } ``` Field contract: | Field | Requirement | | --- | --- | | `version` | Literal `kibi.proof-run.v1` | | `producer` | `{name, version?}` — the component that produced the artifact | | `executor` | Optional `{name, version?}` — the underlying runner | | `integration` | Configured integration id this run belongs to | | `command_argv` | Non-empty; must equal the integration's configured command | | `code_snapshot` | 64-hex; must equal the live snapshot captured before the run | | `environment` | Typed JSON object; Kibi canonicalizes and hashes it | | `run` | Run-level outcome, process exit code, ISO timestamps, optional `failure_phase` (`setup`, `collection`, `execution`, `teardown`, `infrastructure`) | | `proof_results` | 1–100000 results, each shaped as below | Each proof result: | Field | Requirement | | --- | --- | | `symbol_id` | Non-empty stable proof symbol (`SYM-*`) | | `target` | Ecosystem-neutral execution target | | `outcome` | `passed`, `failed`, `timed_out`, `skipped`, `interrupted`, or `errored` | | `binding` | `native_case` (individually observed) or `aggregate_run` (bound process outcome) | | `native_id` | Optional native runner identity (provenance only) | | `attempts` | `{status: "complete", entries: [{outcome, duration_ms?}]}` or `{status: "unavailable"}` | ### Attempt history is factual Adapters report facts, never improve them. When a source format cannot prove retry history, report `attempts: {status: "unavailable"}`. The strict `all_required_first_attempt` policy: - accepts complete history whose **first attempt** passed, - rejects any known non-passing first attempt, - **fails closed** on unavailable native history, - accepts `aggregate_run` results only through the single Kibi-launched process invocation itself (the process attempt), which is known first-attempt evidence when the run passed with exit code 0. ### Run-level outcomes are authoritative `run.outcome` — `passed`, `failed`, `errored`, `cancelled`, `timed_out`, `interrupted`, `no_results` — is evaluated independently of individual results. Under `all_required_first_attempt` a failed run never proves anything, no matter how many results passed before the failure. ### `own_results_first_attempt`: one failing case does not erase a suite A large end-to-end suite almost always has some failing or flaky case, and under the strict policy that one case fails every receipt of the run. A contract can opt into `success_policy: own_results_first_attempt` instead: - a run whose outcome is `failed` in the `execution` phase (or with no phase) is judged per obligation, so an obligation whose own `native_case` result passed on its first attempt is proved even though other cases failed; - the first-attempt rules above still apply to the obligation's own result; - `aggregate_run` obligations still need the whole run to pass, because they have no result of their own; - `errored`, `cancelled`, `timed_out`, `interrupted` and `no_results` runs, and failures in `setup`, `collection`, `teardown` or `infrastructure`, still refuse every obligation. `kibi-cli/playwright-reporter` marks a run that only failed test cases as `failure_phase: execution`; an error outside the test cases (config, global setup, a spec that fails to load) is `setup`, a global timeout is `timed_out` and an interrupted run is `interrupted`. Use the policy where the per-case results are native, as with the Playwright reporter; keep the strict policy where a run-level failure should block everything. ## Environments and fingerprints Producers provide typed environment dimensions (OS, architecture, runtime, container digest, lockfile digest, database image, device, deployment). Kibi canonicalizes the object and derives `environment_hash` itself. Each receipt stores the effective **execution fingerprint** and its components (contract, integration, command, bindings, producer). A receipt whose components differ from the test's current execution is stale, and the drifted components are named: - `kibi prove` prints `execution fingerprint changed since its previous receipt (integration, command)` for each re-proven test, and the JSON summary carries `fingerprintDrift` on that test's row. - `kibi coverage` and `kb_coverage` list the same names as `fingerprintDrift` on the test's `receiptEvidence` row, beside the `stale_proof_receipt` gap. - `kibi proof explain` prints `fingerprint drift for TEST-x: integration, command` and names the tests in the stale gap's reason. A test whose contract, bindings or integration cannot be resolved is not checked for drift; other rules report those. With `KIBI_PROOF_BINDING_MODE=strict-snapshot` only `kibi prove` names the drift, because every tracked change already stales a receipt by snapshot there. After upgrading, a receipt recorded before an integration edit reports `stale_proof_receipt`; run `kibi prove --stale` to refresh it. ## Receipt freshness scope By default a receipt stays fresh until something *it depends on* changes, not until any file in the workspace changes. Each receipt records a `binding_hash` over: - the test's `proof_contract`, - the test document itself (excluding its `proof_receipts` history and its `links`, so adding or reordering a link does not invalidate the receipt; receipts written before links were excluded stay current), and - the **code scope**: the current source-file content of every symbol in - the contract's `required_proofs` (the test's own executable code), - the test's `proof_bindings`, and - every production symbol linked `covered_by` this test. Editing any of those files (or deleting one) changes the binding, so that test's receipts go stale until `kibi prove` runs again. Edits elsewhere leave them fresh. Keep `covered_by` links accurate: they decide which production code a receipt vouches for. Set `KIBI_PROOF_BINDING_MODE=strict-snapshot` to instead bind every receipt to the whole-workspace snapshot it was proven on. Both the binding and the snapshot are computed from repository-relative paths and file contents only, so a CI runner and a developer checkout of the same commit agree: - the workspace snapshot names each file by its repository-relative path in Unicode NFC, so a checkout whose filesystem reports decomposed names hashes the same as one that reports composed names, wherever the repository lives; - a test document and each symbol's `sourceFile` are located through their normalized repository-relative path (`./a.ts`, `a\b.ts` and an absolute path inside the checkout all name the same file); - a `sourceFile` that leaves the repository (a `..` escape or another machine's absolute path) contributes the fixed marker `outside-workspace` instead of whatever that path holds on the current machine. ## Receipt history compaction Every `kibi prove` run appends one receipt per test, so a long-lived branch would otherwise accumulate receipts that can no longer change any decision. Ingest compacts each history as it appends (`kibi.proof-receipt-compaction.v1`), keeping only: - the newest receipt, and the newest passing receipt; - for the current binding and for the live snapshot, the newest receipt per verification scope and contract hash — exactly the receipts coverage selects from. Compaction is deterministic and only removes receipts: the kept receipts are the originals, in their original order, so every coverage decision is the same before and after. Stores written before compaction can be compacted once with `kibi proof compact` (`--dry-run` reports what would be removed). ## Per-test attribution for command integrations A `command` integration is one process. When it writes a `kibi.proof-test-report.v1` to the path Kibi passes in `KIBI_PROOF_TEST_REPORT`, each selected test is evaluated against its own steps: ```json { "version": "kibi.proof-test-report.v1", "tests": [ { "test_id": "TEST-checkout", "outcome": "failed", "steps": [ { "step_index": 1, "command": ["bun", "test", "checkout"], "outcome": "failed", "exit_code": 1 } ] } ] } ``` Tests whose steps all passed receive passing receipts even when the process exited non-zero; only tests with a failing step receive failing receipts. The `kibi prove` summary lists `attribution: "per_test"` and the `failedSteps` (test, step, command, outcome, exit code) for that integration. Attribution fails closed: with no report, a report that omits or duplicates a selected test, a test reported `passed` over a failing step, or a failing process whose report blames no test, the whole run is evaluated as one unit as before (`attribution: "aggregate"` with an `attributionReason`). A valid report in which every test passed is also `per_test`. Kibi's own `scripts/run-proof-producer.mjs` writes this report. ### `kibi proof run-steps` Projects do not need their own producer script. Declare each proof-bearing test's steps (argv arrays, no shell) in its own file under `proof/steps/`, named after the test id. `proof/steps/TEST-checkout.json`: ```json { "test_id": "TEST-checkout", "steps": [["bun", "test", "./tests/checkout.test.ts"]] } ``` One file per test means two branches that each add a test never edit the same file, so their merges do not conflict. A file whose `test_id` differs from its name is refused. When `proof/steps/` does not exist, Kibi reads `proof/steps.json` instead, one JSON array of the same entries: ```json [ { "test_id": "TEST-checkout", "steps": [["bun", "test", "./tests/checkout.test.ts"]] }, { "test_id": "TEST-cart", "steps": [["node", "--test", "tests/cart.test.js"]] } ] ``` To move an existing project, write each entry of `proof/steps.json` to `proof/steps/<test_id>.json` and delete `proof/steps.json`. and make `kibi proof run-steps` the integration's command: ```json { "id": "unit", "producer": "command", "command": ["npx", "kibi", "proof", "run-steps"], "targets": ["default"] } ``` It runs the steps of the tests `kibi prove` selected, each distinct argv once (in its own process group, with a timeout from `KIBI_PROOF_STEP_TIMEOUT_MS`), and writes the per-test report, so each test gets its own receipt. Ctrl-C during `kibi prove` stops the whole process group of the producer, so no test worker is left running. ## Trust boundary Local proof evidence is trusted as part of the local execution environment. An out-of-process adapter can lie just as an in-process reporter can lie. Kibi's guarantees are about binding, policy, freshness, and history — not independent attestation. The envelope is designed so CI identities, signatures, or attestations can be added later. ## Representative recipes - **Web UI (Playwright, optional native producer):** register `kibi-cli/playwright-reporter` in `playwright.config.ts`; add a `playwright` integration; the reporter emits `kibi.proof-run.v1` with producer name `kibi-playwright-producer`. Obligations map to `SYM-PW-*` case symbols. Kibi does not depend on Playwright. - **API (pytest via JUnit XML):** run `pytest --junitxml=…` with a `junit` integration; author `proof_bindings` mapping native test ids to symbols; attempt history is `unavailable` (standard JUnit XML has no retry data). - **JVM/.NET libraries:** Maven/Gradle/dotnet produce JUnit XML; same adapter path as pytest. - **Go/Rust:** `go test -json` or TAP-consuming harnesses via the `tap` integration; TAP has no retry history, so attempts are `unavailable`. - **Database products:** a command integration that starts a cluster, migrates, writes, replicates, and reads; obligations bound with `aggregate_run` provenance. - **CLI tools:** a command integration running the installed binary and asserting observed behavior. - **Custom/proprietary runners:** emit `kibi.proof-run.v1` directly and call `kb_ingest_proof`, or wrap the run in a command integration. Examples live in [docs/examples/proof](examples/proof/) and are validated against the schema in CI. ## Common failures and fixes | Error | Cause | Fix | | --- | --- | --- | | `No proof integration configuration at .kb/proof/integrations.json` | Proof is not configured for this repository yet | Run `kibi proof inspect --json` and apply its `integrationPlan` with `kb_apply_plan` / `kibi apply-plan` | | `integration '<id>' … is not configured in .kb/proof/integrations.json` | A test names an integration the file lacks | Run `kibi proof inspect --update <id> --json` and apply the plan | | `artifact command_argv does not match the configured command` | Command drift | Run through `kibi prove` so the configured command executes | | `captured snapshot is not the live workspace snapshot` | Tracked files changed between capture and ingest | Re-run `kibi prove`; do not edit the tree mid-proof | | `run did not pass (outcome: …)` | Run-level failure despite passing results | Fix the run (setup/teardown/infrastructure); rerun | | `attempt history unavailable` | Source format carries no retry data | Accept aggregate provenance, or use a producer with complete history | | `missing proof result` | Producer never reported a required obligation | Ensure the obligation ran in the configured integration/target | | `proof_receipts is append-only` | History was rewritten by hand | Update via the engine (`kibi prove`, `kibi proof compact`); never edit history | | Every test of a `command` integration failed for one step | The command wrote no `kibi.proof-test-report.v1` | Write the report to `KIBI_PROOF_TEST_REPORT`; the summary's `attributionReason` says why it was not used | | Receipts stale after code changes | The edit touched code in a test's [freshness scope](#receipt-freshness-scope) | Re-run `kibi prove` for the affected tests | ## For agent workflows Bundled skill guidance is in `kibi-usage` → `resources/proof-first.md` (the short path from a recorded rule to `tested`) and `resources/proof.md` (`kb_skills` with `action: "load"` and `id: "kibi-usage"`, then `action: "read"`). Deterministic discovery: `kibi proof inspect --json`. --- # Plugin development URL: https://getkibi.dev/reference/plugins.html > Extend Kibi with capability plugins: the SDK, manifests, and plugin lifecycle. Kibi capability plugins extend seven host-owned seams without taking over validation, Prolog, mutation, or proof: 1. `kibi.semantic-classifier.v1` — lane / ambiguity classification over host propositions 2. `kibi.ontology-pack.v1` — predicate schemas and match candidates 3. `kibi.symbol-extractor.v1` — synchronous legacy symbol analysis 4. `kibi.symbol-extractor.v2` — asynchronous analysis with explicit completeness 5. `kibi.vocabulary-alignment.v1` — modeling-time vocabulary convergence: `rankSubjects` (reuse an existing subject or declare `new_subject`) and `compareClaims` (possible-duplicate candidates for review) 6. `kibi.check-policy.v1` — data-only `kb_check` policy: ownership and pattern-marker rules evaluated by Kibi (see [Check policy](#check-policy)) 7. `kibi.reference-extractor.v1` — what a source file references (imports, calls, environment variables, first arguments, thrown errors, property values), read without running it, for `source` proofs over languages Kibi does not read itself (see [Reference extractor](#reference-extractor)) Every capability is optional for third-party plugins: a plugin declares only the capabilities it provides, and plugins written before a capability existed keep validating and loading unchanged. The builtin plugin provides all six (its check policy is empty). This is distinct from **host plugins** such as `kibi-cursor`, `kibi-opencode`, `kibi-codex`, `kibi-zcode`, and `kibi-claude`, which adapt an IDE or agent host to Kibi's operation surface. Capability plugins never register MCP tools or Git hooks. ## Automatic builtin `kibi-plugin-builtin` ships with the standard CLI distribution and is always registered. It is **not** listed in `package.json` `kibi.plugins`. With no `kibi.plugins` config, only the builtin pack runs. ## Named export Activated packages must export a single named `kibiPlugin` binding that passes `validateKibiPlugin` / `defineKibiPlugin` from `kibi-plugin-sdk`. A `default` export alone is not accepted by the host loader. ```ts import { KIBI_PLUGIN_API_VERSION, defineKibiPlugin } from "kibi-plugin-sdk"; export const kibiPlugin = defineKibiPlugin({ apiVersion: KIBI_PLUGIN_API_VERSION, id: "example-ontology", version: "0.1.0", permissions: { network: false, metered: false, secrets: [] }, capabilities: { ontologyPack: { id: "example-ontology.pack", schemas: () => [], match: () => [], }, }, }); ``` Third-party plugins need only `kibi-plugin-sdk`. They must not depend on `kibi-cli` or `kibi-mcp` internals. ## Activation Declare the package as a project dependency and activate capabilities under `package.json`: ```json { "kibi": { "plugins": [ { "package": "kibi-plugin-jev", "capabilities": { "kibi.semantic-classifier.v1": { "mode": "augment" } } } ] } } ``` Rules: - Bare package names only (no paths, URLs, or aliases) - Package must appear in `dependencies`, `devDependencies`, or `optionalDependencies` - Resolution follows the project's package manager (npm, pnpm symlink, Yarn PnP) - `NODE_PATH`, global installs, and ambient ancestor packages are rejected ## Configuration surface `package.json#kibi.plugins` is the canonical activation and mode surface. Each entry names a bare package and the capabilities it may provide, with `augment`, `replace`, or `shadow`. That manifest is small, declarative, and validated before any plugin module is imported. Provider secrets stay in the environment, outside repository configuration. The manifest does not include `kibi.config.ts`, generic plugin options, plugin factories, or executable config. `kibi doctor` prints the parsed plugin rows (package, capability, mode, declared dependency) without importing the plugin package. First-party Jev secret and model diagnostics are known statically. Generic plugins do not get secret introspection. A configured package that is not listed in `dependencies`, `devDependencies`, or `optionalDependencies` fails that check. Add the package to one of those fields, or remove the `kibi.plugins` entry. Editing `package.json` remains the way to enable or disable a plugin. ## Modes Per capability, at most one `replace` is allowed. `augment` providers run in package activation order with capability-specific builtin positioning. `shadow` providers never affect canonical results; they may contribute comparison metadata only. | Capability | Builtin position | Notes | | --- | --- | --- | | Semantic classifier | First for `augment`; fallback for `replace` failure | External classifiers run only from the semantic advisor (`kb_model` mode `analyze`, CLI `semantic-advisor`) and `kb_compile_intent`. Valid empty `decisions[]` under `replace` is abstention (conservative `none`), not builtin fill. | | Ontology pack | Catalog starts with builtin for `augment` | `replace` excludes the builtin provider catalog. Valid empty `match()` is abstention (no builtin consult). Allowed wherever Kibi already matches ontology | | Symbol extractor v1 | Builtin first for supported files under `augment` | Legacy replacement and fallback behavior | | Symbol extractor v2 | Builtin first for supported files under `augment` | First claiming provider owns the result; partial, failed, or unsupported output never becomes a successful fallback | | Search hints | None from the builtin; the bundled `kibi-plugin-search-hints` is the default `replace` provider unless the project configures a provider or declines it | `replace` or `shadow` only; `augment` is rejected. Runs only from `kb_search`, and only when the intent answer abstained or its top score is below 0.44. A provider may name only the entities it was given, at most 20, scored in [0, 1] in score then id order; a failing, late (3 s first call, 0.5 s after) or invalid answer gives no hints and a diagnostic. Hints never change results, the answer layer or abstention | | Vocabulary alignment | Builtin always runs first; fallback for `replace` failure | External providers run only from requirement modeling (`kb_model` mode `requirement`, CLI `model-requirement`). `augment` refines only clauses the builtin left as `new_subject` and pairs it did not judge duplicates (it can add candidates, never remove them). A provider may only choose among the builtin-ranked candidates or `new_subject`; any other answer is rejected and falls back to builtin with `fallbackUsed`. Results are advice in the modeling plan, never check outcomes | Sync maintenance paths (`sync`, `check`, `kb_upsert`, `status`, proof, and related) keep deterministic builtin analysis for every capability and must never invoke external semantic classifiers, ontology packs, symbol extractors, or vocabulary-alignment providers. `kb_check` in particular never imports plugin code: `domain-redundancy`, `subject-key-identity`, and the other Prolog checks remain the pass/fail authority, and an activated check policy is read as JSON data and evaluated by Kibi's own `policy-ownership` and `policy-markers` rules. Async advisor / compile-intent / staged-symbol paths compose the registry (replace / augment / shadow); replace mode strips or overrides any sync-path builtin suggestions before results are returned. Maintenance source analysis uses the builtin extractor and explicitly activated, host-approved v2 source analyzers. Before importing an external source entrypoint, the host verifies its release-qualified package, runtime dependency and asset hashes. An unknown version, modified asset, missing dependency or escaping symlink fails analysis. Other plugin capabilities are not imported by this path. Semantic classification and ontology activation do not authorize their execution during maintenance. For staged checks, activation is read from captured Git trees. A commit changing source retains baseline source analyzers, so disabling a plugin in the same commit cannot bypass analysis. A configuration-only uninstall is permitted. Installed package files still have to match the host approval. ## Source analysis v2 An extractor exports `symbolExtractorV2` with `supports({ path, language })` and an asynchronous `analyze({ path, content, timeoutMs })`. The input is supplied snapshot text; providers must not substitute working-tree contents. The host owns the analysis deadline: `timeoutMs` is the budget it grants, set slightly below its own deadline, so a provider should return a `failed` result with its own timeout diagnostic before the budget elapses. The host abandons calls that outlive its deadline. Results carry `contractVersion: "kibi.symbol-extractor.v2"` and one status: | Status | Meaning | | --- | --- | | `ok` | Complete supported analysis; zero declarations is valid. | | `partial` | Some declarations were recovered; diagnostics and uncovered ranges explain uncertainty. | | `unsupported` | The provider cannot analyze this input; no symbol evidence is returned. | | `failed` | Operational or validation failure; no successful symbol evidence is returned. | Only after-side gaps the author can act on block a change. The committed (before) side is informational. On the staged side, `failed` and non-local diagnostics (syntax, parse, timeout, integrity) always block, because a removed brace can surface far from the edited lines. A local limitation, such as a Rust macro or a Python decorator, matters only when its uncovered range overlaps a changed line. Positions are one-based lines and zero-based UTF-16 columns, with exclusive ends. The host validates bounds against original content, including CRLF and non-BMP characters. Qualified names and signatures are declaration locators; authored KB IDs remain the authority for identity, ownership and proof. An ambiguous locator cannot transfer an existing ID. `kibi-plugin-treesitter` is optional. Every language's grammar is a data-only `kibi-lang-*` pack (`kibi-lang-python`, `kibi-lang-go`, `kibi-lang-rust`, `kibi-lang-java`, `kibi-lang-csharp`, `kibi-lang-php`, `kibi-lang-c`, `kibi-lang-cpp`, `kibi-lang-bash`, `kibi-lang-ruby`, `kibi-lang-hcl`, `kibi-lang-prolog`) installed next to it. The plugin pins each pack's version and grammar SHA-256 in its catalog and checks the bytes before loading them; a file whose pack is missing, another version or modified is refused with the install line, never skipped. Declare the exact qualified release and the packs you need as project dependencies and add: ```json { "kibi": { "plugins": [{ "package": "kibi-plugin-treesitter", "capabilities": { "kibi.symbol-extractor.v2": { "mode": "augment" } } }] } } ``` The package contains the built-in grammar WASM, the queries for every language, notices and integrity metadata. Analysis does not download parsers, start language servers or execute consumer build tools. It keeps a small pool of persistent workers that load each grammar once; a worker that times out or fails is discarded and replaced. Its deadline and resource limits contain parser failures; they are not a sandbox for arbitrary plugin JavaScript. After a reviewed package rebuild, `node scripts/qualify-source-analyzers.mjs --write` records its exact runtime closure; the command without `--write` verifies it. CI and packing must pass verification without rewriting approval. Update the package integrity manifest before recording approval, and requalify the relocated tarball. See [qualification](architecture/tree-sitter-qualification.md) and [delivery scope](architecture/multilingual-source-analysis.md). ## Trust boundary Explicit activation grants **code-execution trust** to the npm package. Module evaluation can run arbitrary top-level code. Kibi cannot enforce a third-party `network: false` declaration after import. `permissions.network`, `permissions.metered`, and `permissions.secrets` are **disclosure-only metadata** for operators and UIs, not an in-process sandbox. Plugins cannot bypass completeness checks, Prolog, mutation gates, or proof. Host validators stamp provider provenance (`pluginId`, mode, external, network/metered, fallback). ## Privacy and cost Semantic classifiers may receive claim keys, proposition text, and minimal role or signal context. Prefer local/offline providers when possible. Metered providers must declare `metered: true` and list required secret names. ## Testing - Unit-test classifiers/packs/extractors against `kibi-plugin-sdk` validators - Keep import side effects free of network I/O until an allowed capability call - For optional providers such as Jev, cover missing key, timeout, and malformed responses with injectable clients and offline fixtures ## Vocabulary alignment contract `rankSubjects({ clauses })` receives, per clause, a `claimKey`, the clause `text`, the `proposedSubjectKey` Kibi would otherwise declare, and builtin `candidates` (`subjectKey`, `score` in [0, 1], optional `title` and `requirementTitles`). It returns one decision per clause: `choice` is one of the candidate subject keys or `new_subject`, plus a `confidence` in [0, 1]. `compareClaims({ pairs })` receives pairs sharing a subject key (or predicate name) whose signatures differ, and returns `{ pairKey, sameObligation, confidence }` per pair. `sameObligation: true` only nominates the pair for review; exact duplicates are detected by the deterministic `domain-redundancy` check. Results are validated by `validateRankSubjectsResult` and `validateCompareClaimsResult`: foreign keys, duplicate keys, invented subjects, and out-of-range confidences are rejected before they reach the plan. ## Check policy `kibi.check-policy.v1` lets a plugin turn on stricter `kb_check` rules for the projects that activate it, without running plugin code during checks. The plugin's `package.json` names a JSON document: ```json { "name": "my-policy", "kibi": { "checkPolicy": "check-policy.json" } } ``` During `kb_check`, Kibi resolves each package activated for `kibi.check-policy.v1` (only `augment` is accepted), reads that file from inside the package root, and validates it with `validateCheckPolicyDocument`. It never imports the module. A policy that is missing, escapes the package root or fails validation blocks the check rather than silently switching off. The plugin should also export the same document as `capabilities.checkPolicy` so `validateKibiPlugin` and tooling can see it. A document has a `contractVersion` (`kibi.check-policy.v1`), a kebab-case `id`, a `title`, and two optional rule lists: - **`ownership`** (rule `policy-ownership`): symbols whose `sourceFile` matches `include` (gitignore-style globs, minus `exclude`) and whose title matches `symbolTitlePattern` must implement a current requirement linked `requires_predicate` to an asserted fact of one of `requirePredicates`. Symbols tagged `exemptTag` and executable test symbols are skipped. - **`markers`** (rule `policy-markers`): for every current requirement grounded in `patternPredicate`, the pattern is the fact argument at `patternArgument`. Each asserted `markerPredicate` fact whose `markerPatternArgument` names that pattern contributes the literal at `markerArgument`. Every source file implementing the requirement, plus its sibling files with the same stem and a `siblingExtensions` extension, must contain each marker (`_` and `-` spellings both match). Rule ids must be unique across both lists, predicate names are snake_case and argument indexes are zero-based. `kibi-plugin-ui` is the first-party policy. ## Optional UI design plugin `kibi-plugin-ui` (experimental) ships a check policy that keeps React and Angular components on their agreed design patterns. `/kibi-bootstrap` offers it when `kb_plan_bootstrap` finds production `*.tsx`, `*.jsx` or `*.component.ts` files (`pluginOffers`), unless the project already activated it or listed it under `package.json` `kibi.declinedPlugins`. It declares no permissions and has no runtime code path. The UI vocabulary it relies on (`ui_pattern`, `same_pattern`, `pattern_marker`, `ui_container`) and component-scope proof for pattern requirements are part of Kibi core. See [packages/plugin-ui/README.md](../packages/plugin-ui/README.md) and [ui-requirements.md](./ui-requirements.md). ## Reference extractor `kibi.reference-extractor.v1` serves the `references` source-proof reader for languages Kibi does not parse itself. A provider exposes `supports({path})` and `extract({path, content, extract, callee?, key?, timeoutMs?})`, and returns `{status: "ok", language, members, unresolved}` or a refusal (`unsupported` or `failed`, with a `code` and `message`). It lists only what it reads exactly and reports every construct it cannot read statically as an `unresolved` row with its 1-based line and text; Kibi then refuses the read and names those places, so a proof never rests on a guess. Results are checked with `validateReferenceExtractionResult` from `kibi-plugin-sdk`. The capability activates only in `augment` mode. A proof is evidence, so the host uses a provider only when its installed files match a release-qualified closure Kibi ships (the same list impact review uses); an activated but unqualified provider is reported and never imported. `kibi-plugin-treesitter` is the qualified provider today and reads Go, Java, C# and Rust; see [proving-requirements.md](./proving-requirements.md) for what each extract lists and refuses. ```json { "devDependencies": { "kibi-plugin-treesitter": "3.0.0", "kibi-lang-go": "1.0.0", "kibi-lang-rust": "1.0.0" }, "kibi": { "plugins": [ { "package": "kibi-plugin-treesitter", "capabilities": { "kibi.symbol-extractor.v2": { "mode": "augment" }, "kibi.reference-extractor.v1": { "mode": "augment" } } } ] } } ``` A Go, Java, C# or Rust project without a `package.json` creates one that only holds this list (`npm init -y`, then `npm install -D kibi-plugin-treesitter kibi-lang-go`). `kibi init`, `kibi doctor` and `kb_plan_bootstrap` suggest the plugin and the packs when such sources are tracked and it is not active for proofs, and `kibi doctor` names a pack that is missing or not the version the installed plugin pins. Only files people write count toward a pack. A file matched by a `package.json` `kibi.generatedPaths` glob, marked `linguist-generated` or `linguist-vendored` in `.gitattributes`, or one that opens with a generator marker (`@generated`, `Code generated ... DO NOT EDIT`, `auto-generated`), counts only when the KB references it, for example as a symbol's `sourceFile` or in a proof contract's `files`. A pack the project does not want can be declined on its own: ```json { "kibi": { "declinedLanguagePacks": ["kibi-lang-cpp", "kibi-lang-bash"] } } ``` `kibi.generatedPaths` takes gitignore-style globs for codegen output that has no header or attribute (`"generatedPaths": ["src/api/**", "!src/api/index.ts"]`); a `!` pattern, like `linguist-generated=false`, marks a path as hand-written. The same rules exempt generated files from the commit gate's requirement-link check (see `kibi check --staged` in the CLI reference). Kibi then stops suggesting a declined pack, and `kibi sync` and the staged check treat files in its language as files no plugin reads: symbols there are placed by text match, and a staged change to one gets a whole-file review instead of blocking on the missing pack. A generated file whose pack is missing gets the same review. A pack declined in the same commit as a source change in its language takes effect from the next commit, like other analyzer settings. ## Search hints plugin `kibi-plugin-search-hints` implements `kibi.search-hints.v1` with the bundled, MIT-licensed potion-retrieval-32M static embedding (int8, about 33 MB) and a pure JavaScript tokenizer checked against the upstream one. It needs no network, native code or model download. It ships with Kibi and is on by default: a project that names no `kibi.search-hints.v1` provider in `kibi.plugins` and has not declined the plugin gets it as the `replace` provider, loaded from Kibi's own install. Its provider stamp shows `external: false`; a provider the project configured shows `external: true`. A `kibi.plugins` entry for the capability, in any mode and from any package, takes the place of the default. The embedding is English-only. Turn the default off when the knowledge base is not written in English, when the environment does not allow a bundled model, or when another provider is configured instead, by listing the package in `kibi.declinedPlugins`: ```json { "kibi": { "declinedPlugins": ["kibi-plugin-search-hints"] } } ``` On every decision search, the host sends the question and each decision with the scenarios, tests and facts it links (title, statement and body, up to 2000 characters each; up to 50,000 entities), fuses the scores of the decisions with the word ranking, and lists up to seven decisions related by meaning as `queryAnalysis.hints`. Entity vectors are cached under Kibi's runtime directory and rebuilt only for entities whose text changed. The first call in a process may take 3 seconds while vectors are built; later calls get 0.5 seconds, and a slower provider leaves that search ranked by words alone. Bootstrap does not offer it: it is already active. See [packages/plugin-search-hints/README.md](../packages/plugin-search-hints/README.md). ## Optional Jev provider `kibi-plugin-jev` implements `kibi.semantic-classifier.v1` and `kibi.vocabulary-alignment.v1` via TypeSafe Jev (`@typesafe-ai/sdk`). Each is activated separately. It is **not** a default CLI or MCP dependency. - Install and activate explicitly (see [install.md](./install.md)) - Set `TYPESAFE_API_KEY` via Kibi env bootstrap (same for every MCP host): ```bash mkdir -p ~/.config/kibi printf '%s\n' 'TYPESAFE_API_KEY=...' >> ~/.config/kibi/env ``` Optional project override: `<workspace>/.env.kibi`. Process env wins; `KIBI_ENV_FILE` replaces the project path; legacy `.env` fills gaps only. Those workspace files may set only provider secrets and `KIBI_JEV_*` settings; Kibi ignores other `KIBI_*` keys and process variables there (see [Environment files](cli-reference.md#environment-files)). Never store the key in `package.json`. Restart long-running MCP after changes. - Optional `KIBI_JEV_MODEL` (default `jev-latest`; empty or whitespace is unset) - Optional `KIBI_JEV_TIMEOUT_MS`, a positive integer of at most 120000. Malformed values fail with a provider diagnostic that includes the effective model and not the API key - Explicit `JevSemanticClassifierOptions.model` and `timeoutMs` override those environment defaults. They are a programmatic constructor API, not fields in `package.json` - Importing the package, or leaving it installed but inactive, performs no TypeSafe client or network call - On failure Kibi falls back to the builtin classifier with an advisory warning - Requirement modeling (`kb_model` mode `requirement`) does not invoke the classifier. External semantic classifiers run only from the semantic advisor (`kb_model` mode `analyze`) and `kb_compile_intent` - Vocabulary alignment (`rankSubjects` as a `choice` over the builtin top 5 plus `new_subject`; `compareClaims` as a `noul` per pair) runs only from requirement modeling (`kb_model` mode `requirement`), and only when `kibi.vocabulary-alignment.v1` is activated - Live tests require both `KIBI_JEV_LIVE_TEST=1` and `TYPESAFE_API_KEY` - `kibi doctor` reports first-party Jev secret source labels and model/timeout without importing the plugin or leaking values See also [packages/plugin-jev/README.md](../packages/plugin-jev/README.md). --- # Agent onboarding URL: https://getkibi.dev/reference/agent-onboarding.html > The copy-paste discovery snippet that lets any coding agent find and use Kibi's interfaces. This repository uses Kibi. Initialize repository infrastructure with `kibi init`. Then ask the agent to “Bootstrap Kibi for this repository.” The agent first inspects `kb_status.bootstrap` and follows its typed `nextAction`, then routes the request to `kibi-bootstrap`. That skill first interviews the human about knowledge sources outside the code, then calls `kb_plan_bootstrap` with the declared sources and cited intent claims; further questions come only from a `needs_context` result. It shows the hash-bound plan, obtains approval, passes the unchanged plan to `kb_apply_plan`, and finishes with `kb_check` and `kb_status`. On a repository whose knowledge base was written by an older Kibi (a `.kb/config.json` and no `.kb/manifest.json`), the typed next action is `kibi migrate --yes`, the same step `kibi doctor` names: do not run `kibi init` first, because it would claim the latest schema and skip the legacy migration steps. The stable onboarding contract is typed status plus the named workflow skill. Skill manifests and resources are host plumbing for advanced integrations; they are not a prerequisite for ordinary bootstrap requests. Advanced hosts may call `kb_skills` with `action: "list"` and `action: "load"` (CLI: `kibi skill`) to discover that plumbing; ordinary onboarding follows typed status and the named skill. For general Kibi work, load the bundled `kibi-usage` skill as the shared source-first guidance. Its body is the core arc (search for prior intent, edit, record, check, commit); read its resources with `kb_skills` (`action: "read"`) when a task needs a topic it lists. Follow the loaded skill guidance and current operation schemas. Do not treat a package `skills/` directory as implicitly loaded by the host. Do not bypass Kibi's normal authorization or mutation safeguards. Skills are bundled only. Remote install, marketplace install, and script execution are not supported.